Trying to pass php array to Javascript [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have been searching the web like crazy for a day straight trying to figure out why my javascript code is not working. I am trying to pass an array from PHP to Javascript using JSON. After that i want to use it in other functions, thus kinda making the array or variable global. But i have been unable to get it to work, here is my code so far:
data = [];
$(document).ready(function() {
$.getJSON('database.php', function(phpdata){
// vad du vill göra här, allt retuneras i data-variabeln
console.log(phpdata);
data[0] = phpdata[0];
console.log(data[0]);
});
console.log(data);
Any ideas?

When $.getJSON is called, the JS engine will step parallely to the next instruction, which here is console.log(data);. This behaivour is caused to $.getJson's asynchronuality.
Since the next step is calculated and executed in the very next millisecond, the webpage was not fully requested and data is still on its initialized value ([]).
What you can do:
Put all instructions that have to do something with your data in another function and call it on the anonymous function function(phpdata) { ... }.
Like this:
function dataLoaded(data) {
// show data in dom elements
// work with data, e.g. check for data["error"] = true or show the username from data["username"]
}
data = [];
$(document).ready(function() {
// Load JSON from server, wait for it and then work with it in dataLoaded(..)
$.getJSON('database.php', function(phpdata){
dataLoaded(phpdata);
});
}
// this is wrong:
// console.log(data);
It is required that database.php will return an JSON array in the JSON data type. See json_encode and header("CONTENT-TYPE: application/json") on the php manual.
Thanks to the comment for saying: failed case sensitive and data type.

What does database.php do? It should probably be outputting a JSON encoded string.
http://us3.php.net/json_encode

Related

What do I do after I json_encode() my php array?

I am new to both php and javascript and having trouble understanding how to communicate between the two. I have a php array and I used json_encode() to turn it into json and now I just don't know what to do from there. I have just been looking around and haven't been able to find an answer of what to do from there. Do I print it? If I do print it... how do I used javascript to grab it. I can't use the php variable name since javascript doesn't understand it. I am just not grasping this concept.
The most popular way to make a Javascript script communicate with a PHP script is via Asynchronous Javascript And XML (AJAX) requests.
In AJAX requests, your javascript code calls the PHP script needed, sending to it any required parameters. Then, your PHP script should print (echo) the result (the JSON encoded array in your case), and when it does, an event gets fired in your javascript code, which you can handle accordingly.
In Javascript, there are two main ways of performing AJAX requests:
1- Using the XMLHTTPRequest object:
In this method, we are using a Javascript XMLHTTPRequest object to send the request to our PHP script, and we handle its onload event to get the response and do something with it :
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "some_url.php?param1=123");
xmlhttp.send();
xmlhttp.onload = function() {
//here the response from the PHP script is saved in the this.responseText variable
//parsing the JSON string we got into an actual array
var myArray = JSON.parse(this.responseText);
//do something with the array
}
(note that we can also handle the object's onreadystatechange, but onload is a bit simpler to handle)
2- Using a promise (fetch):
fetch("some_url.php?param1=123")
.then(function(response) {
return response.text();
})
.then(function(data)) {
var myArray = JSON.parse(data);
//do something with the array
});

passing variable from java script to jsp script let [duplicate]

This question already has answers here:
How do I pass JavaScript values to Scriptlet in JSP?
(9 answers)
Closed 6 years ago.
I want to pass a java script var to script let in jsp.
i tried many things but not working anything.can anyone tell me a working solution.
i have tried How do I pass JavaScript values to Scriptlet in JSP?
the way this other post stays, is the correct one.
1- create an ajax call (in Javascript) in your webpage to send your desired params to another page.
2- create a page (in jsp) where you request the data sent by the #1.
That's the correct way to go.
#1 Here's an example on how to make an ajax call, you need this on step #1, if your using jquery is simple as:
String data1 = "myData1";
String data2 = "myData2";
String your_jsp_page_to_request = "myJspPage.jsp";
$.post(your_jsp_page_to_request,
{ param1: data1, param2: data2 },
function(data){
alert("Data Loaded: " + data);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
#2 Then in your jsp you need to request the data sent, just using:
String data1 = request.getParameter("param1");
String data2 = request.getParameter("param2");

Javascript scope of array and converting js array to a php array

Edit/Clarification: I have a php page, call it displayPhotos.php, in which I set up an Ajax call to a different php page, call it getPhotos.php, which queries a database and returns photo information (caption, file name etc) to displayPhotos.php where they are displayed. I use php in displayPhotos to manipulate the data returned from getPhotos. The returned data from the Ajax call is a javascript 2-dimensional array. I need to turn the javascript array into a php array so I can do they display and other stuff. How do I do that?
Hope this helps.
My eyes hurt from reading all of the docs.
I want to use ajax to query a database, return the data then use php to continue with the web page.
All of the examples I've looked at start with creating the json in php. I need to start with the json object in javascript.
<script>
var photoarray = [];
var ajaxRequest = $.ajax
({
url : "fhs_get_photos.php",
type: "POST",
dataType: "json",
success: function(photo_array)
{
photoarray = photo_array;
//line below works. the file name is correct but disappears
//outside of this function
console.log("photoarray[0][file_name] is: " + photoarray[0]['file_name']);
},
error: function(request, status, error)
{
alert('An error occurred: ' );
}
});
In this instance I'm not passing anything to the php file that query's the db. The console log shows that the file name in photoarray is correct but once outside of this function it disappears even though it's declared as global, I think it is anyway. Why and what do I need to do to fix this.
The php file just does a SELECT * FROM..... and returns everything.
// in fhs_get_photos.php
// SELECT * FROM table......
echo $json = json_encode($result);
return $json;
So I now have the array back but it's in javascript. Once I figure out the scope problem, how can I convert this javascript array to a php array?
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<figure id="photo_figure">
<script>
//line below gets me: SCRIPT5007: Unable to get property 'thumb' of
//undefined or null reference
console.log("photoarray thumb: ") + photoarray[0]['thumb'];
</script>
Am I explaining this properly?
First of all AJAX is async. This means it sends the request when you ask it to, but receives the response sometime later in the future. And it works after php has rendered and sent the page. So. When you get an update via AJAX, you have to use javascript to make that update matter. The most simple solution is to process the response right there in the success callback. That way you don't need to mess with the global scope (which is a bad practice).
Supposedly, your HTML is like this:
<header>
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<div id="figures"></div>
You can do it by declaring a function that handles the processing:
function updateDom(photoArr) {
var $figures = $('#figures');
$.each(photoArr, function() {
console.log(this);
$figures.append('<img src="' + this.thumb +'">');
});
}
Code below is placed in the success callback
And execute that function in the success callback and pass it the array from json, that was parsed and became a valid js object.
var photoArray = JSON.parse(photo_array);
updateDom(photoArray);
here's the fiddle, but it's for the DOM part only

load entire json file into variable as array

I want to take an external json file (locations.json) and load the contents into a variable. I would then like to use this variable using the information provided here: http://www.json.org/js.html
I've had a lot of trouble trying to load the external json to a variable. I've looked at this ( load json into variable ) page quite a bit, and none of that actually populates the variable. When displaying the variable's contents later, it appears to be empty.
$("#testContain").html("<p>" + json + "</p>");
Using methods listed in the last link, this dispays "undefined".
The json file that I am using looks like this:
[{"id":"1","locname":"Dunstable Downs","lat":"51.8646","lng":"-0.536957","address":"Chiltern Gateway Centre","address2":"","city":"","state":"England","postal":"","phone":"","web":"http:\/\/www.nationaltrust.org.uk\/main\/w-dunstabledownscountrysidecentrewhipsnadeestate","hours1":"","hours2":"","hours3":""},
{"id":"2","locname":"West Delta Park","lat":"45.5974","lng":"-122.688","address":"N Broadacre St and N Expo Rd, Portland","address2":"","city":"","state":"OR","postal":"","phone":"","web":"http:\/\/en.wikipedia.org\/wiki\/Delta_Park","hours1":"","hours2":"","hours3":""}]
Anyone have any suggestions?
The problem is that the request is asynchronous. You could make a synchronous call as suggested by the accepted answer to the question that you linked to, but that is generally not a good idea as it will freeze the browser completely while it is waiting for the response.
The variable is assigned just fine, but when you use it after requesting it, you have to make sure that it's after getting the response, not just after sending the request. Using the value in the callback for the getJSON method is the easiest way to make sure that you have the value:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
// here you have the value
});
// here you don't have the value, as this happens before the response arrives

How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});

Categories