0

Trying to use two done callbacks in a jQuery function. One is a data type JSON, the other is not. The first calls a php function for its data that is not a JSON array. The second I want would call a JSON encoded array from the same php call. I need to pass the array of the ID's to another function

Is this possible? Something like this

function func1() {

  jQuery.ajax({
    type: 'post',
    url: my_ajax.ajax_url,
    data: {
      action: 'myphp'
    }
  })

  .done(function(data) {
    jQuery('#adivID').html(data);
  })
  .fail(function(xhr, status, error) {
    console.log(xhr.responseText);
    alert(error);
  })

  dataType: 'JSON',
  .done(function(data) {
    ids: id;
    func2(data.ids);
  })
}

EDIT 1 - attempt at two end points

function func1() {
  jQuery.ajax({
    type: 'post',
    url: my_ajax.ajax_url,
    data: {
      action: 'myphp'
    }
  })

  .done(function(data) {
    jQuery('#adivID').html(data);
  })
  .fail(function(xhr, status, error) {
    console.log(xhr.responseText);
    alert(error);
  })

  jQuery.ajax({
    type: 'post',
    url: my_ajax.ajax_url,
    dataType: 'JSON',
    data: {
        action: 'myphp',
        ids: id;
    }
  })   
  .done(function(data) {
    func2(data.ids);
  })
}

PHP

function phpfunctionname{
$id= wpdb->get_results("SELECT id from mycats");
$ids .='';
foreach($id = $value){
ids=$value-.id;
};
echo json_encode(array('ids' => $ids));
};
15
  • The code in your question is syntactically invalid. Could you please fix it up? Adding proper indents would also make it much more readable Commented Jan 31, 2021 at 22:52
  • Run your code through beautifier.io for formatting. It won't fix your broken code though Commented Jan 31, 2021 at 22:54
  • 1
    Looks to me that OP is posting code snippets (not SO snippets) in an attempt to demonstrate what they are trying to achieve Commented Jan 31, 2021 at 23:12
  • In short, no. You can't have jquery call two different .done() with different data types as the (return) dataType is set before making the ajax call. In your second (json) .done() you could JSON.parse(data). But data in the first is html. How will your single end point with a single call return two different data types? It's not jquery that determines the data type, it's the server; jquery just converts it for you (eg parses json if you say it's json that's being returned, so you get an object instead of a json string) Commented Jan 31, 2021 at 23:15
  • 2
    One is a data type JSON, the other is not.... One ajax call = one response having one data type. You should do 2 request to two diferent endpoint to have two different results. Commented Jan 31, 2021 at 23:16

1 Answer 1

2

Yes, you can nest ajax callbacks. But first we may want to review what we're talking about here.

JSON stands for javascript object notation. It isn't a data type, it's a way to encode a javascript object into a text string so it can be easily stored/transferred. https://www.w3schools.com/js/js_json_intro.asp

jQuery is a javascript library. It's basically sytactical sugar for vanilla javascript. https://jquery.com/

PHP is a sever side language used for taking client requests, doing stuff with it, and returning a response. You don't call php functions from the client. You make a request and the sever decides how to respond. https://www.php.net/

That out of the way, if you want different data back from the same url, you would have to add that in your options object and then handle that server side. Client side would be something like this:

jQuery.post(my_ajax.ajax_url, { action: 'myphp', return_type: 'string' })
  .done(function(data) { //data will be a string
    jQuery('#adivID').html(data);

    //this part doesn't make sense, because if the data is a string,
    //it won't have an 'id' property. But maybe in your actual code this
    //does make sense. So this is just an example of how nesting works.
    jQuery.getJSON(my_ajax.ajax_url, { ids: data.ids, return_type: 'json' })
      .done(function(json) { //json will be an object
        //do stuff with the object
      })
      .fail(function() {
        //response was probably not properly json formatted
      });
  })
  .fail(function(xhr, status, error) {
    console.log(xhr.responseText);
    alert(error);
  });

jQuery.post() and jQuery.getJSON() are just short hands for jQuery.ajax(), as they require less parameters, and unless you're doing something more complex, keeps your code more readale.

Edit (since you added your php code):

I'm not familiar with wordpress, and it took a few reads to try and figure out what your code is doing. But what I gather from the docs, you might want something like this:

$ids = $wpdb->get_results("SELECT id FROM mycats", ARRAY_N); //returns an indexed array of ids

switch($_POST["return_type"]) {
  case "string": //returns a comma separated string of ids
    echo implode(", ", $ids);
    break;
  case "json": //returns a json array of ids
    echo json_encode($ids);
    break;
}

But again, the getJSON() is going to fail because the post() is going to return a string. It's tough to suggest code without knowing exactly what it is you're trying to accomplish. It's probably also worth noting that in php an object is different from an associative array is different from an indexed array. Also, all variables start with a $. wpdb != $wpdb If you haven't lost several hours because of this, you haven't written enough php haha.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for posting a thoughtful answer
when trying to use the example above, I am getting a "data not defined" error? Given that this is a very different way from what I am used to, I am not sure what that is telling me , other than the obvious- the data isnt defined. The error is coming off the second nested call where it says data.ids Does seem the second portion is running before the 1st though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.