I have been misinterpreted. I have created a JSON Object in PHP. I just need access to that object in Javascript. That is all.
I just learned that many of my problems can be solved by using JSON. Now learning how to use JSON is another problem, though. ;-)
Suppose this is the code in PHP:
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Now how do I access the $javascriptFriendlyData in javascript.
I tried using JQuery but I can't really figure out much...
If it helps, the JSON Data structure is somewhat like this:
[{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}...
]
Try this:
<script>
<?php
echo 'var data = '.$javascriptFriendlyData;
?>
// now the JSON data is stored in the data variable
console.log(data);
</script>
I'm assuming you are running PHP in the HTML template here:
<html>
<head>
<script><?php echo 'var data = '.$javascriptFriendlyData; ?></script>
<script src="some_js_file.js"></script>
</head>
<body>
etc...
In the some_js_file.js, you can now access the data variable.
If it's an array of simple data as you describe, there is little reason to eval() it, but you might consider it anyway.
From the official JSON documentation:
var myObject = eval('(' + myJSONtext + ')');
Now you can use it like any other Javascript object.
If you are creating the JSON encoded data in your PHP script and echoing in your JavaScript, you don't even have to call eval because it is already in a native JavaScript format.
So taking your code...
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Then, in your Javascript code you can do something like...
<script type="text/javascript">
var data = <?php echo $javascriptFriendlyData; ?>;
</script>
Then when the page is rendered, the data is already parsed and ready to use. It is when you are handling AJAX requests that return data that it needs to be evaluated. Otherwise, it is no different then using JavaScript notation inline.
eg:
<script type="text/javascript">
var somevar = [{objVar1:"SomeVal"},{objVal2:"SomeVal2"}];
</script>
If you are trying to have your JavaScript in a separate file, then you will need to set this variable in your JavaScript before you load your JavaScript file or run the JavaScript file through the PHP interpreter.
JSON is just a notation for Javascript data. Which means you can have this kind of JS code :
var data = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
Which will just put your data in the data Javascript variable.
Considering that [] symbolize an array, and {} symbolize an object, you can use this to access the title property of the first element of the data array :
alert(data[0].atitle);
And you'll get
Ameya R. Kadam
And, to loop over each elements of the data array, you can use something like this :
var i;
for (i=0 ; i<data.length ; i++) {
alert(data[i].aid + ' : ' + data[i].atitle);
}
(Absolutly no need for jQuery for such a task, btw)
If your array is in a variable called data:
$.each(data, function(){
alert(this.aid);
alert(this.atitle);
});
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function() {
alert(this.aid)
alert(this.atitle)
})
Or
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function(i,o) {
alert(o.aid)
alert(o.atitle)
})
I have found that the JSON.org Json2.js library to come in handy for going from JSON to JS and back from JS object to JSON. For example, instead of:
var obj = eval('(' + jsonString + ')');
with the JSON.org library you use:
var obj = JSON.parse(jsonString);
You can also specify a second parameter that allows you to work with the results of the JSON being revived as an object.
To go back to a JSON string just call:
var jsonString = JSON.stringify(obj);
This also takes optional arguments to help control JSON string creation.
JSON basicalle represents a Data Structure right, so essentially it's an Object, or instance of a Class, so to use it you do this:
var MyJSonObject = eval("(" + jSonString + ")");
UPDATE
hey Amit, you can't access PHP objects from javascript. What you have to do is somehow construct the JSON string in PHP, but then write it out to the client. I'm not sure how you'd do it in PHP, but this how you'd do it in ASP. The idea is the same, the syntax will be different in PHP.
<html>
<head>
<script type="text/javascript">
var MyObject = eval("(" + <%= Response.Write(strServerSideVariable) %> + ")");
</script>
</head>
<body>
</body>
</html>
Note that in ASP/.NET the tags "<% %>" denote server side, not client side, code. This is what you have to do with PHP amit
It's worth noting that some browsers now provide a set of native functions for JSON decoding and encoding: JSON.parse() and JSON.stringify(). They are safer than using the eval() function and only works if the JSON data is well-formed, whereas eval() would evaluate things like the following:
{
'hello': (undefined
? 'world'
: ('number ' + Math.floor (40.235)))
}
What's wrong with that? The JavaScript value `undefined' is not available in JSON (only true, false, null, strings and numbers are allowed); single quotes are used everywhere when only double quotes are valid in JSON; you can't call JavaScript functions or perform string concatenation in JSON.
Obviously the last one is a big problem because you could receive some malicious JSON, possibly a value from a form input, that attempts to tamper with things. So when possible, use JSON.parse() and JSON.stringify()...because eval() is dangerous.
Edit:
I misread the original post. If you have a JSON object in PHP and you want to use it in JavaScript, you would need to convert the JSON object to a string and pass it on to JavaScript. The only way to do that would be to make your JavaScript code actually ask for the newly created JSON string in the first place. PHP would return a string, JavaScript would use eval() or JSON.parse() on the string, and you'd have your object in JavaScript. I'm not sure if there is a non-AJAX way to do this without making your JavaScript files into PHP files, setting the Content-Type header, etc., but I know that AJAX would work in this situation.
Related
I would like to pass a string that has been serialized by JSON using $.ajax to an external php file to be assigned to a regular array.
Here is what I got so far which isn't showing 0th index of taskContent array.
JQuery code:
$(".json").click(function() {
var allTaskArr = [];
$('#appendTask .taskbox').each(function(index,domEle){
//domEle == this
allTaskArr[index] = $(domEle).val();
});
var allTaskStr = '{"taskContent":'+JSON.stringify(allTaskArr)+'}';
$.ajax({
url:'testjson.php',
type:"POST",
datatype:'json',
data:allTaskStr
});
});
PHP file:
$jsonContent = $_POST['taskContent'];
$taskContent = json_decode($jsonContent,true);
echo $taskContent[0];
You said:
#Spudley I'm getting 'Undefined Index: taskContent' message.
The reason for this that PHP is not receiving a post variable named tastContent.
And the reason for this is that you are not sending the JSON correctly.
In the jQuery code, you are producing a JSON string, and then putting this in the data element of the ajax call. In fact, the data element is supposed to be given an object, not a json string; it encodes it to json itself, so if you give it json in the first place, the PHP program will receive a double-encoded string -- ie a json string which decodes to another json string.
So instead of this:
var allTaskStr = '{"taskContent":'+JSON.stringify(allTaskArr)+'}';
... you need to send the data as an object, like this:
var allTask = {taskContent:allTaskArr};
or just put it straight into the ajax call:
data : {taskContent:allTaskArr}
Hope that helps get you on the right track and explains what the problem is.
Disregard this post before this edit.
This is your issue:
var allTaskStr = '{"taskContent":'+JSON.stringify(allTaskArr)+'}';
Should be:
var allTaskStr = {"taskContent":JSON.stringify(allTaskArr)};
data:, expects an object and you are sending it a string.
I have this code that executes a for loop in javascript with a php array inside of it. Is there anyway I can use the variable for the loop inside of the php variable for example. This is all inside of php.
echo '<script>
for (var i =0; i<4;i++){
alert("hey"'.$phparr[i].');
}</script>';
I know this will not work because the $phparr is a php variable while the i is a javascript variable is there anyway I can do this?
Try:
<script>
var phparr = <?php echo json_encode($phparr); ?>;
for (i in phparr){
alert("hey" + phparr[i]);
}
</script>
PHP is a server side language which means it executes before it reaches the client (browser).
JavaScript is a client side language which means it is executed in the browser (client side).
The best tool for a new web developer is Google search.
Learn how to search effectively.
You're almost there. In order to access the php array in javascript, you first have to echo out the php array into a javascript array. Try:
$phparr_imploded = implode(',',$phparr);
echo '
<script>
var arr = ['.$phparr_imploded.'];
for (var i =0; i<4;i++){
alert("hey"+arr[i]);
}
</script>
';
If your php array is coming from a database, or contains special characters that javascript may misinterpret, make sure to sanitize before outputting.
Are the objects in your php array strings? If so, you need to surround the objects with escaped quotations BEFORE the implode.
for($i=0; i<count($phparr); $i++){
$phparr[i] = '"'.$phparr[i].'"';
};
How about storing the PHP array in a Javascript variable and looping through as kpotehin suggests?
<script>
var i = 0, name;
var myArr = <?php echo json_encode($my_array); ?>;
while (name = myArr[i++]){
alert("hey " + name);
}
</script>
You should make it this way:
var arr = ["<?php echo implode('","',$array); ?>"];
for (var i =0; i<4;i++){
alert("hey"+ arr[i]);
}
Your basic problem is that you are forgetting that the PHP code and the JavaScript code do not execute at the same time. The PHP runs to completion, outputing HTML and JavaScript. Then the browser runs the JavaScript. If the JavaScript needs dynamic access to data in a PHP variable (including an array), then the PHP needs to generate JavaScript declaring the data in a JavaScript structure. That is what all the other answers are doing.
///////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 + ')'));
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>"
)
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.