basically i want to hold a parameter that retrieve value from $.post() call like this:
init = function(){
var lastpage = getLastPage();
}
function getLastPage(){
$.post("getInfo.php",{
last: "yes"
},
function(data){
setLast(data.last);
},'json');
return function setLast(data){
return data;
}
}
so when reach at last post (last page) i should check with lastpage variable that has a value returned from getLastPage() function.
I'm pretty blur with javascript pointer and all. Please help guys.
update (20/4/2010):
I've done the other way around, like this:
init = function(){
getLastPage();
if((page+1) == $("#lastpage").val()){
alert("this is last post");
}else{
page++;
//get info and display to the page here
}
}
function getLastPage(){
$.post("getInfo.php",{
last: "yes"
},
function(data){
$("#lastpage").val(data.last);
},'json');
}
first run the function to temporarily store the value in hidden input tag (lastpage) and then grab the value again to check it whenever i click forward button.
if you all have more appropriate way please tell me.
You should change your code around like this:
$.post("getInfo.php",{ last: "yes" },
function(data){
functionToRunAfterYouHaveDataSometimeLater(data.last);
}
,'json');
The problem with your overall approach is that with AJAX, you're dealing with an asynchronous operation. This means that the function(data) { } portion doesn't run then, it runs later, so your return doesn't actually return anything, it'll be undefined.
Instead of this approach, you need to call $.post() then call whatever function relies on this data to continue as part of $.post()'s callback. After doing that your code order looks like this:
$.post() executes, firing off a request to the server
The rest of your code after $.post() runs
Later when the response comes from the server and you have data, your callback executes
Now continue to do what you need with that data
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);
}
});
The function below grabs a php page, then reloads it every 5 seconds. The only thing coming from that roomdata.php page is a string with a color name (blue, yellow, etc.). I wanted to be able to use that name in the function modifyLight(color), but it's not letting me. I don't know why, but no matter what I tried, it's not treating the variable data as a string, even if I clarify it as one.
Any help is appreciated, thanks!
$(function(){
function loadData()
{
var data = load('roomdata.php');
modifyLight(data);
setTimeout(loadData, 5000); // makes it reload every 5 sec
}
loadData(); // start the process...
});
You are using async ajad calls. You need to configure your request to be sync.
$.ajax(URL, {async : false});
In that way the execution of the next line will be done until the ajax request Is finished.
EDIT
Your function should be like this:
$(function(){
function loadData() {
$.post("roomdata.php", function(result) {
modifyLight(result);
setTiemout(function() { loadData(); }, 5000);
}
}
loadData(); // start the process...
});
The problem with the way you were doing it is that $.load(); only loads something with Ajax and put the content on $('#yourdiv'); It does not return anything. You need an ajax request with something in the "success" event. In the code I gave you, $.post makes an ajax request via post to roomdata.php and then, once the ajax is finnished, it executes the function function(result) { ... }
I have the following function that is called when I click on a button to submit a form:
function dadosFormularios(preenchimentoForm){
//var path = document.location.pathname;
//alert(path);
alert(preenchimentoForm);
//window.location.href = 'wp-content/themes/template/index.php';
var qstringA = '';
//dados dos campos
var nome=document.getElementById("nome").value;
qstringA = 'nome='+ nome;
//alert(qstringA);
if(preenchimentoForm==false){
alert('Please correct the errors in the Form');
}
else{
if(preenchimentoForm==true){
window.location.href = 'index.php?'+qstringA;
return false;
}
}
}
Since I'm using this way of processing the data, how can I alert my page index.php that the data sent by the function arrived on the index? I can't use a if (isset($_POST['button']..) since I send the information by the function and not through the button of the form, right?
window.location.href = 'index.php?'+qstringA;
This line is just redirecting to index.php with a query string ?nome=nome_value.
For example. index.php?nome=nome_value
So, in your index.php You can simply get everything posted with $_GET.
Check it by doing a print_r($_GET); there.
In index.php, you can simply check
if(isset($_GET["nome"])){
//Nome is set
//Do something here
}
P.S. Although, without knowing the other circumstances or reasons behind usage of this function, it can be said that this function is just doing what a simple <form action=index.php> would have done.
P.P.S. Although you have mentioned jQuery in title and also tagged it, I am not sure this function is using any of the jQuery code. I think it is just a simple Javascript function.
If you're using jQuery, check out .ajax(). Just remember, it's asynchronous, so the results may not be what you think they are. You don't need to reload the whole page (which is what your window.location.href = 'index.php?'+qstringA; would do) just to submit information.
If you want to alert or something when the ajax call completes, you can define a function to call on a successful ajax call.
Use ajax() like :
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
http://api.jquery.com/jQuery.ajax/
I have an issue when trying to get Javascript to execute functions in my desired order. I'm trying to get a jQuery modal form to load information based on a certain selection. I have two SELECT boxes that need to be loaded, but the contents of the second SELECT box depend entirely on the selected value of the first SELECT box.
I made the following functions to request the information I need:
function get_Subjects(varID, callback){
$.post("../vars/get_SID.php", { vid : varID },
function(result){
getInfo('tbsubjectdiv', '../vars/findSubjectlist.php?sid='+result);
});
callback();
}
function get_Selectedfields(varID, callback){
$.post("../vars/requestTblock.php", { vid : varID },
function(result){
populateForm('tbWiz', result);
document.form_tbWiz.varname.disabled = true;
$('.trSearch').hide();
$('.trValueset').hide();
});
callback();
}
function get_TextblockType(varID, callback){
$.post("../vars/requestVtype.php", { vid : varID },
function(result){
if(result == 0){ //Opzoeken
$('.trSearch').show();
}else if(result == 1){ //Datum vergelijken
$('.trSearch').show();
$('.trValueset').show();
}else if(result == 2){ //Percentage
//
}
});
callback();
}
The first function checks the MySQL database for the selected value
of the FIRST SELECT field, and loads the results into the second
SELECT field.
The second function requests the rest of the rest of the form data, and populates the form using populateForm(). It also hides
certain parts of my form in preparation for function three.
The third function basically requests which parts of the form have to be displayed, because that's not always the same.
The whole idea behind this is that I want to use populateForm() to populate all of the form fields. In order for populateForm() to properly set the selected SELECT option, the particular SELECT field must first contain the OPTION it needs to select. Makes sense. I try to make sure of this with my first function, which will load all of the OPTIONs. THEN I try to use the get_Selectedfields() to populate all the proper values. This is not what happens though. No matter what I try to do, getInfo() in the first function is ALWAYS being called LAST. This makes it impossible for populateForm() to select the proper option, which is driving me mad.
I'm trying to "force" the execution-order by doing this:
function getTextblock(var_ID){
get_Subjects(var_ID, function() {
get_Selectedfields(var_ID, function() {
get_Textblocktype(var_ID, function() {
// Done
});
});
});
}
When I realised it still did not work the way I wanted, I decided to use Chrome's Developer Tools to check the order in which everything is executed. It all works as expected, but at the very end it jumps straight back to getInfo(), which is part of the FIRST function I called. I'm absolutely clueless as to why getInfo() gets executed last. If this just gets executed at the very beginning, where I want it to execute, it would all work fine.
You have to call the callback in the callback function of the post request:
function get_Subjects(varID, callback){
$.post("../vars/get_SID.php", { vid : varID },
function(result){
getInfo('tbsubjectdiv', '../vars/findSubjectlist.php?sid='+result);
callback();
});
}
function get_Selectedfields(varID, callback){
$.post("../vars/requestTblock.php", { vid : varID },
function(result){
populateForm('tbWiz', result);
document.form_tbWiz.varname.disabled = true;
$('.trSearch').hide();
$('.trValueset').hide();
callback();
});
}
function get_TextblockType(varID, callback){
$.post("../vars/requestVtype.php", { vid : varID },
function(result){
if(result == 0){ //Opzoeken
$('.trSearch').show();
}else if(result == 1){ //Datum vergelijken
$('.trSearch').show();
$('.trValueset').show();
}else if(result == 2){ //Percentage
//
}
callback();
});
}
The POST is being handled asynchronously in your functions so your "callback" is really just being executed almost immediately after your initial call, whereas the callback of $.post is being executed after the post has occurred. Does that help you sort things out? You will probably need to kick off the rest of the process in the callback of $.post("../vars/get_SID.php", { vid : varID }...
$.post is shorthand for $.ajax so you can read up a bit more in the jQuery docs, but I would not suggest switching to synchronous requests. If you absolutely must have one request finished before the next can execute then kicking off that next step from the callback is the way to go.
You're using ajax. The first a is for asynchronous. If you called the functions from the function(result) blocks then they would occur in order.
Alternatively (and this isn't a great idea but you can do it) use the $.ajax() object and set async to false.
As you don't know how long long an ajax request will actually take, you can only chain events within the ajax response:
function getTextblock(var_ID){
$.post(YOUR_TARGET, YOUR_DATA, function(result){
YOUR_CODE
// CHAIN HERE, call new function or sub ajax request
});
}
Wesley,
The javascript will execute always on the predefined order. If you put a bunch of "alerts()" in the middle of your code, you can taste that.
But this is not true for callbacks, because they will be moved to the bottom of execution stack on javascript where we can't determine the order, since they are called by a AJAX return which by definition is asynchronous.
Even though your ajax executes in a millisecond, the callback will not be executed until all methods in your script block have finished.
You have, actually three options:
Chain all the methods sequence in callbacks. Please, don't call a callback!! It inst supposed to be you, but the "system" that will call those.
// The data you need first
function myStartPoint() {
$.post(url, function(result) {
// do what you need with this result (this is your callback, but anonymous)
// then, call the next step
secondPoint();
});
}
function secondPoint() {
$.post(url, function(result) {
// again, the callback is anonymous... your hardly need to declare something named callback
// chain how many points as you need
nextPoint();
}
}
"Force" the ajax to be synchronous with async:false option. This can cause performance issues.
The ugliest of all is to use the damned setTimeout which is very, very wrong, but will work in your case because, the setTimeout will put the method on the bottom of execution stack even after those callbacks which are expected to be fast. Seriously, I just put this option because eventually someone would say it... Do not take this path.
I am executing a php call from javascript(jQuery), php sript is sending result back. The problem is that these php scripts are taking some time (milliseconds), and java script is not waiting for them to finish, thus variables are not getting initialized with correct values.
The code is simple:
$.get("php/validation.php",{'email':email},function(data){
// valid_email now contains true/false
alert(data);
if(data=="true"){
var valid_email = true;}
});
The "alert" is printing true but value of valid_mail is recognized as "false" in the code below. Is there any other better way to call php scripts and wait for until they are not finished?
Prashant
That function(data) is called asynchronously; it waits until after the PHP script has finished. Any code below that $.get() chunk, however, is executed immediately. If you want the code below to wait as well, you have to move it up into that function, or put it into a new function and just call it.
You must react to the response when it is there, not sooner. Of course JavaScript keeps running and does not wait for the response (otherwise the user would notice the thread blocking during the wait). Either you solve it by using a separate callback function, like this:
function checkValidity(email, callback) {
$.get("php/validation.php",{'email':email},function(data){
// execute callback with true or false as the argument
callback(data=="true");
}
}
function showValidity(valid) {
$("#someId").css("color", valid ? "green" : "red");
// probably more
}
checkValidity($("#someField").text(), showValidity);
or by acting right in the success callback of $.get() itself:
function checkValidity(email, callback) {
$.get("php/validation.php",{'email':email},function(data){
$("#someId").css("color", (data=="true") ? "green" : "red");
}
}
You should use a callback to a function to handle the result, you can't use it directly after running the $.get.
See: How can I return a value from an AJAX request?
Thanks for the tip. It has solved most of the problem but one is still giving same problem. The function below is sending the mail but still "false" condition is getting executed.
$.post("php/send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
}
});