jquery to php (wait for php script until result/finish) - php

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);
}
});

Related

Preventing AJAX-called PHP-Script to execute a function

I have an ajax call of such form:
$("#assignDesigner .save").click(function(event) {
event.preventDefault();
$.post("/cms/cms/php/update_di_user_designer_meta.php", $("#assignDesigner").serialize(), function(response) {
alert("Update " + (response ? "worked" : "failed"));
var data = {
promoted_header: $(".product-promotion .rightcol > h3").html(),
promoted_content: $(".product-promotion .rightcol > span").html(),
promoted_owner: $("#designerSelection").val()
};
$.post("/cms/cms/php/create_di_promoted_products.php", data, function(response_inner) {
$("section.product-promotion").replaceWith(response_inner);
})
})
});
My PHP-Script looks like this:
<?php
function insertCode($param)
{
...many echos...
}
if (isset($_POST))
{
insertCode($_POST['param'])
}
?>
When called via AJAX the function should take the POST-Data in the insertCode function. When required or included the function is called with a different $param.
The Problem is, when I send my AJAX-Request the function is executed twice. First before the POST-Code is evaluated. So all the echoed text is sent back twice to the AJAX-Success-Function.
I have then tested whether the echoed text is sent back ich I comment the lower part with the test and yes even then the code of the function is echoed although I have never called the function.
How can I prevent the AJAX-call to help himself calling the function?
You could simply, check within the PHP file, who or what is requesting the PHP file!
// If the request came from AJAX then do this
if ($_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest") {
// Perform Ajax related stuff
}
else {
// Perform non-Ajax related stuff
}
Though, take in mind that headers can always be faked!
I have resolved the issue now and there were two problems.
First in my click-event-handler I used the response to replace the contents of a specific tag. But as long as there was an error in the PHP-Script the tag wasn't created again within the script which caused the output to stack on the page.
Secondly there was a bool variable in the PHP-Script which was not set when requested by the AJAX-Call.
Nontheless thank you for your answers. They helped very much resolving.

Execute php from javascript

I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.

Have one function to wait for an AJAX call, without synchronous AJAX(SJAX)

I am creating a dynamic todo-list on a webpage. On the page you have a form for registering todo's and a table showing all the registrated todo's. The idea is that you register something you want done in a form, hit the submit button, and then the todo-list-table is automatically updated with the latest registered todo. My script manages all of this except for automatically updating the latest registered todo.
Here's my code:
$(document).ready( function() {
$('#todo_registration input[type="submit"]').click(function(evt){
evt.preventDefault();
var todo = $('#todo_registration input[name="daily_todo"]').val();
$('#todo_registration input[name="daily_todo"]').val(null);
$.when( registerTodo(todo) )
.then (
updateTodoDisplay()
);
});
});
function updateTodoDisplay() {
$.post("./daily_todo_display.php", null, replaceTbodyHTML);
}
function replaceTbodyHTML(data) {
$('#todo_display_table tbody').html(data);
}
function registerTodo(todo) {
var parameters = {
daily_todo: todo,
registration_button: 'clicked'
};
$.post("./daily_todo_registration.php", parameters); //, printRegistrationStatus);
}
I have checked that the script successfully registrates the todo in the database. The php-script that gets the updated todo-list also works. My problem, I think, is that the function updateTodoDisplay() doesn't wait for the AJAX call in registerTodo() to successfully complete before it runs. But I thought my use of #.when() was supposed to make updateTodoDisplay() wait.
I know making the AJAX call synchronous would probably fix my problem, but in my opinion that is a bad solution. I only want this one and only function to wait for the AJAX call to complete. Thus I want the rest of the webpage to function while these calls are made.
Any one know a fix for my problem? Thnx.
What you need is possible, but it looks like you have an error in your code.
Change the
.then (
updateTodoDisplay()
);
to
.then (function(){ updateTodoDisplay(); } );
or even
.then (updateTodoDisplay);
The problem is that when you are registering the callback, in your current code you are passing the result of executing updateTodoDisplay() instead of passing it as a function. That is why you get it executed right away.
You should $.post your data, AND when server-side updating is done, respond from server-side too - sending text/json/xml back to the UI. You save one (the second) request with that, you keep ajax asynchronous, you keep your code shorter/more-maintainable, and you get rid of this issue. =)
$.post("url/todo.php", params, function (data) {
// callback
// do UI update here
// "json" but you can say "xml" too
}, "json");
All you need to do is to figure out your server-side response.
jQuery.post()
Have a nice time implementing! =)

Setting a PHP $_SESSION['username'] using a jQuery $.post call and a callback method

I've researched and played around a fair bit, but I am stumped. Essentially I want to setup my site so that it can detect if a user is 'logged in' and thereby change the way it looks: removing the "Sign In" link and replacing it with a "Sign Out" link, and so forth.
For testing purposes I started my index.html page with:
<?php
session_start();
$_SESSION["username"]="javaman";
?>
Next, I call my setup function from within the jquery document.ready:
$(document).ready(function() {
setup_page();
};
The setup function looks like:
function setup_page()
{
var username = get_user();
//check for error
var index = username.indexOf("error");
//if not an error
if(username.length > 0 && index == -1)
{
//do the jquery calls to hide/show links
}
}
And that get_user function looks like:
function get_user()
{
var result;
$.post("./session.php", {action : "get", key : "username", value : "val"}, function(data){
result = data;
});
return result;
}
The session.php is a simple app that takes in 3 post values and hopefully spits out the proper result, the problem I am running into is that the js result variable is often undefined, especially so when I debug via the IE dev toolbar. FF seems ok though. Am I using the callback in the correct way? I've tried putting alert() functions everywhere to figure out where the code is screwing up, but that doesn't help either as often the alert's say the result is undefined. Meanwhile, it seems like the get_user calls the post function but the stack immediately returns and never gets to the return statement until AFTER the get_user has returned a value of.. undefined. I believe I am misunderstanding the code flow here. I am used to C where logically one function follows another. In that vein I am interpreting the callback to essentially be like:
int i = callback_function(post("some data"));
So in my mind the post completes it's action and then calls another function or at least performs another action and then that completes and then the get_user can return it's value.
Or is the order of operation: post, get_user, callback?
...confused in Seattle
Internet Explorer does not natively support indexOf on arrays. Use jQuery's $.inArray() instead:
var index = $.inArray("error", username);
Keep in mind that AJAX stands for Asynchronous Javascript and XML. So the callback fires as soon as a response comes, but the rest of execution goes on. If you want to lock the execution until AJAX-request will be completed, use
$.ajaxSetup({async:false});
before AJAX call.

pass parameter from $.post() callback to outer variable

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

Categories