I have been playing with JSON/PHP/JS today and I am having problems..
My PHP works fine which gets a row of data from my SQL table then encodes as JSON.
My JS/Jquery file loads the data from the PHP file fine using $.getJSON.
However, when i try and use the data later in the page like so: gender = user['player'].gender, I get
user.player is undefined.
This is my code that is relevant:
function getUserInfo() {
var url = "./php/getUserInfo.php";
$.getJSON(url, function(data) {
$.each(data.members, function(i, dat) {
user['player'] = {
gender: dat.gender,
fname: dat.first_name,
lname: dat.last_name,
username: dat.username,
};
});
});
}
user = {};
getUserInfo();
//Displays an object, which has the correct information I want.
console.log(user);
var gender = user['player'].gender;
console.log(gender);
the last line of code gives me the error that user.playe is not defined. but it should display male
Help would be helpful, I have tried many things to fix this but cant seem to do so.
$.getJSON is Asynchronous.
As soon as the request is sent , it goes to the next line and does not wait for the request to be completed.
So when you try to access the variable , it is still not available..
Try putting that piece of code after the $.each and it should work.
Related
Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});
I have found many threads regarding this issue, but unfortunately I couldn't get it running. Problem is I don't know much about JQuery.
I am trying to make an Ajax call using JQuery in order to fetch multiple records from a mysql database. I have the following function :
function updateWebpage ()
{
$.ajax({
url: './sale/api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var username = row[0];
var stateId = row[1];
$('#output').append("<b>id: </b>"+username+"<b> stateId: </b>"+stateId)
.append("<hr />");
}
}
});
};
My api.php is executing a mysql query with something like this:
$array = retrieveUsersInfo('%'); //fetch result
echo json_encode($array);
My main issue, is how to debug an issue like this? Since ajax is calling asynchronously another file, I cannot view any errors. From my firefox debugger, I can see that the $.ajax function is entered, but success is not.
Thanks in advance.
a couple things to try.
hit the api url directly in a browser (not through ajax) and make sure it returns the valid response.
add an error: function(err){} to your jquery ajax call. this method will get called if there is something other than a 200 response back from the server.
I use Chrome's developer tools more than firefox/firebug. It has a Network tab in it that shows me all the communication between the client and the server. You should see a call out to your api in that tab.
just off hand, i think you need to make sure the mime-type is set to text/json in your php file.
It's embarrassing to have to ask, but I freely admit I'm an unseasoned Javascript developer, and I just can't figure this out. Hopefully, this will be dead simple for someone else, and I want to thank everyone here ahead of time for the help this site continually provides me.
A couple days ago, I asked this question, and am no longer getting that error. But I've run into a wall trying to actually access the data stored in the variable. My JSON looks like this:
[
{"id":"1","name":"Bob","haircolor":"Brown"},
{"id":"2","name":"Carol","haircolor":"Red"}
]
It's going into a variable like this:
var people=[];
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people.push(data);
});
Thanks to initializing people as an array, I no longer get any error messages. But I can't access the contents of people, either. people.length returns a 0, and people[0] and people[1] are undefined.
It's there, I know it's all there, but I'm having a devil of a time figuring out where.
people only gets values after the ajax event happens.
Call some callback function after you put the data into the people array.
Try with this: http://jsfiddle.net/hUq7k/
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
$.each(data, function(i, people){
console.log(people.id); //<------this should output "1, 2"
});
});
make sure you are getting the response data.
The following should work, if the server is actually returning the expected JSON:
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
var people = data;
alert("people.length: " + people.length);
if (people.length > 0) {
alert("people[0].id: " + people[0].id);
}
});
The following should not work, i.e., people will be undefined, because $.getJSON is an asynchronous method and this code is attempting to access people before the AJAX operation has completed.
var people;
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people = data;
});
alert("people.length: " + people.length);
if (people.length > 0) {
alert("people[0].id: " + people[0].id);
}
i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.
I have Ajax file in which code has written to accept values form user and then these values are taken in a Ajax function as follows:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(){
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
});
});
The function for passing values and getting values from other file:
function sendValue(str,name){
$.post(
"newsletter/subscribe.php", //Ajax file
{ sendValue: str,
sendVal: name
},
function(data2){
$('#display').html(data2.returnValue);
},
//How you want the data formated when it is returned from the server.
"json"
);
}
and these values are passed to another file called "subscribe.php" in which insertion code to database is written and again I return the value to my first ajax function as follows:
echo json_encode(array("returnValue"=>$msg));
The msg is ging to contain my message to be displayed.
But now, this works fine on localhost, I get the return values nad message properly but when I upload it on server this gives me an error as:
data2 is null
[Break on this error] $('#display').html(data2.returnValue);
This only gives error for return value but insertion, sending mail functionality works fine.
Please provide me with a good solution wherein I can be able to get back the return values without any error.
Thanks in advance.
If it works on your development site, I suspect the error to be in your PHP script.
Your host might run an ancient php version which does not have json_encode().
Simply call the script manually to check its output. If it requires POST you could write a form or check the result to your ajax call with FireBug
Without additional explanation why this is happening, try this:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(e){ // added the e paramenter
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
e.stop(); // dont submit the form normaly
});
});
If you have firebug, write data2 to its console and see what it is:
function(data2) {
console.log(data2);
$('#display').html(data2.returnValue);
}
In addition, you can use firebug net panel to see your php file raw response (if it has error - you will see it there).
Use that:
var response = $.ajax({
type : "POST",
url : "newsletter/subscribe.php",
dataType : "json",
async : false,
data : "sendValue="+str+"&sendVal="+name
}).responseText;