I have an piece of code here, it's just an ajax options which I use to pass to my $(form).ajaxSubmit(submit_ajax_options)
var submit_ajax_options = {
url: init_param.server_url,
type: 'POST',
data: { agents_data : agents },
dataType: 'json',
timeout: 30000,
beforeSubmit: function( formData, jqForm, options ){
console.log('before submit');
form_loader.fadeIn();
},
success: function( response, status, xhr, $form ){
console.log('success callback');
form_loader.fadeOut();
if(response.status == 'ok'){
create_box('success', response.msg);
setTimeout(function(){
window.location.href = response.redirect;
}, 2000);
}
else{
create_box('danger', response.msg);
}
},
}
And this is my process code on my server (PHP):
<some processing code here>
$response['redirect'] = $redirect_url;
$response['status'] = 'ok';
$response['msg'] = "successfully";
//output data jsone
echo json_encode($response);
when I run as debug on my server, code ran ok without any mistake, but in my js code at client, I don't receive anything callback in my success block of submit_ajax_options (I don't see the logging string in my browser console, although the logging string in beforeSubmit block was printed)
I really have no any idea for this issue. Anybody can help me about my situation. really thank you a lots
You can try this if it helps you
$response['redirect'] = $redirect_url;
$response['status'] = 'ok';
$response['msg'] = "successfully";
//output data jsone
echo json_encode($response);
exit; // add exit so it stops execution and you can see the data in response
decode your JSON response
var data = JSON.parse(response);
console.log(data.status)
Related
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.
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 am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.
Here is my AJAX call, where #class is a select box with values.
$("#class").change( function () {
if($('#class').val().length > 0){
$.ajax({
type: "GET",
url: "http://192.168.0.9/ajax",
data: 'class_id=' + $("#class").val(),
datatype: 'json',
async: 'true',
beforeSend: function() {
alert("Before send!");
},
success: function(result){
if (result.status){
$('#result').html(result);
} else {
alert('request unsuccessful!');
}
},
complete: function() {
alert("Complete!");
},
error: function (request,error) {
alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);
$("#result").html(request.responseText);
}
});
} else {
alert('Please make a selection');
}
return false;
});
This is my PHP function that returns the result
$result = array();
$result['status'] = "success";
$result['message'] = "Types";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
Finally, this is the response I am getting in my error alert:
A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent
I am hoping this is a simple error and someone can tell me what I am doing wrong?
Perhaps your parameter should be pass in JSON format:
data: "{'class_id':'" + $("#class").val() + "'}",
Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself
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);