views:

27

answers:

4

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.

Here is my Javascript function

function editModule(a){
    data = {moduleNum:a}
    $.ajax({
        type: 'POST',
        data: data,
        url: 'includes/ajaxCalls.php',
        success: function(data) {
            alert(data['title']); // <-- This is where I'm not sure what to return from php
        }
    });
}

Here is my php doc (so far, this is where I need to know how to return an object)...

<?php
$data =  array('title'=>'this');
echo json_encode($data);

When I run the function I just get the alert "undefined".

Suggestions?

Thanks, -J

A: 

I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.

SBUJOLD
+2  A: 

Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.

function editModule(a){
    data = {moduleNum:a}
    $.ajax({
        type: 'POST',
        data: data,
        dataType: 'json',
        url: 'includes/ajaxCalls.php',
        success: function(data) {
            alert(data.title);
        }
    });
}
thetaiko
A: 

Your php page returns: {"title":"this"} in this case. So you can reference the result with:

alert(data.title);

mamoo
A: 

You may need to specify the data type:

function editModule(a){
    data = {moduleNum:a}
    $.ajax({
        type: 'POST',
        data: data,
        url: 'includes/ajaxCalls.php',
        dataType: 'json',
        success: function(data) {
            alert(data['title']); // <-- This is where I'm not sure what to return from php
        }
    });
}
Dianoga