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!
Related
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));
?>
I am trying to execute a specific query where I search for the name that i get using javascript. I have this HTML:
<a onmouseover="showDef(textContent)" href="aLinkHere.com">myWord</a>
The function showDef gets the myWord and I'm trying to execute my query after that.
<script type="text/javascript>
function showDef(txt) {
var myWord = txt;
//Some code here to execute the query?
}
</script>
The query I want to have is as follows:
mysql_query("SELECT * FROM defs WHERE name='myWord'");
Now I have to replace the 'myWord' with the word stored in the javascript variable. Is there any way to this? I already tried the following, but that didn't work..
document.write('<?php $data = mysql_query("SELECT * FROM defs WHERE name=\''+ myWord + '\'"); ');
I am relatively new in javascript and php, so any help is very much appreciated!
Javascript is client side language and you need php (server side) lang to execute query.
Create ajax request with that variable and use that variable in your query.
return that response from your remote php file and catch response in javascript. And enjoy with response.
IF you are searching name only(exact) then use = else use LIKE or REGEXP for better performance
This is an example that uses the jQuery library.
var dataString = 'searchVar='+ myWord;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data){
alert(data)
}
});
IN php code you jst get variable with $_POST['searchVar'] and execute your query
$qry = "SELECT * FROM defs WHERE name LIKE '%".'$myWord."%'";
and in while loop jst echo you response.
You're relatively new indeed, this is basic strings 101.
1) do NOT use document.write, it's not meant for you to be used, it's an API from a decade ago and doesn't do what you think it does. Find the element you want to set the content of (using document.getElementById or the like) and then use .innerHTML = ... to set its content.
2) To get your value in your query on the PHP side, just put it in there, it's one of the basic features of PHP:
$myword = sanitize_the_hell_out_of_this($_POST['myword'];
mysql_query("SELECT * FROM defs WHERE name='$myword'");
You can pick whatever method you like for sanitization, there are a few baked into PHP but do NOT, under ANY circumstance, pass the posted value straight to your database, unless you like people deleting your database because they can. Someone can just edit the html, change the single word to "'; drop table words; 'lo" and now your table will get dropped. fun times =)
In order for it to actually work, remember your page runs on the client's computer, and PHP is a server technology. So the javascript will have to ask the server for the data by literally asking the server: you'll need an AJAX get or post operation, and then work with the data that get back. You can't inject PHP code and then have it run on the user's computer.
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!
the reponseText should be like this on PHP
echo "<script>alert('test')</script>";
But nothing happen. How do I return Javascript code?
An ajax call is up to the caller to decide what to do with it (depending upon what type of data is returned). In this case, if your caller isn't prepared to execute this, then nothing will happen with it. Depending upon what the real code wants to do here, there are a number of different possibilities for handling the returned result from the ajax call.It could be formatted as JSONP so it calls a function in your main page code to process the returned data. You could return full JS (without the tags) and do an eval() on it after the host page (generally not considered a wise idea due to some security risks) or it could be just added to the current page and let the browser just parse whatever you put in there.Usually, an Ajax call returns pure data and your host page code processes that data and holds the code for deciding what to do with it. This is the safest mechanism because there's no way for anything that hijaacked a connection to inject code into your page (all it can do is change the data).
You've returned it as text. Now all you need to do is insert that text onto the page somehow:
document.body.innerHTML += response;
There's a lot going on, and a lot of assumptions made, but that's the simplest way to do it.
(Well, that's not entirely true. The easiest way to do it would be to just return the JavaScript, and then eval it.)
here's a simple example. But don't include the <script> tags for this tough
$.ajax({
type: "GET",
dataType: "text",
url: "jsLoader.php",
success: function(data){
eval(data);
}
});
I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql