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!
Related
Basically I have two sliders on my page, whenever their value is adjusted they reference a script which returns a JSON array holding values about products which meet the new criteria.
In my success callback I want to call my PHP class which renders my view to the screen ( I am aware that I could probably achieve this effect in Javascript, but I already have a PHP class built which handles all of the required logic, so it would be simpler if there was a shortcut.
My AJAX method looks like this:
function update_results(values)
{
var json = JSON.stringify(values);
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?cache=" + (new Date().getTime()),
data: { query : json },
cache: false,
success: function(data) {
// Remove the old data from the document
$('tr').remove();
// Build the new table rows using the returned data array
$('table').append("<?php Table t = new Table(data); ?>");
}
});
}
Calling my Table constructor builds everything I need just by passing the JSON array I recieve back from my AJAX call, however nothing is being rendered to the screen at the moment - is there any way of doing this?
PHP runs on the server...JavaScript on the client... "<?php Table t = new Table(data); ?>"
does not magically work with the Ajax call. The server should be returning the table when you make the Ajax call.
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));
?>
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())
So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.
I have an ajax call made with jQuery, something like this:
$.ajax({
type: "POST",
url: ajaxurl,
data: data,
success: function(response){
alert(response);
}
});
I get data from PHP like this:
$data_array = get_data();
foreach($data_array as $data)
{
echo $data;
}
PHP to slow
The PHP data function call is slow because it gets very much data from the database, might fetch images, make some json calls and other slow things.
One loop round at the time
Therefor I need to get the PHP code just do one round, then Javascript and then do the next round in the loop.
More than one way to solve it?
There might be more than one way to do it. Which one is prefered? Javascript foreach-loop, JSON and global Javascript variables comes to mind.
You can set the return type in your ajax function as xml or json, and then return you array in either of these types. I feel that JSON js the preferred one for your solution.
I'm slightly against storing actual images in the database. I prefer to only keep a unique link for them and then return that instead of the actual image. This would speed the query up a fair bit. I agree with mad_programmer that the JSON js would be preferred for your situation.
You could manipulate your query to do a limit. So something like:
var total_count = ajax_get_sql('select statement with count');
var curr_count = 0;
var set_number = 10;
var select_statement_without_limit = 'statement';
setTimeout('fetch_data()',0);
...
function fetch_data()
{
if(curr_count < total_count)
{
ajax_get_sql(select_statement_without_limit with limit appended);
curr_count = curr_count + set_number;
setTimeout('fetch_data()',0);
}
}
With all your ajax calls set to wait for a response instead of continuing. I would keep the sql logic in PHP, but use javascript to query the server many times. This will prevent your JS script from giving long execution errors. I haven't really taken into account data manipulation, but you can probably figure it out!