0

How can print date and age (in following array) separate by $.ajax()?

php:

$array = array(
                'date' => 2011/9/14,
                'age' => 48,
            );
return $array // this send for ajax call in the jQuery

I want this output by jquery:2011/9/14 & 48

2
  • 2
    I think you should get your understanding of client-server, jQuery, AJAX, POST, PHP etc. straight. Commented Sep 14, 2011 at 11:27
  • 1
    +1 @Baszz. @Selena json_encode and echo are your friends in this situation, return isn't. Commented Sep 14, 2011 at 11:29

5 Answers 5

1

Use $.ajax Methods and setting parameter dataType to JSON for receive data type JSON from PHP file.

Jquery Code:

$.ajax({
  url: "getdata.php",
  type: "post",
  dataType: "json",
  success: function(data){
    alert("Date:" + data.date + "\n" + "Age:" + data.age);
  }
});

if your array data contains string make sure it's closured with quote then make data type JSON with json_encode() function.

PHP Code (getdata.php):

$array= array('date'=>'2011/9/14','age'=>48);
echo json_encode($array);
Sign up to request clarification or add additional context in comments.

Comments

1

Echo the encoded array in php page say mypage.php using

echo json_encode($array); 

And use jQuery.getJson in the client side

$.getJSON('mypage.php', function(data) {
  alert(data['date']);
  alert(data['age']);
});

1 Comment

Excellent one! this code is very useful especially when you are using $.post instead of $.ajax
1

You need to encode the array as a valid JSON string using the PHP function json_encode. You can then use the jQuery function $.parseJSON to convert it into a JavaScript object. From there you'll be able to do whatever you want with it.

If you do this, you'll end up with an object like:

ajaxDataObj = {
    date: '2011/9/14',
    age: 48
}

**Edit**
Please see stratton's comment below about using $.getJSON for a more compact solution.
Also, Ben Everard's comment on your original post about using echo rather than return is critical.

1 Comment

if you use $.getJSON instead it can all be incorporated in a single ajax function
0

You can't just return $array to the browser, the result will be "Array" as string. YOu have to use return json_encode($array); which returns a string that could be parsed by browser.

1 Comment

i not use of json, did there is other way?
0

If the server-client communication is working alright, then you should do something like this on the client side:

$.ajax({
    //configuration...
    'success':function(response){
        var dateAge = response.date+' & '+response.age;
        //put or append the string somewhere. 
    }
});

Comments

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.