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];
});
Related
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);
});
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
How can print date and age (in following array) separate by $.ajax()?
php:
$array = array(
'date' => 2011/9/14,
'age' => 48,
);
return $array // this send for ajax call in the jQuery
I want this output by jquery:2011/9/14 & 48
Use $.ajax Methods and setting parameter dataType to JSON for receive data type JSON from PHP file.
Jquery Code:
$.ajax({
url: "getdata.php",
type: "post",
dataType: "json",
success: function(data){
alert("Date:" + data.date + "\n" + "Age:" + data.age);
}
});
if your array data contains string make sure it's closured with quote then make data type JSON with json_encode() function.
PHP Code (getdata.php):
$array= array('date'=>'2011/9/14','age'=>48);
echo json_encode($array);
Echo the encoded array in php page say mypage.php
using
echo json_encode($array);
And use jQuery.getJson in the client side
$.getJSON('mypage.php', function(data) {
alert(data['date']);
alert(data['age']);
});
You need to encode the array as a valid JSON string using the PHP function json_encode. You can then use the jQuery function $.parseJSON to convert it into a JavaScript object. From there you'll be able to do whatever you want with it.
If you do this, you'll end up with an object like:
ajaxDataObj = {
date: '2011/9/14',
age: 48
}
**Edit**
Please see stratton's comment below about using $.getJSON for a more compact solution.
Also, Ben Everard's comment on your original post about using echo rather than return is critical.
You can't just return $array to the browser, the result will be "Array" as string.
YOu have to use return json_encode($array); which returns a string that could be parsed by browser.
If the server-client communication is working alright, then you should do something like this on the client side:
$.ajax({
//configuration...
'success':function(response){
var dateAge = response.date+' & '+response.age;
//put or append the string somewhere.
}
});
Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.
I hope you'll able to help me. I'm fed up of trying things without any solution and php it's just driving me crazy. I'm looking for help because I have a html document where I use ajax thanks to jquery api. Inside this file, in a js function I have:
$.ajax({
type: "GET",
url: "c.php",
data: "dia="+matriz[0]+"&mes="+matriz[1]+"&ano="+matriz[2]+"&diaa="+matriz2[0]+"&mess="+matriz2[1]+"&anoo="+matriz2[2]+"&modo=0&semana=0",
success: Mundo,
error: function(e){
alert('Error: ' + e);
}
});
This code allows me to send the information that I want to the file c.php where I have:
include('funciones.php');
include('config.php');
$mierda = array();
$mierda[0] = $_GET['modo'];
$mierda[1] = $_GET['dia'];
$mierda[2] = $_GET['mes'];
$mierda[3] = $_GET['ano'];
$mierda[4] = $_GET['diaa'];
$mierda[5] = $_GET['mess'];
$mierda[6] = $_GET['anoo'];
$mierda[7] = $_GET['semana'];
As you see it's very simple. My crazy problem is that with firebug I've seen that the data is sent well but for some reason I can't use it. I have tried with $_Get, $_post and $_request and always is the same problem. But this can be stranger... If I put:
echo json_encode($mierda);
then miraculously, the php returns the data that I have passed so in conclusion I have:
I can send the data to the php file well
I can print all the data that I have sent well just accessing yo $_GET, $_POST, $_REQUEST
I can't use any value separatly like $_GET['dia']
What's going wrong there?
PS. The include php files are functions that access to my database so there's no interaction with them.
Your data is not URL-encoded. Try do something like this,
$.ajax({ type: "GET",
url: "c.php",
data: {"dia":matriz[0], "mes":matriz[1] ....},
success: Mundo,
error: function(e){ alert('Error: ' + e); }
});
If you are returning a json value use json to read that.
See
http://api.jquery.com/jQuery.getJSON/
http://pinoytech.org/blog/post/How-to-Use-JSON-with-jQuery-AJAX
Here is an example to read json value
$('document').ready(function(){
$('#submit).click(function(){
$.post('your_php_page.php', {employee_id: '456'},
function(data){
console.log(data.first_name);
console.log(data.last_name);
}, 'json');
})
});
Hope it helps
You have a crazy problem. According to your question:
$mierda = array();
$mierda[0] = $_GET['dia']; //... and so on
echo json_encode($mierda);
works while:
echo $_GET['dia'];
doesnt. Try:
$mierda = array();
$mierda[0] = $_GET['dia'];
echo $mierda[0];
echo $_GET['dia'];
It will show you whether the problem is in the PHP, or the javascript.
I have encoded the data as ZZColer said and the error is still.
Starx, it's not a question of the returning.
digitalFresh, in fact the error is from PHP because I can copy $_POST, $_GET array to a new array and print all this information but if I put after all things like:
If( mierda[0] == 0) {... The element is empty! and if I try directly $_GET['dia'] it says that this element doesn't exist in the array. Also I have tried $_GET[dia] or $_GET[0] without a solution.
PD:
I don't know how but PROBLEM SOLUTIONED!
Thanks to all!