AJAX issues (Cannot get ajax to successfully work)

2019-03-06 00:05发布

问题:

I asked a question earlier today with little luck: AJAX within a foreach loop

i was put on the right path but the answer provided has got me more confused than ever. Whenever i click on my anchor tag with the ajax call, nothing happens. When i go into console view and check the network tab, it says the call was a success. when i go further into the call details it shows all the data i sent and the page it went too. The code on page_id=252 does not fire whatsoever.

I am using wordpress for this assignment. I am using custom templates to hold my PHP code. not a plugin.

I have two pages:

Index.php
ajaxcall.php

Index.php (?page_id=## is default permalinks to my wp pages. this location is valid.)

    <script type="text/javascript">
    function onClickingThis(rem_opt,vidid){
      $.ajax({
          url: '?page_id=252', 
          type: 'POST',
          data: {action: 'update_this_func', remove_option: rem_opt, uservideo_id: vidid },
          dataType: 'json',
          success: function(response){
            console.log('works');
          }
      });
    }
</script>

// all my php code, for everything on the page.
<a href="#"  onclick="onClickingThis(0,1)></a>

ajaxcall.php

function update_this_func(){
$remove_option = $_POST['remove_option'];
$uservideo_id  = $_POST['uservideo_id'];

global $wpdb;

$wpdb->query("UPDATE " . $wpdb->prefix."uservideo
              SET is_removed =" . $remove_option . "
              WHERE uservideo_id =" . $uservideo_id );

return json_encode(['status' => 'Updated!']); // return status as json
}

This code was provided by user: Ervald, but he did not want to elaborate on his code. My success message is not working for the ajax, but i am not getting any errors in the console. How do i debug my ajax? is my ajax not set up properly? If this is not the right way to use ajax please let me know. Any help is GREATLY appreciated.

回答1:

there have been 2 problems in your PHP script:
1. the function was not called
2. the return-value of the function was not echoed.

(in order to respond to an AJAX call, the called url always needs to output something - JSON in the most cases. AJAX can't access PHPand thus can't read PHP return values.)

here is the fixed version:

function update_this_func($remove_option, $uservideo_id){

    global $wpdb;

    $wpdb->query("UPDATE " . $wpdb->prefix."uservideo
                  SET is_removed =" . $remove_option . "
                  WHERE uservideo_id =" . $uservideo_id );

    return json_encode(['status' => 'Updated!']); // return status as json
}
echo update_this_func($_POST['remove_option'], $_POST['uservideo_id']);