I'm trying to catch a PHP variable in AJAX, but I'm not having much luck.
myCode.php
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
?>
In my HTML, I have the following:
<script>
function initiate_delete() {
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: {
type: 'test'
}
});
}
</script>
Is there any way to have AJAX wait for the PHP to execute and then get $status when I execute initiate_delete?
Thanks in advance.
Change code to
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo $status
or short it to
echo myFunction() ? "success" : "failure";
To wait for an answer - you can execute the request asynchronously, and get the result in the .done() callback
$.ajax({
url: $(this).attr('href'),
type: 'POST',
fail: function(){
//do something
},
done: function(m){
/// do something else
}
});
Your PHP needs to return the value. If you want to keep the dataType Json (suggested) you just need to json_encode your output.
So the PHP becomes:
<?php
$type=$_POST['type'];
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo json_encode('status'=>$status);
?>
Then you need to tell Ajax what to do with the answer received using .done()
So your Ajax will become:
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: { type: 'test'}
}).done(function(data){
console.log(data.status);
});
Now you can do what you want with status but only in the .done() function. The rest of your js will be executed without waiting for ajax to return a value since it is asyncronous. So add here all the logic like dom manipulation and so on depending on this response.
Obviously you can have more data returned by php in the json and acccess them by key as done for status.
Related
I am making an AJAX call but its not returning a value in the success handler. This is my AJAX call. I have checked that it's hitting the PHP file correctly
var msj;
$.ajax({
type: "POST",
url: "ajaxFile.php",
data: {
name: name,
status: status,
description: description,
action: 1
},
sucess: function(data){
msj = data;
alert(data);
}
});
alert(msj);
My PHP code is as follow:
if (isset($_POST['action']))
{
if ($_POST['action'] == 1)
{
$obj = new project($_POST['name'], $_POST['active'], $_POST['description']);
$obj = testInput($obj);
$check = validateName($obj->getName());
if ($check == 1)
{
echo $nameError;
}
else
{
print "asdasdasd";
}
}
}
Please help me tracking the mistake.
As far as I can see there's a syntax error in your code. There's sucess instead of success.
You are only providing a "success" callback function. You should also provide an "error" callback so you can debug and see what is wrong. You can also provide a "complete" callback that will be used in both alternatives.
var msj;
$.ajax({
type:"POST",
url:"ajaxFile.php",
data:{name:name,status:status,description:description,action:1},
complete:function(data){
msj=data;
alert(data);
}
});
alert(msj);
In your PHP, you could add
header('Content-Type: application/json');
to make sure JQuery identify well your web service.
This is updated based on an answer, but i still have a problem.
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
dataType:"JSON",
url: action,
data: dataString,
success: function(res){
if(res.status === 'error'){
console.log('Error!!!');
} else{
console.log('Success!!!');
}
}
});
Here is where i do the check, and also where i am confused. my else statement looks wrong.
$desired_email = strip_tags(#$_POST['email']);
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//performs insert query
} else {
header('Content-type: application/json');
$res['status'] = 'error';
echo json_encode($res);
}
Any help is greatly appreciated. I am new to jQuery and ajax and using json
Because you've returned a json array, even check email is invalid. You need to process the response data in success of ajax function. The error callback only works when server return status code on header (it isn't status in response data), i called it is Solution 1. In Solution 2, i solve it by return a header in PHP code.
Solution 1: Solve it on client (javascript)
//...
success: function(res){
// Use json parse method to parse the response data if it is string.
// If you have been to set dataType: 'json', it's ok. Can ignore this comment & code.
// res = JSON.parse(res);
status = res.status;
if(status == 'error'){
//Process the error in here
}
}
//...
Full ajax function example:
$.ajax({
url: 'index.php',
data: {email: 'vuong#gmail.com'},
method: 'POST',
dataType: 'json',
success: function(res){
if(res.status === 'error'){
console.log('Error!!!');
} else{
console.log('Success!!!');
}
}
});
It's work on my workplace!
Solution 2: Solve it on server (php)
// Add it to before `echo` line
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
You only need to choose once in both. Good luck!
Sorry all because my English is not good.
I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);
I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not
i have this :
echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';
<script type="text/javascript">
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
if(rmd==0)
alert("deleted");
else
alert("not empty");
window.location.reload(true);
}
});
}
</script>
and this
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
$rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>
my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?
thank you for your answers
PHP
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if (isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
?>
JS
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did}
}).done(function(rmd) {
if (rmd===0) {
alert("deleted");
}else{
alert("not empty");
window.location.reload(true);
}
});
}
i advice to use json or :
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
You need your php file to send something back, then you need the ajax call on the original page to behave based on the response.
php:
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo "{'rmd':$rmd}";
}
which will output one of two things: {"rmd": 0} or {"rmd": 1}
We can simulate this return on jsBin
Then use jquery to get the value and do something based on the response in our callback:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://jsbin.com/iwokag/3",
success: function(data){
alert('rmd = ' + data.rmd)
}
});
View the code, then watch it run.
Only I didn't send any data here, my example page always returns the same response.
Just try echoing $rmd in your ajax file, and then watching the console (try console.log(rmd) in your ajax response block)
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
console.log(rmd);
}
});
You can then act accordingly based on the response
Try echo the $rmd out in the php code, as an return to the ajax.
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
//if $rmd = 1 alert('directory not empty');
//if $rmd = 0 alert('directory deleted');
echo $rmd;
}
Your "rmd" in success: function(rmd) should receive the callabck.
I am trying to get the data return from a function called by a jquery ajax call. My function is located in a a php file and it looks liket his
valid_user() {
$id = $_POST('id');
if($id == 'hello'){
return true;
}
else{
return false;
}
}
and here is my ajax call
$.ajax({
type: "POST",
url: path + "valid_user",
sucess: function(msg) {
alert("Data returned: " + msg );
}
});
I have tested everthing and the function is wokring ( has been changed for this example) but I can not the return value of the function valid_id(). How do I get this? the variable msg keeps coming back empty. Thanks
From my understanding, there are several issues.
1) the method valid_user() is not been called.
2) The url doesn't look like it is correct either.
3) The "success" keyword is spelt "sucess".
4) You aren't passing any "data".
Here is an example ajax call tailored to what you may want.
$.ajax({
type: "POST",
url: "validateUser.php",
data: "id=49",
success: function(msg){
alert( "true or false: " + msg );
}
});
It looks like you misspelled sucess----but this may not be in your running code. You should check the second parameter of success:
success:function(data, textStatus)
You need to write PHP server-side code that calls the function and writes its return value to the output stream. For example:
<?php echo valid_user(); ?>
This should work - you might want to put better sanitizing on the POST value just in case.
In the PHP file:
$id = isset($_POST['id']) ? trim($_POST['id']) : '';
$return = 'false';
if($id!=''){
valid_user($id);
}
echo $return;
valid_user($id) {
if($id == 'hello'){
$return = 'true';
}
}
jQuery Call:
<script>
id = 'hello';
$.ajax({
type: "POST",
url: "validateUser.php?id="+id,
success: function(msg) {
alert("Data returned: " + msg );
}
});
</script>
Thank you for your help, I figured out the issue, the reason why it was not working was becuase my function valid_id() was returning true or false, and I needed to return echo "true"; and echo "false"; once I did this the msg variable contained the data true or false.