I have the below Ajax function
ajax = function (params, action) {
$.ajax({
type: "POST",
url: "ajax.php",
data : params+"&action="+action,
dataType: "json",
success: function(response) {
switch(action)
{
case "save":
//some stuff
break;
case "del":
var seclastRow = $("."+table+" tr").length;
if(response.success == 1)
{
$("."+table+" tr[id='"+response.id+"']").effect("highlight",{color: '#f4667b'},500,function()
{
$("."+table+" tr[id='"+response.id+"']").remove();
});
}
break;
}
},
error: function() {
alert("Unexpected error, Please try again");
}
});
}
The following is the ajax.php that it calls. The file is a big if-else series, but I am pasting the wrong part only.
else if ($action == "del")
{
$id = $_POST['rid'];
$res = $obj->delete_record($id);
if ($res)
{
echo json_encode(array("success" => "1","id" => $id));
}
else
{
echo $obj->error("delete");
}
}
However, once the result is echoed back, the success function never enters in the Ajax part and I always get the Unexpected error alert.
Any ideas?
I as able to get the error using the callback error: function() and then displaying the response inside console.log. Check the image. response text
Related
When I run this script, instead of the error inserting HTML in the page, it returns an alert like the success function - but with the error message instead.
AJAX
$(function() {
$('form').submit(function() {
$page_title = $('input[name="page_title"]').val();
$.ajax({
method: 'GET',
url: 'test-script.php',
datatype: 'jsonp',
jsonp: 'jsonp_callback',
data: {
page_title: ($page_title),
},
success: function(result){
alert(result);
},
error: function(result) {
$('#error').html('result');
}
});
});
});
PHP
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
print $title;
} else {
$error = ('Name required');
print $error;
}
}
add a http_response_code(); to your php to tell js, that there was an error. Also you better should send back a json encoded error string, that can be understood by javascript.
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
echo $title;
} else {
http_response_code(400);
$error = ["message"=>"Name required"];
echo json_encode($error);
}
}
See the list of appropriate response codes
EDIT:
Response to your comment "the HTML is inserted... then disappears"_:
You need to prevent the form from beeing submitted. To do that add event.preventDefault() to your onSubmit handler:
$('form').submit(function( event ) {
event.preventDefault();
// rest of your code...
I would like to retry an ajax request when response data is an empty json object.
My ajax code is following.
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
$(this).ajax();//retry ajax request here, if data is empty
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
PHP
echo json_encode(array(
'type'=>$paymentType,
'btn'=>$this->PaymentBtn,
'usd' => round($this->finalUSDAmount,2),)
);
You can put your ajax request in a function and then call that function If the respons is empty.
Like this:
function yourCall(){
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
yourCall();
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
}
this setup will however keep trying the ajax call untill it gets a valid respons. This meaning that it will keep firing if the respons length == 0
Just Simply Do Following:
$.ajax({
url : 'index.php?r=funding/getPaymentButton',
type : 'POST',
data : {email:benfEmail,data:JSON.stringify(data),paymentType:method},
tryCount : 0,
retryLimit : 3,
success : function(json) {
//do something
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
//handle error
} else {
//handle error
}
}
});
I'm submitting a form via jQuery.ajax()
Now my PHP script is checking if a specific input field is empty, example:
$is_error = $user->is_error;
if($is_error !=0)
{
echo $is_error;
}
Back to my jQuery.ajax() , I'd like to check if the value of $error was true or not, within the sucess: part of the jQuery.ajax() call.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if there is an error message
// like:
// if(is_error) {show specific error message}
// else {show everything positive message}
}
});
Is it possible to check the PHP variable's value in there? Like if/else ?
Best regards!
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
This code will echo the value.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if $error == 0 or $error == 1.
if(data==1)
....
}
});
Then you check what is the returned value.
With your variable data, you can return values from PHP. And after in your scope success you can check.
You have to echo the error so that it can be returned as data.. The ajax only returns what has been created in html..
In instances like this I would use the following:
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(response)
{
if(response == 1){
alert('Error');
}else{
alert('No error');
}
}
});
i think you should try the following in php script
echo $error;
and then in jquery.ajax() do
success: function(data){
//data is $error
}
I'm trying to check if a website exists with an ajax call, but I'm not sure I am getting it right. On my page I grab a URL on click
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(){
$("#start").remove();
},
error: function(){
alert("Bad URL");
}
});
});
a=And then check on ajax.php
$url = $_POST['url'];
ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
return true;
} else {
return false;
}
It seems I am getting SUCCESS no matter what... What am I missing?
It seems I am getting SUCCESS no matter what... What am I missing?
This is extremely pretty straightforward.
Because of this reasons:
// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
$("#start").remove();
}
Which should be
success: function(respond){
//you don't have to return TRUE in your php
//you have to echo this one instead
if ( respond == '1'){
$("#start").remove();
} else {
//handle non-true if you need so
}
}
In php replace this:
if(strlen($r)>1) {
return true;
} else {
return false;
}
to
if(strlen($r)>1) {
print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}
Oh yeah, also don't forget to fix this as well:
data: "url="+url,
to data : {"url" : url}
As Nemoden said, you get a success message even if it returns false.
You need to check the data returned and then remove the element.
for example
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(response){
if (response == 'whatever you are returning') {
$("#start").remove();
}
},
error: function(){
alert("Bad URL");
}
});
});
Success callback is called whenever server-side script returned an answer (there were no connectivity errors or server-side errors). Is this answering your question?
See the difference:
$("#go").click(function() {
var url = $("#url").val(),
ajax_data = {url: url};
$.post({
"/ajax.php?cb=?",
ajax_data,
function(response){
if (response.status) {
// URL exists
}
else {
// URL not exists
}
$("#start").remove();
},
'json'
});
});
php back-end:
printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));
this works:
$.ajax({
type: 'POST',
url: 'register.php',
data: {captcha: captcha
},
success: function() {
$('#loading').hide();
$('#success').fadeIn();
}
error: function() {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
});
sends captcha response to PHP and if entered correctly, you can register. problem is, is that if you incorectly enter your captcha, the JQuery still runs the functions for a successful run although the PHP ran a "die" and did nothing.
In PHP, if the captcha is entered incorrectly is does this
if (!$resp->is_valid) {
die ("false");
}
else
{
register
}
How do I request the error that PHP spits out so I can do something like?
success: function(find error) {
if(error == "false")
{
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else
{
$('#loading').hide();
$('#success').fadeIn();
}
}
EDIT!:
With your help heres what it looks like now and it works fantastic!!
$.ajax({
type: 'POST',
url: 'register.php',
dataType: "json",
data: {
challenge: challenge,
response: response,
zip: zip
},
success: function(result) {
if (!result.success) {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else {
$('#loading').hide();
$('#success').fadeIn();
}
}
});
and the PHP
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else
{
$response = array(success => true);
echo json_encode($response);
Ya'll are the coolest. My first JQuery I've ever done, It's came out so awesome. This site rules!
I wouldn't use success/failure. Even if the script dies it is still going to return a 200 SUCCESS to your ajax call.
Use JSON to return responses depending on whether or not it is a success and parse and proceed with correct logic
<?php
if ( $resp->is_valid ) {
echo json_encode( array( 'status' => 'true' ) );
} else {
echo json_encode( array( 'status' => 'false' ) );
}
?>
Then you can parse the response in your AJAX call. Remember, if you call die('false'); that is still going to return a success message to your ajax function.
PHP:
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else {
$response = array(success => true);
echo json_encode($response);
}
jQuery:
success: function(result) {
if (!result.success) {
// Wrong input submitted ..
}
else {
// Correct input submitted ..
}
}