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

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

Related

Javascript code running fine until put into a function

I have taken some source code from here to submit a form using AJAX. The form is basically taking some information from a user and putting it into a database via PHP. The code I have works, but given that what I am working on has many forms all doing the same thing, I - obviously - want to make sure my code is lean and mean. So, making sure that each of my form field names have the same as my database with some matching IDs for various parts of the form for user feedback, have changed it to the following:
<script type="text/javascript">
$(document).ready(function() {
// process the form
$('#formId').submit(function(event) { // for the specified form:
// completeForm('#formId'); // WHERE I CALL THE FUNCTION
// FUNCTION STARTS HERE WHEN IT IS ONE
var formData = {}; formId = '#formId';
$(formId + ' input, ' + formId + ' select, ' + formId + ' textarea').each(
function(index){ // for each item (input, select, textarea in the specified form
var input = $(this);
// First, clear any existing formatting that has been added by previous form inputs
$('#' + input.attr('id') + '-group').removeClass('has-info has-error has-success bg-error bg-info bg-success');
// Next, add data to the array of data to pass to the PHP script
Array.prototype.push.call(formData, input.val());
}
); // End of loop through each item.
// Now the data is collected, call the requested PHP script via AJAX.
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(this).attr('action'), // '/processing/general_settings_processing.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html' // 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// Return success and error messages to the user
// Code to come once the basics have been sorted out!
});
// FUNCTION WOULD END HERE WHEN IT IS ONE.
event.preventDefault();
});
});
</script>
The code as above works absolutely fine; the relevant PHP file is called and - although I have no processing done in this particular file yet - does its stuff (I have it echoing the $_POST array to a file and returning to view in the console log atm).
However, when I try and make it a function, it doesn't - the console log simply echoes out the source code for this document instead of the PHP array that it supposed to be doing. The function is placed above the $(document).ready line; specified as function completeForm(formID) { . . . } , contains the section of code as noted in the comments and called in the commented out line as shown. So, logically (to me) it should work.
The ultimate idea is to have the function to do this in a file that can be called by all the forms that call it, while the code to call the function is in the relevant part of the page. Some pages will have more than one form using it. (I mention that should even if what I am doing here works, it wouldn't when I come to reuse the code!)
(I'm relatively new to JS and JQuery, although have a fairly good grasp of some programming techniques, mainly these days just in PHP.)
The issue you are having with making that a function is you forget to include the "thisBinding". As a result, when you tried to use the form's action target in your ajax call with this code:
url : $(this).attr('action')
it does not find an "action" attribute - basically the issue is that this is actually window and as a result there is no action attribute. Simply bind this to your function call and your code will work as written.
completeForm.call(this,'#formId');
.call MDN

Access of javascript global variable fails

I'm doing my first mobile app with jquery mobile and phonegap/cordova. All goes great until I create the pages themselves, but as soon as I want to access some variables i access from the remote server, it fails at specific places. I already tried about 30 variations re-writing the same code again - literally spent 4 hours already on outputting a simple var -, but no success, and i simply pulling my remaining hair out now.
Here's my code snip
I have an html file, a js file and a php on serverside, outputting a json answer
php response i get:
{"item":{"ID":"1","fname":"Kris","lname":"Nagy","email":"myemail#email.com","password":"abc123","role":"1","practice":"0","address":"","city":"","zip":"","phone":""}}
login.js
var userName;
function getUser() {
$.getJSON( "http://myserver.com/getuser.php?email=myemail#email.com&pass=absc123", function( json ) {
console.log( "JSON Data: " + json.item.fname );
console.log( "JSON Data: " + json.item.email );
// testing if i have the correct data, console outputs the rigth values
userName = = json.item.fname;
window.userName = json.item.fname;
//trying to assign value to variable
console.log( "Variable data" + window.userName );
// testing if i have the correct data stored, console outputs the right value
});
}
getUser();
console.log( "test outside function" + window.userName );
//gives back undefined
index.html (here I'm just trying to access the variable, sure i have the full html, including the js, jquery and all necessities)
<script>
getUser(); //outputs the values to console
console.log( "test in html" + window.userName ); /*/gives back undefined
</script>
As i need some vars in my html to work with, how do i achieve to be able to output them in the html. This example tries to make some kind of login, but my question is more abotu the variables, as i want to understand them. In my understanding I have global variables with the window. call, but it seems everything but to be global, and I'll need to work with variables all along the app, so its vital i understand them. Though as you see it seems i miss a point, so any help is so appreciated.
I know how to work with php, but as the final product needs to run on cordova, I'm limited to html/js on the client side, and javascript is not my strength (yet).
You could return the promise interface exposed by ajax request from your function:
var userName;
function getUser() {
return $.getJSON(...);
}
getUser().done(function () {
console.log("test outside function" + window.userName);
});
You cannot access userName outside the JSON success callback, since you are assigning teh value only in success callback of an asynchronous method.
console.log( "test outside function" + window.userName ); // it wont work
If you still want to access immediately, make synchronous call by setting one of ajax settings async:false, but the overall goal of ajax is lost

Return result to a PHP variable from AJAX in a jQuery function

So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.
The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......
Main PHP Page:
$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
var selr= null;
if(rowid != null){
selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
$.ajax({ // I believe I need to use AJAX so here is my attempt
type: "POST",
url: "getId.php", //This is another PHP page for the reuslt. See below
dataType: "json",
data: {selr:selr},
success: function(data) {
alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
}
});
}
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call
getId.php
<?php
$rId = $_POST["selr"];
echo $rId;
?>
Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?
Thank you, I love you all.
By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.
It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.
Example of how you can send that data to another PHP page
//Your existing jQuery
success: function(data) {
// alert (data);
var result=data;
$.ajax({
type: "POST",
url: "anotherpage.php",
data: { data: result }
});
}

Trying to pass php array to Javascript [duplicate]

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

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