Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a particular value from ajax response

I am using ajax with masonry

Ajax code: This ajax is used to get data from

$.ajax({
      type: "get",
      url: "some.php",
      dataType: "text",                 
      success: function(data) { 
        if (data && data.length > 0) {       
          $items = $(data); 
          $grid.append( $items )
          .masonry('appended', $items);
          $(this).find(".loading").hide();
        }
      }

Php Part: This is just a small or sufficient part of php file to understand the problem

$b= "sv";
echo "asjdgsajd";
echo "a";
echo $b;

now i am getting everything correctly but i want to use say value of $b for setting a attribute value and also other values as content but how can i particularly get value of $b? Thankyou

like image 747
shubham sharma Avatar asked Nov 15 '25 12:11

shubham sharma


1 Answers

Change the dataType to json.

$.ajax({
      type: "get",
      url: "some.php",
      dataType: "json",                 
      success: function(data) { 
        //data will hold an object with your response data, no need to parse
        console.log('Do whatever you want with ' + data.b + '.');
      }

In some.php do the following:

$response =array(
    'b' => "sv",
    'a' => "asjdgsajd",
    'c' => "a"
);
echo json_encode($response);
echo $b;

The items of the associative array will end up as properties of a javascript object, that you can use in your success callback (or done function as success is deprecated).

like image 195
some-non-descript-user Avatar answered Nov 17 '25 10:11

some-non-descript-user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!