Send PHP Array To Javascript - php

///////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

var o = JSON.parse( requestText );
Include this ( https://github.com/douglascrockford/JSON-js/blob/master/json2.js ) to support old browsers.

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

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

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 (:

The simplest way to transform that long line of text in Javascript is using eval:
alert(eval('(' + requestText + ')'));

Related

ajax form handling an array

am trying to handle an array comes from php file after submitting the form data , the value of data after submitting the form is = ARRAY but i cant use this array in any way , any idea how can i handle this array !!!!
Javascript :
$('#file').live('change',function(){
$('#preview').html('');
$('#preview').html('<img src="loader.gif" />');
$('#data').ajaxForm(function(data){
$(data['toshow']).insertBefore('.pic_content').hide().fadeIn(1000);
}).submit();
});
PHP :
....
....etc
echo json_encode(array('toshow'=>somedata,'data'=>somedata));
JSON String come from server
{"toshow":"\r\n\t\t\t\t\r\n\t\t<table class=\"out\">\r\n\t\t\t<tr ><td class=\"img\"><a title=\"2012-06-02 01-22-09\" rel=\"prettyPhoto\" href=\"img\/2012-06-02 01-22-09.284.jpg\"><img src=\"img\/thumb\/2012-06-02 01-22-09.284.jpg\"\/><\/a><\/td><\/tr>\r\n\t\t\t\r\n\t\t\t<td>\r\n\t\t\t\t<table cellSpacing=\"1\" cellPadding=\"0\">\r\n\t\t\t\t\t<tr><td class=\"data\"><span class=\"click\">2012-06-02 01-22-09<\/span><\/td><\/tr>\r\n\t\t\t\t\t<tr><td class=\"data\"><span class=\"click\">Download<\/span><\/td><\/tr>\r\n\t\t\t\t\t<tr><td class=\"data\"><a href=\"img\/2012-06-02 01-22-09.284.jpg\"><span class=\"click\">View<\/span><\/a><\/td><\/tr>\r\n\t\t\t\t<\/table>\r\n\t\t\t<\/td>\r\n\t\t\t<\/tr>\r\n\t\t<\/table>","span":"<span class='text'><img src='greencheck.png'\/>2012-06-02 01-22-09 Uploaded ,File Size =152Kb <\/span>"}
better to convert array to json format using json_encode($array). json data can easily be handled by Javascript
You can't echo array directly, it will output Array only.
You need to use json_encode.
echo json_encode($your_array);
You can handle the array via PHP also with jQuery
for jQuery use - jQuery each
for PHP use - foreach or for loop
or try
echo '<pre>';
print_r($array);
echo '</pre>';
In your PHP side you have to insert json_encode($array) AND in the JS side instead of using data['toshow'] use data.toshow.
Hope it helps!
Send out a JSON response, like this from PHP:
<?php
echo json_encode($yourarray);
?>
Then to adapt your AJAX function, do this:
$('#file').live('change',function(){
$('#preview').html('');
$('#preview').html('<img src="loader.gif" />');
$('#data').ajaxForm(function(data){
var jsonData = jQuery.parseJSON(data);
//acess it like
alert(jsonData.toshow); //alert for your testing
$(jsonData.toshow).insertBefore('.pic_content').hide().fadeIn(1000);
}).submit();
});
EDIT *
Changes, update according the plug-in docs.
Having never used the .ajaxForm jQuery plug-in, I went after the documentation, I'm going to put the code here, as clear as possible from what I read, I'm even letting the plug-in parse the response automatically into json.
I didn't see any .ajaxForm().submit(), and there's no need to it according to the docs.
$('#file').live('change',function(){
$('#preview').html('');
$('#preview').html('<img src="loader.gif" />');
$('#data').ajaxForm({
dataType: 'json',
success: function(data){
alert("json string response from php: "+ data.toshow);
$(data.toshow).insertBefore('.pic_content').hide().fadeIn(1000);
}
});
});
dataType makes the plugin parse the response to json alone.
and the success: function(data) happens if there was a response from PHP only.
Implement it carefully, and give link if you still didn't get it right.

decode json as html

So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}
As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.
You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);
You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.
Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)

How exactly do you use json_decode to pass a javascript array to php?

This is how I got my php array to javascript
echo 'var daysofweek = '.json_encode($daysofweek).';';
Now I am aware that json_decode can do the opposite, however the problem is I don't know the syntax to do so.
I tried:
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
yes im clueless.
I forgot to mention that I want to send an array through post, having all my information regarding all the form values dynamically created by javascript. Otherwise, I wouldn't know which name="" to look for as it will be decided by the user. Unless someone else has an alternative solution...
PHP is a pre-processor and can't do what you're asking. You would need the PHP engine to be able to process the javascript on the page. json_decode is for decoding a json string in PHP.
To do that you would have to pass the javascript array to a PHP script using something like Ajax so your PHP script can process it anyway you would need, then pass back the result to your Javascript code.
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
I'm clueless in this part... is this javascript? if so, you need to use a JSON Parser like the JSON2.js https://github.com/douglascrockford/JSON-js
this file creates a Javascript JSON Object which allows you to parse a JSON string to a Javascript object. (you can always use eval() but it won't prevent against possible malicious code...) or the other way around... from a Javascript Object transform into a JSON string.
After converting to a JSON string you just need to send the data through AJAX to a PHP file, like:
var data = {
key: value,
key2: value2
},
JSON = JSON.stringify(data);
$.ajax({
url: 'php_file.php',
type: 'POST',
data: JSON,
success: function(data){
alert(data)
}
});
(I'm using jQuery to save some lines...)
Then on the php_file.php you would have something like this:
<?php
$json = json_decode($_POST['data']);
foreach($json as $value){
//Do something with it!
}
?>
Yes as the Wajiw said, PHP is pre-processor. But I think it might be possible with the ajaxed request.
Send the Javascript array as an argument request to the other page and process it with the php, and again display back the results.
Note: Never tried this :)
Thanks
First of all:
array_days[] = "psdfo";
array_days[] = "bsdf";
These lines are valid PHP but not valid JavaScript. The correct equivalent would be:
array_days.push("psdfo");
array_days.push("bsdf");
On to passing the resulting array of strings (that's what I am assuming) to PHP. To send it as form data in pure JS, we can create hidden input elements when the form is submitted (try it):
<form id="myform" method="POST" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('myform').onsubmit = function() {
for(var i = 0; i < array_days.length; ++i) {
var inputElement = document.createElement('input');
inputElement.type = 'hidden';
inputElement.name = 'array_days[]';
inputElement.value = array_days[i];
this.appendChild(inputElement);
}
};
</script>
PHP will interpret each input having the name of array_days[] as an array element of $_POST['array_days']. For example, you can access $_POST['array_days'][0] in PHP.
For AJAX, jQuery 1.4 and above will automatically achieve this effect when you pass an array as a data parameter to $.ajax.
Why not json_decode()? The answer is that older versions of web browsers do not support the JavaScript function JSON.stringify() that is equivalent to PHP's json_encode(), although there is a library to add support. One might consider it for a more complex case, but for such a simple case, it should not be necessary.

PHP: how to extract ajax array response

I am getting ajax response in array format from php url. How to extract array response values in jQuery?
FYI:
PHP array is:
$response = array('msg' => 'Hello', 'html' => '<b>Good bye</b>');
I am getting $response array in my ajax response. i.e.
var promo = "promo=45fdf4684sfd";
$.ajax({
type: "POST",
url: baseJsUrl + "/users/calc_discount",
data: promo,
success: function (msg) { // I am getting $response here as ajax response.
//alert(msg);
// Here I want to check whether response is in array format or not. if it is in array format, I want to extract msg here and want to use response array values.
}
});
Let me know answer pls.
Thanks.
You should echo that $response with json_encode().
You should probably set dataType: 'json' too inside the object literal you send to $.ajax().
Then you can access it natively with JavaScript using the dot operator inside your success callback...
function(msg) {
alert(msg.html);
}
BTW, this line...
$response = array(['msg'] => 'Hello', 'html' => '<b>Good bye</b>');
... isn't valid PHP. Remove the brackets from the first key.
My favorite solution for this is to encode array with PHP's function json_encode() so jquery will be happy to parse it.
I presume that you mean a JSON response, like this:
{"msg":"Hello","html":"<b>Good bye<\/b>"}
This is actually a native JS object, so you can use it right away like this:
success: function(msg){
alert(msg.msg);
alert(msg.html);
}
You can also use the jQuery.each() function to loop over all properties of the JSON object if you need to:
jQuery.each(msg, function(key, val) {
alert(key + "=" + val);
});
and If you do not have control over the PHP output then you can use another method to get the result.
Another solution is using http://phpjs.org/ library. Here you can find many functions available in JS as available in php. Usage is also same as that of PHP. So I feel if you get the json_encode/json_decode from there and use that then it can solve your problem easily.
Remember you can compile your needed functions only. In your case, it is json_encode and json_decode. No need to download whole library. Url to compile your library: http://phpjs.org/packages/configure

Sending PHP json_encode array to jQuery

ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})

Categories