I have send query ajax request to server. The server response in two variable that is errmsg or successmsg . so how can i understand response is whether errmsg or successmsg. More code explain below
script.js
$.ajax({
url:"abc.php",
method:"POST",
data:$('#form').serialize(),
success:function(data){
?????????
}
error:function(data){
.......
}
});
abc.php
<?php
if (condition) {
$successmsg = hello;
echo "$successmsg";
}
elseif (condition) {
$errmsg = Error Occured;
echo "$errmsg";
}
elseif (condition) {
$successmsg = welcome;
echo "$successmsg";
}
else {
$errmsg = Bye;
echo "$errmsg";
}
?>
return error or success depending on what you are doing with your code in php for example
return iferror ? ['errmsg' = 'Error'] : ['successmsg'=>'success'];
then get your response in ajax like
$.ajax({
url : 'your-url,
data : {your - data},
success: function(response){
if(response.successmsg){
console.log(response.successmsg);
}
else{
console.log(response.errmsg);
},
error: function(response){
console.log(response);
}
});
You can return the server's response using this code:
<?php
if ($textvar > 500){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
?>
Then the Ajax code can be:
$.ajax({
cache: false,
url: '/js/checkmsgs.php',
success: function(res){ // This will be applied if the php code is completlly done without any programming mistakes.
if (res == 'SUCCESS'){
alert('Success');
}else{
alert('Error !');
}
},
error: function(){ // this one will be applied if the php code have a mistake !
alert('eeeeeerrror');
}
});
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 have try ajax success and error. but its not working on my login form. but its work on my insert, update or delete php.
here my ajax code :
$('#login').submit(function() {
$.ajax({
type: 'POST',
url: 'resto_proses_login.php',
data: $(this).serialize(),
dataType: 'json',
success: function(status) {
alert("success");
},
error: function(){
alert("error");
}
})
return false;
});
and this is my resto_proses_login.php
<?php
session_start();
include 'connect.php';
$query = mysql_query("SELECT * FROM tb WHERE user='$_POST[user]' AND pass='$_POST[pass]'");
if(mysql_num_rows($query) == 1)
{
$return_arr=array();
$row_array['status']='sukses';
array_push($return_arr,$row_array);
echo json_encode($return_arr);
$data = mysql_fetch_array($query);
$_SESSION['access']=$data['access'];
$_SESSION['nama']=$data['nama'];
} if($_SESSION['access']== "ADMIN" ) { header('location: admin/');
} elseif ($_SESSION['access']== "KASIR") { header('location: kasir/');
} elseif ($_SESSION['access']== "DAPUR") { header('location: dapur/');
} elseif ($_SESSION['access']== "PELAYAN") { header('location: pelayan/');
} else { echo "failed"; }
?>
if im not use ajax, this process have error with code. that error will show number line : undefined index: access. if it success. no error showing.
my question is if use ajax. it just show alert("error"); although I input the correct data
I want to show a ajax error after submitting a form. It ends now with 'die'
but what is the best way to handle this? Just write something in this php file in 'script' tags?
if($_POST['postForm'] == 'newsletter'){
$newsletterSubscriber = new NewsletterSubscriber();
$newsletterSubscriber->set('CMS_newsletters_id', 2);
$newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
$newsletterSubscriber->set('firstName', $_POST['voornaam']);
$newsletterSubscriber->set('lastName', $_POST['achternaam']);
$newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
$newsletterSubscriber->set('emailAddress', $_POST['email']);
$newsletterSubscriber->set('subscribed', 1);
$saved = $newsletterSubscriber->save();
die('subscriber added');
}
I tried several solutions I found but I can't get it to work.
Thanks!
All you need to do is create a array and place any parameters you want to pass back into that array, then use json_encode() to turn it into a json string that can be easily processed by javascript
if($_POST['postForm'] == 'newsletter'){
$newsletterSubscriber = new NewsletterSubscriber();
$newsletterSubscriber->set('CMS_newsletters_id', 2);
$newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
$newsletterSubscriber->set('firstName', $_POST['voornaam']);
$newsletterSubscriber->set('lastName', $_POST['achternaam']);
$newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
$newsletterSubscriber->set('emailAddress', $_POST['email']);
$newsletterSubscriber->set('subscribed', 1);
$saved = $newsletterSubscriber->save();
$response = array('error_code'=>0,
'message'=>'subscriber added'
);
echo json_encode($response);
exit;
}
The javascript woudl be something like
$.ajax({
type: "POST",
url: "connection.php",
data: {param1: 'aaa'},
dataType: JSON
})
.done( function(data){
if(data.error_code == 0) {
alert(data.message);
}
});
Note when you use dataType:JSON the browser automatically converts the json string returned to a javascript object so you can address data.error_code and data.message in simple javascript object notation
You can do like:
if($saved) {
die('subscriber added');
} else {
echo "error";
}
and In ajax you can check:
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
success: function(data){
if(data == "error") {
alert("Data has not been saved successfully. Please try again.");
window.location.reload(true);
}
}
});
Did you check jQuery Ajax API? this comes directly from their example.
It says that you can use the .done() .fail and .always() functions
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
the best solution is to make you custom json and send it to ajax:
instead of die try:
$message = array('error'=>'subscriber added');
echo json_encode($message);
and in you ajax callback do:
function(success) {
if(success.error) {
//do stuff
}
//do stff
}
Use a json message followed by a error number:
if($saved) {
echo json_encode(array('message'=>'Successfully saved','erno'=>0));
} else {
echo json_encode(array('message'=>'Error on save','erno'=>1));
}
js:
success:function(data) {
if(data.erno == 1) {
alert(data.message)
//do other stuf here
} else {
alert(data.message)//if save was successful
}
}
I want to create jquery ajax success function based resp from logout.php. If users not sign in,It redirect bring them to login page.,but it's not working as I'm expected,no event occur when user is logged or not.So, what is wrong with my ajax function?
logout.php
<?php
if( !$user->is_logged ) {
echo 'true';
}else{
echo 'false';
}
?>
jquery function in index.html
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
if(resp =='true'){
document.location = '../login_test.html';
}
if(resp=='false'){
alert('U are logged');
}
}
});
});
Change some errors and made it to better view:
PHP:
<?php
header('Content-Type: application/json');
if( !$user->is_logged ) {
echo json_encode(array('status' => 'ok'));
}else{
echo json_encode(array('status' => 'bad'));
}
?>
Javascript:
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
var state = JSON.parse(resp).status
if(state == 'ok'){
document.location.href = '/login_test.html';
}
else{
alert('U are logged');
}
}
});
});
If you have no alert, and have no redirect - you have not .success callback, and problem one level above your condition. In that case show us your errors from js-dev-console from browser.
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
}