///////UPDATE - I already have jquery library included to my code so if its easier with jquery than javascript let me know please.
OK. There are loads of questions on here that are sending a JavaScript array to php but only 1 which is the same as mine. Unfortunately I didn't understand the answer.
So, at the moment I have an associative array in php. I then used this code,
echo json_encode($this->_inputErrors);
I don't actualy know why i'm using it, just was mentioned a lot in other examples like this. So that then sends the data to javascript (via ajax) and if i do this code,
alert(requestText);
I get a long line of text. As I imagine i should.
So how do i then in javascript get the text back to an array?
Or Is there a better way to do this?
Many Thanks For Your Time,
Chris
5 Answers 5
var o = JSON.parse( requestText );
Include this ( https://github.com/douglascrockford/JSON-js/blob/master/json2.js ) to support old browsers.
5 Comments
console.log( o ); and open your console, you'll see.requestText is a JSON string. You need to parse the string into an object.
You can use JSON.parse to convert the string to JSON.
var obj = JSON.parse(requestText);
If your browser doesn't have JSON, include this:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
1 Comment
You need to set the return type as JSON
or if using jQuery, you can use jQuery's method getJSON() to get the JSON object from the url
5 Comments
$.ajax at first but now I don't get it. Do you mean like content-type in PHP or something else?Somedays before, I faced the same problem. Check my solution :)
array.html
$(document).ready(function(e){
//This array is where I'll receive the PHParray
var js_array=new Array();
$("#btn").click(function(e){
$.ajax({
type: 'POST',
url: 'vector.php',
cache: false,
success: function(data){
js_array=data;
//I use this "for" to print each array item into a div called "data".
for(var i=0;i<js_array.length;i++){
$("#data").append("<p>"+js_array[i]+"</p>");
}
},
dataType: 'json'
});
});
});
vector.php
<?php
$array = array(1,2,3,4,5,6);
/*As you, I use "json_encode" to serialize the array
echo json_encode($array);
?>
I hope it can help (:
Comments
The simplest way to transform that long line of text in Javascript is using eval:
alert(eval('(' + requestText + ')'));
15 Comments
evaling your own servers JSON response. And eschewing a quintessential feature of scripting languages for fictional reasons like that is not very clever. (It's also not fashionable to downvote competing answers.)
json_encodeconverts a PHP object into a JSON one.