How to get multiple outputs in ajax?

I’m using ajax in wordpress to get the output of a function:

jQuery.ajax({
            type: "POST",
            url:"wp-admin/admin-ajax.php",
            data:'action=nafham_list_cats_selection&selection_id=' + $selection_id,
            success:function(results){
                jQuery(".semester_selection").empty();
                jQuery(".semester_selection").prop('disabled', false);
                jQuery(".semester_selection").append(results);
            }
        })

And here’s the function I use:

Read More
function nafham_list_cats_selection() {
    if(isset($_POST['selection_id'])){ 
        nafham_get_listed_cats($_POST['selection_id']);
        die();

    }
}

Using jQuery ajax I’m able to get the output of the function, but what I need to do is to get multiple outputs like if the function echos two variables, I’d like to be able to use the two values separated in the ajax response, is that possible?

Related posts

Leave a Reply

1 comment

  1. Make an array of your output, for example if you have in your php file

    // Some code here and finally you've an array to echo/send to the browser i.e.
    $data=array("id"=>1, "text"=>"This is some content"); // This is your data array/result
    echo json_encode($data); // use json_encode to convert it to json encoded string
    

    Above code will send following json encoded string to the browser

    {"id":1,"text":"This is some content"}
    

    in your ajax success callback function you can convert it to a json object using ‘parseJSON’

    jQuery.ajax({
            type: "POST",
            url:"wp-admin/admin-ajax.php",
            data:'action=nafham_list_cats_selection&selection_id=' + $selection_id,
            success:function(results){
                var obj=$.parseJSON(results); // now obj is a json object
                alert(obj.id); // will alert "1"
                alert(obj.text); // will alert "This is some content"
            }
        });
    

    This is only an example and hope it’ll help you to understand. for more try this and this.