0

can anybody help to explain or give reference on how to send array of multiple array (or just array ) in jquery. and what the best way to do when something is failed or successfull. what i mean is how the php code send back the success or failed message

3 Answers 3

6

See this article for an example. Basically, you have to use PHP's json_encode() to convert a PHP array to JSON code. In the linked example, the jquery-json plugin is used to convert JSON back to a Javascript array.

Alternatively, you can use jQuery's built-in capabilities for retrieving a PHP response as a Javascript array/object.

Sign up to request clarification or add additional context in comments.

Comments

1

Use JSON ENCODE

Something like this:

index.php

<script type="text/javascript" src="jsfile.js"></script>

<a href='numbers.php' class='ajax'>Click</a>   

numbers.php

<?php
     $arr = array ( "one" => "1", "two" => "2", "three" => "3" ); // your array
     echo json_encode( $arr ); // encode it to json
?>

jsfile.js

jQuery(document).ready(function(){
    jQuery('.ajax').live('click', function(event) {
        event.preventDefault();
        jQuery.getJSON(this.href, function(snippets) {
            alert(snippets); // your array in jquery
        });
    });
});

Comments

1

If it is a simple error message and always the same one, you can simply return that string e.g. "error" and test for that value in JavaScript. But I would recommend to send the complec data in XML or even better in JSON (because it is smaller and can be used without poarsing it in JavaScript). Just do this in your PHP:

if($error){
  echo "error";
} else {
    json_encode($complex_data);
}

If you want to put some information into your error, which I highly recommend, just return an error array encoded with JSON. So replace the echo "error" with this:

echo json_encode(array("error" => "your error message", "status" => "an optional error status you can compare in JavaScript"))

Than you just have to check if the "error" is found in the JSON returned from PHP.

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.