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.
Related
Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating jQuery AJAX requests to a PHP function
I am trying to run a really simple formula,
Call a web page, and every few seconds or so Ajax calls a php function to echo "Hello World"
<?php
function test(){
echo "Hello World";
}
?>
<script type="text/javascript">
function testingTimer()
{
//CALL PHP FUNCTION CALLED TEST
}
setInterval('testingTimer()',5000);
</script>
All I need is the code that calls the already declared php function.
You cannot call that directly. Write code of AJAX and call URL like myfile.php?action=test and in file myfile.php write if action GET variable is equal to test then call that function and don't forget to exit code to prevent any other output.
Google on how to do ajax calls. It's basic knowledge explained in too many tutorials, and varies depending on if you are using a framework or not, and which.
You can post something for example :
function testingTimer()
{
$.post(URL,
{
foo : 'foo'
}
);
}
and in php check post:
if (isset($_POST['foo']))
test();
AJAX does not have the ability to call an arbitrary php function on its own. AJAX allows you to connect to a given page and request data. That being said, you can use AJAX to load a given page and all that page does is call your test function:
Based on your example code I assume you're trying to do this all within a single file. The issue you have is that PHP is run server side before/as the page loads. Once loaded it cannot be re-executed without a refresh.
You need to have your PHP in a separate file so that it can be called over HTTP by AJAX and return a response.
So something like this (if using jQuery):
$.ajax('helloworld.php', function(data){
alert(data);
}, 'html');
Should popup with hello world if implemented correctly.
You should use jQuery to use the ajax function.
You should not use a setInterval, but a setTimeout after the response of server because if the server take more than 5000 seconds to respond, then you'll have two requests at the same time.
If you want to put a timeout, you can always see the abort function on the jqXHR Object.
For example, you could do:
function refresh() {
$.ajax({
type: 'GET', // can be POST or GET
url: 'page.php' // php script to call
// when the server responds
}).done(function(response) {
console.log(response);
// call your function automatically
setTimeout(refresh, 5000);
});
}
display a javascript message before proceeding
Continuing from that thread, I would like to know if there is any way I can execute a php source code to display some related data from the database once the ajax get function gets the data of '1'
That is
$.get("display.php",function(data)
{
if(data!='1')
{
if(confirm("Display this item"))
{
// use this place to execute a php file. But how ?
}
}
}
);
You can't execute a PHP file in JavaScript. At that point you will need to use ajax to get whatever content the PHP script you which to execute produces and then use JavaScript to place it on the page (or do whatever else it says to do).
You can perform another ajax request (using $.get again, in your case)
if(confirm("Display this item")) {
$.get("file.php", function(data) {
// Handle data
});
}
call the ajax function again to get data from the php file.
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.
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);
}
});