I have found many threads regarding this issue, but unfortunately I couldn't get it running. Problem is I don't know much about JQuery.
I am trying to make an Ajax call using JQuery in order to fetch multiple records from a mysql database. I have the following function :
function updateWebpage ()
{
$.ajax({
url: './sale/api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var username = row[0];
var stateId = row[1];
$('#output').append("<b>id: </b>"+username+"<b> stateId: </b>"+stateId)
.append("<hr />");
}
}
});
};
My api.php is executing a mysql query with something like this:
$array = retrieveUsersInfo('%'); //fetch result
echo json_encode($array);
My main issue, is how to debug an issue like this? Since ajax is calling asynchronously another file, I cannot view any errors. From my firefox debugger, I can see that the $.ajax function is entered, but success is not.
Thanks in advance.
a couple things to try.
hit the api url directly in a browser (not through ajax) and make sure it returns the valid response.
add an error: function(err){} to your jquery ajax call. this method will get called if there is something other than a 200 response back from the server.
I use Chrome's developer tools more than firefox/firebug. It has a Network tab in it that shows me all the communication between the client and the server. You should see a call out to your api in that tab.
just off hand, i think you need to make sure the mime-type is set to text/json in your php file.
Related
I am new to php and am trying to update a hidden field value inside a php function and can't see to find a solution that works.
In template.php I have:
<input type="hidden" id="variable_ID" name="variable_name" value="variable_value">
This works fine.
However I need to update the value of the variable to the record ID of inserted record in a function in functions.php eg
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
// *** Set Hidden field value to $get_record_id here ***
}
I have tried a myriad of things but can't seem to find a solution.
Any pointers on how to solve this problem?
Here is the solution I used - thanks to #Steven and #El_Vanja for direction.
(I may need to change the question title now though because what I actually needed to do was return a variable to javascript from PHP using Ajax. I didn't need to use hidden fields).
PHP
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
echo json_encode($get_record_id);
exit;
}
JS
jQuery.ajax({
url: ajax_url,
type:'POST',
data: {
action: "myFunction",
anydata:"to be posted"},
success: process_record_ID
});
function process_record_ID(data_returned_from_myFunction){
recordID = data_returned_from_myFunction;
}
Hope this helps others!
Notes
I believe that we have to declare 'process_record_ID' as a separate function outside of AJAX because AJAX is asynchronous. If we define the function in the success handler, the function runs in AJAX before the value is actually returned from PHP.
In the AJAX success handler, we don't need to explicitly list the 'data_returned_from_myFunction' variable in the call to process_record_ID function. When the data is returned to the AJAX success handler from PHP, it still gets sent to the function.
Additional answer
You're correct AJAX is an asynchronous construct which means that certain tasks can be carried out before you might expect them to (from a synchronous perspective).
For example we can (as per the code in the original answer) use jQuery to update the value of a field directly in the success handler.
We can't update a JS variable directly, i.e:
some_variable = response.value;
If you attempt it the variable some_variable will likely be undefined.
The difference comes down to callbacks:
Callbacks allow the asynchronous function to call a function after it completes. Where as setting a variable happens on the spot.
There are two easy ways to solve this issue then:
Create a function outside of the AJAX request and allow it to callback that function once the AJAX request has completed -- as you've already discovered.
Use the complete option inside of your AJAX request.
Using a call back
Firstly we need to define out variable to be updated and the function which we will use to update it:
var inserted_id = "";
function update_id(data){
inserted_id = data.record_id;
}
Then we can make out AJAX call:
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : update_id
});
N.B.
Calling update_id in this fashion means we pass the entirety of the returned JSON object; not just the returned number.
Alternatively...
var inserted_id = "";
function update_id(data){
inserted_id = data;
}
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response){
update_id(response.record_id);
}
});
This method is effectively the same but we only pass the returned number to the update_id function.
Using complete
complete works the same way as success however activates once the AJAX request is... complete...
var inserted_id = "";
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
complete: function(data) {
inserted_id = data.responseJSON.record_id;
}
});
Original answer
Having not seen the rest of your code giving a complete answer is tricky. However, this should set you on the right track:
PHP
Firstly, in your PHP you need to make sure and output the data that you want returned to the webpage. In this case we want to return the insert id of the newly created record; to do this we're going to output a JSON object so that the AJAX call can interpret the value and update the page:
function myFunction() {
$mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
echo json_encode(["record_id" => $mydb->insert_id]);
exit;
}
N.B.
We don't want any output other than the JSON string. Hence exit has been used after the echo. You may want/need to adjust the echo and exit to fit with the rest of your code etc.
JS
Now that we have our PHP returning usable data to our ajax call (which should look something like the below) we can take the returned data aka response and update the value of the hidden field accordingly.
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response) {
$("#id_of_hidden_field").val(response.record_id);
}
});
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
I use ajax type for send data to php file and get response and show. In my php file i have
while($i<14){ echo $i.'<br />'; $i++;}
that return 14 replay.
So, my webpage when call data with ajax method, after some secounds, show all 14 results. But i want get live response from my ajax file.
So i want my webpage show :
1
...
and then
1
2
....
etc
This is my Ajax code that return all response together in shower div.
I want get live responses. for any responses that sent from php file
function update_table(uptype){
$("#shower").html("Loading...");
var dataString = 'type=' + uptype;
$.ajax({
type: "POST",
url: "motor.php",
data: dataString,
cache: false,
success: function(html) {
$("#shower").html(html);
}
});
return false;
}
What you are asking is not possible with your current setup.
Think of an ajax-call to a PHP-script is like visiting a website like www.example.com/yourscript.php
PHP will then server-side render a code which is sent to your web-browser. This is a one call and one answer operation. PHP will not dynamically add elements to the website. Neither will it then be able to dynamically send answers to your ajax-call. What you have to do to solve this is storing the progress of the PHP script somewhere, and do several calls to get a update on the status.
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
I have Ajax file in which code has written to accept values form user and then these values are taken in a Ajax function as follows:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(){
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
});
});
The function for passing values and getting values from other file:
function sendValue(str,name){
$.post(
"newsletter/subscribe.php", //Ajax file
{ sendValue: str,
sendVal: name
},
function(data2){
$('#display').html(data2.returnValue);
},
//How you want the data formated when it is returned from the server.
"json"
);
}
and these values are passed to another file called "subscribe.php" in which insertion code to database is written and again I return the value to my first ajax function as follows:
echo json_encode(array("returnValue"=>$msg));
The msg is ging to contain my message to be displayed.
But now, this works fine on localhost, I get the return values nad message properly but when I upload it on server this gives me an error as:
data2 is null
[Break on this error] $('#display').html(data2.returnValue);
This only gives error for return value but insertion, sending mail functionality works fine.
Please provide me with a good solution wherein I can be able to get back the return values without any error.
Thanks in advance.
If it works on your development site, I suspect the error to be in your PHP script.
Your host might run an ancient php version which does not have json_encode().
Simply call the script manually to check its output. If it requires POST you could write a form or check the result to your ajax call with FireBug
Without additional explanation why this is happening, try this:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(e){ // added the e paramenter
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
e.stop(); // dont submit the form normaly
});
});
If you have firebug, write data2 to its console and see what it is:
function(data2) {
console.log(data2);
$('#display').html(data2.returnValue);
}
In addition, you can use firebug net panel to see your php file raw response (if it has error - you will see it there).
Use that:
var response = $.ajax({
type : "POST",
url : "newsletter/subscribe.php",
dataType : "json",
async : false,
data : "sendValue="+str+"&sendVal="+name
}).responseText;