0

I have a fairly simple AJAX request for my WordPress site. My PHP function is a switch statement and all the other switch statements work except for the recent one I added (change_due_date).

I commented out the majority of the code in my new 'case' to better try to find the problem.

AJAX (at bottom of page, under my other AJAX request (which works)):

      function my_ajax() {      

          var newDate = <?php echo $new_date; ?>;
          var data_string = 'action=do_ajax&fn=change_due_date&newDate=' + newDate;

          jQuery.ajax({                         
            type: "POST",
            url: '/wp-admin/admin-ajax.php',
            data: data_string,
            dataType: 'JSON',
            success: function(data){
                // alert(data); 
                console.log("success!");
            },
            error: function(errorThrown){
                console.log("error!");
            }

          });

      } // end of my_ajax function

      jQuery('a.test').click(function(){
         my_ajax();
      });

    </script>

I tried, at first, just sending 'newDate' as my 'data' value - and that did work (as in AJAX returned 'success!'). In that case my PHP function still didn't run, since it wasn't being called. I suspect something is wrong with my formatting on the AJAX side of things...

Now, when I send 'data_string' as my data I get an AJAX error...

PHP Function:

switch($_POST['fn']){  ...    
    /* AUTOMATE DUE DATE CREATION - made by Alex */
    case 'change_due_date' :
        /*$field_key = "field_515b2428887d7";   // Key ID for field
        $new_date = $_POST['newDate']; // new date      
        $new_due_date = DateTime::createFromFormat('Ymd', $new_date);
        $new_due_date->format('Ymd'); // formatting */
        echo ('<h1>functioning</h1>'); // testing purposes

        /*$parent_field = get_field($field_key); // Select parent field
        foreach($parent_field as $sub_row) :                
            // Change value of sub-fields   
            $sub_row['date_due'] = $new_due_date;


            $new_values[] = $sub_row; //  Load new values into array
        endforeach; 
        update_field( $field_key, $new_values ); // Update ACF*/
        $output = "Successfully updated due dates."; // testing
    break;
... }

I've been working on this code for a couple days - I admit I am not the best at AJAX... but I can't seem to find what's wrong? I have looked at the WP Codex for guidance on how to structure my AJAX.

  • What error are you getting? – czerspalace Jul 13 '16 at 23:00
1

A simple answer to your question is that you have the data type as JSON in your ajax request and you are passing a string in it. You need to pass a json object in the ajax request when you chose dataType equals to JSON. A JSON object is typically a key pair value inside curly braces. Here is a reference where you can see how ajax requests can be implemented in WordPress.

https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/ https://stackoverflow.com/questions/14185582/creating-an-ajax-call-in-wordpress-what-do-i-have-to-include-to-access-wordpres

Check the data inside the ajax function. You will need to verify your json before sending it to the server so that there wont be any issues further. Also you will need to decode the json on the PHP server side. Then only you will be able to manipulate the data in your PHP code. May be an alternative way for you is that you can make a request without datatype json and you will get the post values in your PHP code making it easy to use. Check the below link for reference.

http://www.makeuseof.com/tag/tutorial-ajax-wordpress/

0

I think you may have a problem in the way you establish your data. If you read the WP Codex on AJAX, you will see the data in the examples is in key/value pairs. That is, the data should look something like this:

var data = {
        'action' : 'do_ajax',
        'fn' : 'change_due_date',
        'newDate' : newDate
    };

Also, note the Codex says that the variable ajaxurl points to /wp-admin/admin-ajax.php (since version 2.8). Sometimes, this won't work unless you call wp_localize_script() first.

Personally, I don't use datatype: 'JSON'. I can't say whether or not your scheme is being broken by including it in your data.

Lastly, don't forget this at the end of the PHP function that sends data back to the AJAX call:

echo $output;
wp_die();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.