PHP arrays into javascript arrays - php

I am a bit confused here on how I implement an array into JS from PHP....
I'm doing this for testing - eventually I'll use long polling or websockets if they get highly supported but this is what I have:
$get = mysql_query("SELECT x,y,sid FROM player_town WHERE uid='1'") or die(mysql_error());
$row = mysql_fetch_assoc($get);
$data = json_encode($row);
Further down the script I then put in the head:
<script>var data = Array(<? $data; ?>)</script>
<script type="text/javascript" src="js.js"></script>
But in js.js it says undefined but $data is set. This is the error:
x is not defined
In js.js I did alert(data[x]); and I get undefined.
My json_encode looks like this:
{"x":"283","y":"99","sid":"1"}
Any ideas?

Not sure why you need to wrap the json string in an Array, you could just do
var data = <?php echo $data; ?>;
--
To get the value of data in your js, you can either do data.x or data["x"]

Be sure you're echoing the PHP data into the <script> tags
<script>var data = Array(<?php echo $data; ?>)</script>
As an aside, it's a good idea to avoid using short tags (<? and ?>) in a production setting--many servers have them disabled by default, and it's a really annoying way to have your code break.

You should try this instead:
var data = <?= $data ?>

Not sure if <? $data; ?> is a typo or not but you should be using either <?=$data;?> or <?php echo $data; ?>

You can use AJAX (much easier). Make your PHP script echo $data, and then using jQuery ajax request the data in your HTML file as JSON. For example:
$.ajax({
url: script_url,
dataType: 'json',
success: function(json)
{
...
}
});

I agree with the answer in your comments. I would make an AJAX call to yourFile.php and then send back your JSON encoded response. so here would be my psuedo code.
1. Make AJAX request
$.ajax({
url: "yourFile.php",
dataType: 'json',
success: function(data)
{
console.log(data);
}
});
2. Make sure that your PHP file also returns header for JSON
header('Content-type: application/json');
2. Return {"x":"283","y":"99","sid":"1"} as data on your ajax request
3. call the values by using data.x or data.y or data.sid

Related

Reading JSON data (created by PHP) via jQuery Ajax results in "parserror"

I create JSON-data with the following php code:
if($res = $db->query('Select row1 from table1')){
while($row = $res->fetch_row()){
$json[] = $row;
}
}
sort ($json);
$json = json_encode($json);
echo $json;
The result is [["1"],["2"],["3"]].
When I try to fetch this data with jquery ajax
<div id="output">JSON will be put here</div>
<script language="javascript" type="text/javascript">
$(function () {
$.ajax({
url: 'json.php',
dataType: 'json',
data: '',
error: function(request,error) {
alert(error);
},
success: function(data) {
var json = data[0];
alert(json);
$('#output').html(json+", ");
}
});
});
it says: "parseerror".
I searched a lot (here at Stack Overflow), but my jQuery version seem to be right (1.7.2) and reformating the JSON-outpu did not help (I deleted the opening brackets and tried a lot of other things).
Any ideas?
Parse the data return in ajax result,
var retData= JSON.parse(data);
You should check if you get an object before using it:
if(typeof data != 'object')
data = $.parseJSON(data);
Sometime it is interpreted as a string and you have to convert it first
I don't think you need to push it in an array. Your query is already an array. SO try to only json_encode() and that alert the data what you get and try to access the data by using data.somevariable( at least that is how I access my json data in the ajax).
Hope it helps
Verify the content type of the response header (you can see this in any modern browser's network console). It needs to be coming back as application/json. Any other type may cause your Javascript to fail. Before echoing the JSON in your PHP file, try adding:
header('Content-Type: application/json');
This will explicitly and correctly set the response content type. Keep in mind, this in contingent upon your return string being valid JSON in the first place, which it seems to be.

Pass array from php back to javascript and loop over it

Hi I'm working on passing back an array from php to javascript. I learned online that I should use json_encode on the array when passing it back but now that i have it in the ajax i'm unsure how i can loop over it because doing things like response[0] gives me [ and response[1] gives me " although when writing the entire thing to the document using innerHTML i can see it looks like an array but using a for loop gives me each letter like i stated above with the response[0] equaling [ rather than the first entry. What am i doing wrong? Any help is greatly appreciated!
PHP
<?PHP
$link = mysql_connect('localhost', 'root', 'root');
mysql_select_db("Colleges");
$result = mysql_query("SELECT * FROM `Colleges` ORDER BY School");
$schools = array();
while ($row = mysql_fetch_array($result)) {
array_push($schools, $row['School']);
}
mysql_close();
die(json_encode($schools));
?>
Ajax
<script type="text/javascript">
function schools(){
$.ajax({
url: "Schools.php",
type: "POST",
success: function (response) {
//Loop over response
}
});
}
</script>
You should decode your JSON response (which is a string actually) to be able to work with it as with an object:
var respObj = JSON.parse(response);
The other way around is noticing jQuery that JSON will be supplied by the server (with either dataType: 'json' ajax parameter or Content-Type: application/json response header).
In the object you pass to the ajax method, you should try to add dataType: 'json' in order to specify that the result is json, or you could specify it in your php script calling header('Content-type: application/json'); before the call to die();
Doing so will result in your response being the object you expect instead of a string.
Finally, you could leave it as is, and call in your success callback response = $.parseJSON(response); which will take the response string and turn it into an object, see http://api.jquery.com/jQuery.parseJSON/
Use Following if it helps
res=jQuery.parseJSON(response);
for(i=0;i<res.length;i++)
{
alert(res[i].propertyname);
}
here property name implies to the keys on json .In your case it can be 'School' or just a number i or value can also be just res[i]
Javascript
for ( variable in response ) {
alert(results[variable]);
}
JQuery
$.each(response, function(ind, val){
alert("index:" + ind + ". value:" + val);
});

How to call $_SESSION in javascript

I have two separate pages, one page is where it uploads the file and the other page displays the information.
In the imageupload.php page, I have this session below:
$_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];
I also have a javascript function which calls back to the javascript functiom:
<script language="javascript" type="text/javascript">window.top.stopImageUpload();</script>
Now on a seperate page (QandATable.php), I have a javascript function, but my question is how can I call the $_SESSION code above in the javascript function so I can append it to $('.list')?
Below is javascript function:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
You cant, because $_SESSION is a server side variable but you can access it by.
For the entire session variable
<script type="text/javascript" >
var session = <?php echo json_encode($_SESSION); ?>;
</script>
For a particular variable in session.
<script type="text/javascript" >
var session_var = <?php echo json_encode($_SESSION['VAR_NAME']); ?>;
</script>
Now you have js variable called session with that information. However it is not advisable in most situation to output all that info to public pages.
Session variables are stored on the server. JavaScript is executed on the cliend side, so it knows nothing about the server side. It know only as much as you pass to it.
To pass a variable to javascript, use an ajax request, or simply output the values:
<script>
var sesionValue = <?=json_encode($_SESSION['value']);?>;
</script>
You should look into using JQuery, as it makes these AJAX-like tasks much easier.
See my function I wrote just today to do something similar to what you're asking.
This takes some PHP output (returned in the success part of the call to ajax(). The format it takes is in JSON, which is compatible by both PHP and JavaScript (JSON: JavaScript Object Notation).
function viewClientDetails(id) {
var clientParams;
clientParams.clientID = id;
$.ajax({
url: BASE_URL + '/clients/get-client-details.php',
type: 'POST',
data: clientParams,
dataType: 'JSON',
success: function(myClient) {
var name = myClient.name;
$('td#name').html(name);
},
error: function(e) {
console.log(e.responseText);
}
})
}
In my PHP file (called /clients/get-client-details.php) I have something like this:
<?php
...
$myClient = array('name' => 'Mr Foobar');
print json_encode($myClient);
?>
This simply writes my PHP object to JSON format.
In the JS code above, the code inserts a part of the JSON data into an HTML table-data element whose CSS selector ID is #name, with the line: $('td#name').html(name);
Apologies if this confuses you more, I thought I'd show an example of what you can try some time..
This may help you a bit along the way...keep trying things, you'll get there :)
You can't. $_SESSION is a PHP variable, and that code runs server-side.
You'll need to store the value as a Javascript variable in the output from your PHP file, then access that variable in your Javascript.

$.post() jQuery and PHP

Here is a piece of code :
$username="anant";
$name="ana";
echo $username;
echo $name;
Now if using jquery $.post() i want to retrieve $username and $name ,how would I do it ?
Thanks!
I assume the code is your php based response to the $.post call. If all you are returning are values then the easiest thing to do is to return a json response. For example...
PHP Script:
$values = array(
'username' => 'anant'
'name' => 'ana'
);
header('Content-type: application/json');
echo json_encode($values);
JS $.ajax call:
$.ajax(
url: '/path/to/script.php',
type: 'post',
dataType: 'json',
success: function(data){
alert('Username: '+data.username);
alert('name: '+data.name);
}
);
Or if you wanna stick with $.post then follow kovshenin's answer for the syntax using $.post. But be sure you use my php code witht he header() call to properly set the content type of the http response. I just prefer to use the long hand.
I'm not a php expert but try something like:
php
$username="anant";
$name="ana";
echo json_encode(array("username"=>$username,"name"=>$name));
js
$(function() {
$.get('test.php', function(data) {
alert(data.username + ':' + data.name);
});
});
I hope this helps!
You will be better off with json_encode which javascript will understand just fine:
$res = array('username' => 'anant', 'name' => 'something');
echo json_encode($res);
Then use the following code in jQuery to retrieve the values:
$.post('/something', function(response) {
alert("Username is: " + response.username + " and name is: " + response.name);
}, "json");
Cheers.
Now that I know what you are trying to do post expects a fourth parameter the encoding type. If you set it to JSON you would encode your data like so
echo '{"username": ".'$username.'", name":"'.$name.'"}'; //Json may not be perfect
you can access it in jQuery using
data.username
First thing is you have to do a GET not a POST. You may need to change your server side code a little bit so that front end had a clue of how to identify different values (JSON will be better) but a simple , should work fine.
$username="anant";
$name="ana";
echo "$username,"
echo "$name";
your output will be then something like Anant001,Anant your username, name.
Then use a simple jQuery call to get it and split it by , and here is an example..
$.get('/getnames', function(data){
var tokens = data.split(",");
var username = tokens[0];
var name = tokens[1];
});

How to pass an array of strings from PHP to Javascript using $.ajax()?

I have a PHP script that retrieves names (strings) from database. I would like to pass this array to Javascript using $.ajax().
I cannot understand how should I encode the array in PHP and then decode it in Javascript.
Could someone give an example code for this ?
Thanks a lot !!
<?php // test.php
$myArray = array(1, 2, 3);
echo json_encode($myArray);
?>
HTML File:
$(function() {
$.getJSON('http://localhost/test.php', function(data) {
$(data).each(function(key, value) {
// Will alert 1, 2 and 3
alert(value);
});
});
});
u can use json_encode
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
full example you can read at :
http://www.prodevtips.com/2008/08/15/jquery-json-with-php-json_encode-and-json_decode/
or
http://www.prodevtips.com/2009/12/09/multiple-select-lists-with-jquery-and-json/
<?php
echo json_encode(array('key' => 'value', 'cool' => 'ice'));
?>
json is a javascript object. So there is no need to "decode" it. However, it looks like you are using jquery. There is a nifty function for retrieving json data:
jQuery.getJSON(url, senddata, function(returndata){alert(returndata.cool);})
or
jQuery.getJSON(url, senddata, function(returndata){mybigfunction(returndata);})
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.getJSON/
or you could also do it with $.ajax as you mentioned:
jQuery.ajax({
url: url,
dataType: 'json',
data: senddata,
success: function(data){mybigfunction(data)}
});
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.ajax/
The "callback" is a function that gets called and passed the json data returned from the url.
You will 'ice' baby... ermm... sorry for the corn.
The getJSON method is rather short and handy. Have a look at the links for more details.
This is Php File Code
<?php
$array = array(1, 2, 3);
echo json_encode($array);
?>
Then you can parse $array in your $.ajax() like this
success: function (data) {
var x = JSON.parse(data);
console.log(x);
}
To do this, you'll just have to echo out a script into the PHP page that contains your data, which you can then access from any other Javascript on the page, including jQuery and .ajax().
Again, if you just want to pass it via an AJAX call, just use json_encode():
<?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>
And then process it with the callback functions from .ajax() or, probably better, .getJSON(), which is built for just this use.
I promise I don't just spam my blog here, but I wrote a post on passing variables between Javascript and PHP, because I did it often enough that I came up with a simple/reliable/clean and reusable way to do so. If you're regularly passing data from PHP to Javascript and don't need AJAX, I'll paste the essentials here:
At the top of each external js file, I add comments as to which PHP variables are required, so I can keep track of what I need when I include it (this is optional, of course, but nice):
/* This script depends on the following variables in phpvars:
groupidlist
groupnamelist
serverurl
uid
*/
Then, in the PHP file, I pass the needed variables with a single line of Javascript, assigning a JSON Array with all the needed values. Examples in PHP, directly from my code:
<script type="text/javascript">
var phpvars = <?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>;
</script>
Once that is set up, I can then simply access whatever PHP Variables I need in the Javascript through the phpvars array. For example, if I needed to set an image source using my serverurl, I could do as follows:
imgElement.src = phpvars.serverurl + '/images/example.png';
Because it uses JSON, there is no worrying about making sure that you don't screw anything up in your Javascript by trying to insert the PHP variables. The encoding/decoding of the variables is handled on both ends by built-in JSON functions, so it is very hard to break it, and brainless to pass variables - you pass them like you would any other PHP array. In my fiddling that led to this, I had problems with both of these, and this solution takes care of them nicely.

Categories