AJAX Global Array Storage - php

Long story short, I'm trying to store corresponding data values from a JSON returning AJAX into these global arrays. I know that the arrays are constructing correctly because I've put alerts within AJAX, but when I put it outside the AJAX, the array is still undefined.
How can I export either the entire popData JSON object to work on it and store the values in the global arrays or get the populating of the arrays in the AJAX to carry outside the call? I need these arrays to be accessible by another function to compare the population values to a narrow range of values selected by the user--if anyone wants to suggest a better way of doing this, but it has to pull the population values onLoad which is already done in the HTML. I think this is the most streamlined way to do that with the fewest AJAX calls on the server, but I'm open to suggestions! :D
var popProducers = new Array();
var popProducersCount = new Array();
function getPopulationInfo(){
$.ajax({
url:phpURL,
cache:false,
dataType:"json",
data: { },
success:function(popData){
for (i=0;i<popData.length;i++){
//producers and producersCount should be the same length at all times!
//If current producer name isn't in array already
if(popProducers.indexOf(popData[i].ProducerName) == -1){
//add new element to represent new producer quantity (producerCount.length returns number of elements in the array, thus if there are no elements = 0 thus making index 0 equal to 1 and so on)
popProducersCount[popProducersCount.length] = 1;
//Adds the producer name to the list of producers
popProducers[popProducers.length] = popData[i].ProducerName;
} else {
//Otherwise, it will increment the index of the producersCount array corresponding with the pre-existing producer name's index by 1
popProducersCount[popProducers.indexOf(popData[i].ProducerName)] += 1;
}
}
}
});
alert("Population Data Alert: " + popProducers);

.ajax() and its underlaying XMLHttpRequest() create asyncronous requestes by default. That just means, your alert() statement is encountered before your success handler.
Easy solution here, move that alert() into the success handler at the very bottom.
If you want to deal with it in a more apropriate way, you could use jQuerys Deferred objects in a way like
function getPopulationInfo(){
return $.ajax({
// lots of stuff
});
}
and then call it like
getPopulationInfo().done(function() {
alert("Population Data Alert: " + popProducers);
});
by returning the .ajax() method we implcitly return a Deferred object. Long story short, you can pass in some additional callbacks for success (.done()), error (.fail()) and complete (.always())

Related

Update MY SQL DB Table from jQuery

Based on the user input's, i calculate some values on my submit action of my form. I have to persist these values in my backend DB. I use PHP for my server side scripting. Please let me know the best practice for doing this. It is a single page application and i use .load("Report.html"); to show the summary page.
Just thinking aloud, can i fetch the row(to be updated) from DB, json_encode, update the json object in jQuery, decode it, then update in DB?
Please help...
My submit button code...
$('form').on('submit', function(event)
{
event.preventDefault();
//CALCULATE SCORE
var noOfCorrectAnswers = 0;
var noOfQuestionsViewed = 0;
$.each(questionsArray, function(i, item)
{
if(item.correctOption == item.selectedAnswer)
{
noOfCorrectAnswers++;
}
if(item.isQuestionViewed == 'YES')
{
noOfQuestionsViewed++;
}
});
alert(noOfQuestionsViewed);
$('#sampleDiv').load("UserReport.html");
});
Run some AJAX passing all of the information you need (which may even be none depending on your use case) from the client-side to your server-side PHP. Your PHP script can fetch things from the database if necessary, make any calculations and/or manipulations and then store the information back in the DB.
If you need to return information to your client-side after updating the database then try returning a JSON object (by just printing the code out in the proper format) from your PHP script before exiting with whatever your JS needs.
Do note that this should be all done asynchronously, so you need to setup your AJAX callback function to handle any information that's returned from your PHP script. If you want to do it synchronously, go for it - but you asked for best practices :P
Looks like you're using jQuery - here's the documentation on AJAX
Raunak Kathuria's answer provides some same code
On form submit make ajax call to set database in the db and access the json
$('form').on('submit', function(event)
{ ...
alert(noOfQuestionsViewed);
$.ajax({
url: "yourphp.php", // php to set the data
type: 'POST',
data: 'yourparams', // all the input selected by users
dataType: json
success: function(json){
//here inside json variable you've the json returned by your PHP
// access json you can loop or just access the property json['sample']
$('#sampleDiv').load("UserReport.html", function () {
// its callback function after html is loaded
$('#someid').html(json['sample'));
});
}
})
You can also use the done callback of ajax
PHP
yourphp.php
Set the values here in db running the desired query and return values using
<?php
// your db ooperations will come here
// fetch the db record
// return the db records in json
$responseVar = array(
'message'=>$message,
'calculatedValue'=>$calculated
);
echo (json_encode($responseVar));
?>

Best method of passing large array to PHP

I am trying to find the best method for passing a large array of IDs from one page to the next.
I've built a simple downloadable image site that allows users to select any number of images to download. Right now, when a user selects an image its ID is stored in a JSON string inside a cookie. The problem I've been having is finding the best way to pass the JSON to the review before downloading page.
Currently, I'm sending the JSON as a URL parameter but I'm not sure if this is the smartest solution since the number of IDs in the JSON could reach into the hundreds.
I've looked in PHP sessions but I don't really understand how can I enable the user ability to add/subtract from the variable once the page has been loaded.
$(function(){
$('.download_cart').click(function(){
var urlArray = [];
obj = JSON.parse(getCookie("downloads"));
if(obj != null){
if(obj.items.length !== 0){
$.each( obj.items, function( i, value ) {
urlArray.push(obj.items[i].id);
});
}
}
window.location = cart_url+'?array='+urlArray;
})
});
Try POSTing your data to the new PHP page:
var data = 'urlArray='+urlArray
$.ajax({
type: "POST",
url: 'new_php_page.php',
data: data
});
Now you'll be able to get your variable at $_POST['urlArray'] on your new page.
http://api.jquery.com/jQuery.post/
Consider to pass them in a set of ajax-requests, by 200 (for example, to not overflow input limit) IDs in each request.
Assign urlArray to a hidden field then submit the form, it can parse large no of array to another page

Get global array of arrays from Jquery $.getJSON method to REUSE array

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

Best way to send and process variable sized data

On this page...
http://lab.2toria.com/reflex/index2.php
When the user has dragged and dropped blocks onto the grid, I want to be able to send the positions in some form to a php script that will save them into a table that simply records the coordinates (eg "x1y2", "x1y3", etc) into rows. The fields in my table so far are VERY simple (blockID, blockCoords)
What would be the best way to do this? I'm after your opinion on two things:-
1) Using jQuery ajax, how could I send a string containing the coordinates as a list? Would it be best to create an xml string, or is there another way I've not thought of...and how would I do this
and..
2) Based on the method used to send the data (xml, or whatever), how would I then process the data in the receiving php script to save the data into a table. I know how to save records etc, just wanting to know how best to deal with this situation.
$('element').droppable({
drop:function(event, ui){
$.ajax({
url: '/path/to/my/file.php',
type: 'POST',
data: {'left' : ui.helper.position().left,
'top': ui.helper.position().top},
success: function(data){
//do something with the response from the server
}
});
}
});
And in /path/to/my/file.php
if(isset($_POST['left'])):
$db = new mysqli('connection info here');
$q = $db->prepare('INSERT INTO some_table (left, top) VALUES (?,?)'); //prepare the statement
$q->bind_param('ss', $_POST['left'], $_POST['top']); //safe binding
if(FALSE !== $q->execute()):
return 'Query Executed!';
endif; //execute the statement
return false;
endif;
So in the php file we're simply checking for the existence of the $_POST variable left. We assume top will be available also. We make a mysqli connection, prepare a safe statement, bind the parameters as strings, using the $_POST left/topvalues. Then we check if the execution didn't return false (returns true/false), and if it didn't, we pass a value and exit out of the conditionals all together. If not, the return false will fire by default.
Edit
From your comment, you want to save the actions that the user performs until ready to actually perform the insert, that's easily doable as well.
var dc = 0,
drops = {};
dc will be the dropcount, and drops will be an object.
$('element').droppable({
drop: function(event, ui){
drops[dc] = {'left' : ui.helper.position().left, 'top' : ui.helper.position().top};
dc++;
}
});
In the above, we simply increment through the drops object, storing the information for the left/top values on each drop.
$('.save').click(function(e){
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: {'drops': drops},
success: function(data){
console.log(data);
}
});
});
Here, we have a save button with a class of save, we prevent the default action, then we sent the drops object to the server.
if(isset($_POST['drops'])):
//same process as outlined above, use a helper function to insert the rows
endif;
Now we check for the existence of the $_POST variable 'drops', we'll employ the same tactics as above. I would simply recommend a helper function saveDrops($obj), iterating the returned drops and performing a save for each obj passed in.
1) Yep, use jQuery ajax posting the coords and block id.
2) They will be available to php in the $_POST variable.
See:jQuery Post

Create mysql table from a query run on another PHP page

I have a PHP page that processes some information when a button is pressed. One of this information is to process a query. I then want the results of the query to be put into a table in another page. I know how to put query results into a table, but I don't know how to pass them row by row to a table on another page. Can anyone help or point me in the right direction?
If I understood this correctly, you'll need AJAX (and, by requirement, JavaScript) for this. What you want to do is call your generation function and have it return a format that you can parse (JSON, XML, you name it).
From there, you'll append it to your table using JavaScript's DOM manipulation functions.
The generation part
Assume that you're getting your data in an array format as follows:
$row = array('column 1','column2');
You'll be getting tons of rows like these, or just one - we'll write the script to handle both cases without requiring a rewrite. Every time you get a row, add it to a non-associative array , call it $RowArray. So, on every row, you'll be calling $RowArray[] = $row;.
You now have the PHP side almost done - all you need to do now is to echo it back to the client. Make sure you echo nothing else but this: echo json_encode($RowArray);. This will format and serialize your array to be a perfect JSON object.
The JavaScript side
We'll assume jQuery for simplicity. Your aim will be to read the JSON object and add rows to a table. We'll assume that the table has ID #MyTable.
The AJAX call is done as follows:
$.ajax({
url: "your_url.php",
dataType: "json",
type: "post",
success: function(d) {
// Your code here
}
});
The success handler will be triggered when the object has been successfully parsed, and the variable d will be the object. This object will be a JavaScript array where each element is an object. All you need to do now is to loop through d and create a row per entry!
success: function(d) {
for(var i=0; i < d.length; i++) {
var newRow = $("<tr></tr");
for (var k in d[i]) {
newRow.append($("<td></td>").text(d[i][k]));
}
newRow.appendTo($("#MyTable"));
}
}
Voila, dynamic AJAXified table in six lines!

Categories