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);
}
Related
Okay so after searching Stack Overflow for answers I found two threads and tried them both but they did not work for me.
Assign data from jQuery getJSON to array
How to get JSON array from file with getJSON?
My issues is I want to work with some data from a database for a mapping utility, however some elements of the JSON dissappear after you call the Jquery method $.getJSON(). I can create them to a 'ul' element just fine. I CANNOT get them to push to an array of array's with any method I have tried yet. I am asking here as I am curious what I am doing wrong. I have thought I may have to traverse the DOM to get the elements once populated maybe but that seems silly to me and I was wondering if there was an easier way potentially. I am a novice at javascript and Jquery but understand programming concepts.
The concepts I am using are this:
I have a SQL Server 2008 database with values:
PlaceID PlaceName
1 Place 1
2 Place 2
3 Place 3
4 Place 4
I can create a PHP script with the 'sqlsrv' driver to get the values and output a
echo json_encode($data);
I can confirm I can return the data from this PHP script in IIS locally. (with all the special jerry rigging you have to do to IIS to make it like PHP)
I can call the php script and display it's data with JQuery library 2.0.3.js using the
$.getJSON('SqlTalk.php')
I can populate elements in the HTML with this, but I cannot get an array of array's for reuse with other objects, which is what I really really want. Ultimately I want to make an entire javascript that just gets an array of arrays from the PHP script and then reference that javascript either embedded or as a reference to use for mapping. However it appears $.getJSON is asychrnonous from my reading but even the methods I am seeing are not working for me to attempt to 'push' to an existing array. It may be that I am misunderstanding syntax when mixing Jquery and traditional javascript as well though.
Complete HTML code where the bottleneck is. Basically PHP will be returning data as shown in step 1 except as a JSON object. This is a simple example to get me beyond proof of concept first. I can push explicitly to the array, and I can generate the child items of the ul element just fine. I cannot push the items from 'getJSON' at all no matter what I attempt at reformating the getJSON method from what I have read.
<html>
<head>
<script type='text/javascript' src='JQuery 2.0.3.js'></script>
</head>
<body>
<ul></ul>
<script>
test = [
{
PlaceID: "1",
PlaceName: "Somewhere"
}
]
test.push({PlaceID: "2", PlaceName: "SomewhereElse"});
function getArray() {
return $.getJSON('SqlTalk.php')
}
getArray().done(function(json){
$.each(json, function(key, val){
//test[key] = { PlaceID: val.PlaceID}; // doesn't work
test.push({PlaceID: val.PlaceID, PlaceName: val.PlaceName}); // also does not work, can't push.
$('ul').append('<li id="' + key + '">' + val.PlaceName + '</li>');
});
});
alert(test.length);
// So I get my output to the 'ul' element fine, but my test array never gets the values.
//I have tried what others have stated and it does not work.
</script>
</body>
</html>
The global will not be updated until after the request is complete.
var getArrayPromise = getArray().done(function(json){
$.each(json, function(key, val){
//test[key] = { PlaceID: val.PlaceID}; // doesn't work
test.push({PlaceID: val.PlaceID, PlaceName: val.PlaceName}); // also does not work, can't push.
$('ul').append('<li id="' + key + '">' + val.PlaceName + '</li>');
});
});
getArrayPromise.done(function(){
alert(test.length);
});
there is no workaround, that's just how asynchronous requests work. The clock keeps ticking and the code keeps executing while the request is being received.
You might want to use the complete callback on the AJAX response
$.ajax({
url: 'SqlTalk.php',
dataType: 'json',
success: function(data){
for (var i = 0; i < data.length; i++) {
test.push({PlaceID: data[i].PlaceID, PlaceName: data[i].PlaceName});
$('ul').append('<li id="' + i + '">' + data[i].PlaceName + '</li>');
}
},
complete: function(){
console.log(test);
}
});
I did a quick jsfiddle ( http://jsfiddle.net/Ar7kX/ ) to show the complete callback in action (using another kind of data and way, since I don't have obviously access to your real data :) ), a more proper one with arrays of arrays to follow in minutes (if I know how I can gather foursquare data from a jsfiddle)
EDIT
Here you can see an array of array in action directly pulled from foursquare http://jsfiddle.net/f38F3/1/ (30 items), hope this reflects the same situation you have pulling data from your php script
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.
Greeting, fellow programmers,
I have a problem.... keep in mind that I'm completely self-taught, so this may be a stupid question, but I've done hours of research and no one seems to have had the same problem..
I'm working on a php project and I need to be able to perform and ajax GET request, but then store the response as a string variable and perform some string methods on it. Is this possible? And if so, how do I do it.
Thanks in advance.
PS: I've been using JQuery's .load() method to perform GET's and POST's.
The following could be a better approach than using the .load function if you have to use it for other things than just interacting with the DOM.
$.get("from-page.php", function(data) {
var manipulated = data.substring(data.length, Math.ceil(data.length / 2));
//any kind of manipulations you want
$("#div").html(manipulated);
});
I'm not sure if you read the docs but it's in here
Look for Example: Display a notice if the Ajax request encounters an error.
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
response should contain the string you want to manipulate.
Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link
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.')
}
})