Christian Eric Paran
Christian Eric Paran

Reputation: 1010

Ajax Sending and Retrieving

I've been using ajax for a while now and I want to learn more about retrieving data. I only know how to get output by using callbacks.

When I use callbacks and I want individual values, I use split() or explode() so I can get individual value. Is there a better way than this? if I keep using this I think it will get messy if inputs have the same character as the pattern for split/explode.

I want to know how to retrieve data individually via variables, not by echo or HTML outputs.

ask if you don't understand my problem.

Thanks.

Upvotes: 0

Views: 98

Answers (2)

Igor Parra
Igor Parra

Reputation: 10348

Using Ajax/jquery $.get sample:

$.get(
    path_to_your_script. "?run=process_ajax_callback",
    {
        var_ajax: 1, // var sample
        // more vars to your function
    },
    function(response, status) {
        // evaluate response var as a javascript object/array
    },
    'json' // we expect json formatted response
    );

Returning values from a PHP function:

function process_ajax_callback()
{
    // ...

    $output['var'] = array(1, 2, 3); // var sample

    echo json_encode($output); // encode as json!!!

    exit; // very important (only output from this function)
}

Upvotes: 0

Shyju
Shyju

Reputation: 218732

You can return the output from your PHP page as jSON. you can iterate thru the json results with each method and get items. That is much cleaner way than doing split

A sample

$.getJSON("yourphppage.php", function(data){
   $.each(data.ResultSet.Results,function(i,item){
      console.log(data.ResultSet.Results[i].Name);
      console.log(data.ResultSet.Results[i].Age);
   });     
});

Assuming you are returning a JSON result like the below from your php page

{
    "ResultSet": {          
        "ErrorMessage": "No error",
        "Results": [
            {
                "Name": "John",
                "Age": "22"
            },
            {
                "Name": "John",
                "Age": "22"
            }
        ]
    }
}

EDIT : When working with Use jSONLint, an awesome webbased tool to tell you whether your JSON is valid or not.

http://jsonlint.com/

Upvotes: 3

Related Questions