Send error messages from php to ajax - javascript

I am trying to send a "notification" or error messages from php to ajax. I'm trying to achieve something like this:
php:
if (myString == '') {
// Send "stringIsEmpty" error to ajax
} else if (myString == 'foo') {
// Send "stringEqualsFoo" error to ajax
}
ajax
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(){
alert("It works");
},
error: function() {
if(stringIsEmpty) {
alert("String is empty");
} else if(stringEqualsFoo) {
alert("String equals Foo");
}
}
});
How can I send error messages to ajax?
Update
Here's the php file I have. I tried using the echo solution answers said, but when I output what the data is (in ajax), I get undefined:
<?php
$img=$_FILES['img'];
if($img['name']==''){
echo('noImage');
}else{
$filename = $img['tmp_name'];
$client_id="myId";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$pvars = array('image' => base64_encode($data));
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$out = curl_exec($curl);
curl_close ($curl);
$pms = json_decode($out,true);
$url=$pms['data']['link'];
if($url!=""){
echo "<h2>Uploaded Without Any Problem</h2>";
echo "<img src='$url'/>";
}else{
echo "<h2>There's a Problem</h2>";
echo $pms['data']['error'];
header("HTTP/1.1 404 Not Found");
}
}
?>
I added echo("noImage") in if($img['name']==''){

The error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/
So if you return a response from your PHP server, the error function won't be triggered. However, you can define a function to handle the error based on the response you send from PHP:
success: function(data){
if (data === "stringIsEmpty") {
triggerError("stringIsEmpty");
} else if (data === "stringEqualsFoo") {
triggerError("stringEqualsFoo");
}
},
And then you can have the error function like this:
function triggerError(error) {
if (error === "stringIsEmpty") {
alert("Your string is empty!");
} else if (error === "stringEqualsFoo") {
alert("Your string is equal to Foo!");
}
}
If you make a request to let's say post.php, you can just return a string:
// Create a function to see if the string is empty
$funcOutput = isStringEmpty();
echo $funcOutput;
Or specifically for the example:
echo "stringIsEmpty";
For more information see: How to return data from PHP to a jQuery ajax call

You can trigger the jQuery error-handler by changing the http response code in php. Any 4xx or 5xx error should work, but best stay in rfc.
PHP:
// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";
jQuery:
[...]
error: function(jqxhr) {
alert(jqxhr.responseText)
}
[...]

The thing is, if your php responds, then it's technically not a error, and must be handled in the success callback.
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(data){
alert('The response is: '+data);
if(data=="empty sting"){
alert("The string is empty");
} else if (data == 'foo') {
alert("The string equals 'foo'");
} else {
alert("It works");
}
},
});
And in your PHP:
if (myString == '') {
echo('empty string');
} else if (myString == 'foo') {
echo('foo');
}

The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...
If you want to control some response of the server you can write this code in the "success" setting.
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response){
if (response == '') {
// Send "stringIsEmpty" error to ajax
} else if (response== 'foo') {
// Send "stringEqualsFoo" error to ajax
}
}
}
});
The PHP could be something like this
if (myString == '') {
echo '';
} else if (myString == 'foo') {
echo 'foo';
}

I've tried the bootstrap Model using jQuery AJAX And PHP with error handling
Javascript File:
// add receipt data
$('#insert_form').on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "includes/user-insert.inc.php",
method: "POST",
data: $('#insert_form').serialize(),
async: true,
beforeSend: function() {
$('#insert').val("Inserting");
},
success: function(data) {
$('#insert_form')[0].reset();
$('#add_reciept').modal('hide');
dataTable.ajax.reload(null, false);
if (data == "No") {
$('#alert-danger').addClass('alert alert-danger');
$('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
$('#alert-danger').fadeIn().show();
setTimeout(function() {
$('#alert-danger').fadeOut("slow");
}, 8000);
} else if (data == "Yes") {
$('#alert-success').html('<strong>Well done!</strong> A Record has been Added.');
$('#alert-success').addClass('alert alert-info');
$('#alert-success').fadeIn().show();
setTimeout(function() {
$('#alert-success').fadeOut("slow");
}, 8000);
}
},
error: function(err) {
$('#alert-danger').addClass('alert alert-danger');
$('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
$('#alert-danger').fadeIn().show();
setTimeout(function() {
$('#alert-danger').fadeOut("slow");
}, 8000);
},
complete: function(data) {
$('#insert').val("Insert");
}
});
});
process.inc.php file:
// check users again or not
$sql = "SELECT * FROM users_acc WHERE U_Email='$U_Email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo 'No';
} else {
$query = "
INSERT INTO users_acc(Firstname, Lastname, U_Email, U_Password, Gender, user_role_id)
VALUES('$Firstname', '$Lastname', '$U_Email', '$U_Password', '$Gender' , '$user_role_id')
";
echo 'Yes';
}

So if your returned string is empty, or it equals "foo", you may think that is an error, but HTTP thinks it is a success, and you need to look for these strings in the "success" function.

Related

cancel ajax success function from inside ajaxSuccess event

I have a global ajaxSuccess event and a local success function attached to an ajax request.
I want to cancel the success function if the global find status = false in the response.
like this
$(document).ajaxSuccess(function (event, xhr) {
let result = xhr.responseJSON;
if (result.status === false) {
//here the ajax should be stopped, I don't want to call the local functio
}
}
$.ajax(url, {
'method': method,
'success': function () {
//success function to call if the global ajaxSuccess is ok
}
})
can this be achieved ?
This will give you an insight into what you may be looking for. You will need to return the backend data in json.
why don't you set status to certain values
Eg. false= 0 and true = 1. You can then print success or failure based on values returned from the backend in this sample from PHP backend.
Here am sending a post variable with value of test_ok. If the value is test_ok then alert success else alert fail and
stop further action
<script>
$(document).ready(function(){
var test ='test_ok';
var datasend = "test="+ test;
$.ajax({
type:'POST',
url:'test.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(result){
$('#result').fadeIn('slow').prepend(msg);
if (result.status ==0) {
alert('failed');
return false;
}
if (result.status == 1) {
alert('success');
}
}
});
});
</script>
test.php
<?php
$test = $_POST['test'];
$output = array();
if($test == "test_ok"){
$output[] = array(
"status" => '1'
);
}
if($test != "test_ok"){
$output[] = array(
"status" => '0'
);
}
echo json_encode($output);

How to stop a ajax request properly

I'm trying to stop an Ajax request when a user click a button. But even if I made use the .abort(); the ajax keep requesting each 2 seconds. Basically, a user wait for an input from the server. If the response is 2, then after 2 second an ajax request need to be call. If the response is 3, then is it good. the function is not called anymore.
I tried different solutions, .arbord(); changed the ajax completely...etc None of the solution worked out. I guess I'm missing some concept here.
////////////////////// index.php
.
<button id="cancel" onclick="CancelRequest()">Cancel</button>
.
<script>
function CheckStatus(){
var jqXHR = $.ajax({
url: "status.php",
async: true,
cache: false,
type: "POST",
data: {data: id},
success: function(response){
var response;
if (response == 2) {
alert(response);
setTimeout(CheckStatus, 2000); /// NEED TO SEND THE REQUEST AJAX REQUEST AGAIN, the response needs to be 3
} else if (response == 3) {
alert("good");
} else {
alert("error");
}
}
});
}
CheckStatus(); // start ajax automatically
}
//cancel request if the user press a button
function CancelRequest() {
jqXHR.abort();
}
</script>
///////////////////////////////////// status.php
$number = $_POST['id'];
.
.
.
.
$number = 2;
if ($number['status'] === 3) {
echo "good";
} elseif ($result['status'] == 2) {
echo "repeat again";
} else {
echo "error";
}
I expect that when I call jqXHR.abort(); the ajax should stop. However it keep going forever.
Declare the variable jqXHR outside of the CheckStatus() function
<script>
var jqXHR;
function CheckStatus(){
jqXHR = $.ajax({
url: "status.php",
async: true,
cache: false,
type: "POST",
data: {data: id},
success: function(response){
var response;
if (response == 2) {
alert(response);
setTimeout(CheckStatus, 2000); /// NEED TO SEND THE REQUEST AJAX REQUEST AGAIN, the response needs to be 3
} else if (response == 3) {
alert("good");
} else {
alert("error");
}
}
});
}
CheckStatus(); // start ajax automatically
}
//cancel request if the user press a button
function CancelRequest() {
jqXHR.abort();
}

how to check that ajax returns true or false value using jquery

i'm building a signup form for my website i validate my signup page with jquery i want to do that when all the fields are filled with valid way then the signup page redirect or load and store the data in database...
1. first jquery code checks input fields
2. then in the jquery code there is a ajax call which check if the email already exist or not if the ajax call return true then data will be inserted in database if it return false the the page will not load and display the message that email is already exist
the problem in my code is that when the ajax call is true or false my page keep loading and insert the data in database but i want that if value is false page will not load.
here is my code
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
if (result.status===false) {
$('#error').html("Email alreaday exist");
return false;
} if(result.status===true) {
return true;
}
}
});
and here is my email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
}
echo json_encode($result);
exit(0);
}
Try this:
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
if (response.status === true) {
return true;
} else {
$('#error').html("Email alreaday exist");
return false;
}
}
});
In my opinion you should invoke the PHP API method to insert the new email directly inside the success function callback:
$.ajax({
type: 'POST',
url: 'email_validator.php',
data: {email: mail},
success: function (response) {
var result = $.parseJSON(response);
if (result.status === false) {
$('#error').html("Email already exists");
}
else (result.status === true) {
// -> Call here the PHP api method to insert the new email in the database
}
}
});
You can add async option to false and return outside the ajax call:
function testAjax() {
var resultStatus = "";
$.ajax({
type:'POST',
url:'email_validator.php',
async: false,
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
resultStatus = result.status;
if (result.status===false) {
$('#error').html("Email alreaday exist");
}
}
});
return resultStatus;
}
[UPDATE]
But you do not need to check this on client side. Yo can check if email exists in your email_validator.php and immediately write it to the database if it does not exist:
email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
// --> INSERT the new email into the database
}
echo json_encode($result);
exit(0);
}

Proper way to handle Ajax response in PHP

I'm using Ajax to logout from page.
index.php
Logout
custom.js
$(document).ready(function () {
$('.logout-button').click(function () {
dataUrl = "mode=logout";
$.ajax({
url: "ajax.php",
type: "POST",
data: dataUrl,
success: function (data) {
if (data == "OK") {
location.href = 'login.php';
}
}
});
});
});
ajax.php
session_start();
$mode = $_POST['mode'];
if ($mode == 'logout'){
session_unset();
session_destroy();
$_SESSION = array();
echo "OK";
}
Sometimes it works as it should. But sometimes it just reload to same page, even if session is already deleted.
What am I doing wrong?

php can not get the data send by ajax

this is the js code, ajax has two arguments, the first is url, 2nd is a object which contains type data and onsuccess. (I didn't use jQuery but the function I define myself, the code is at the end of the question)
I just want to send the 'text' string to php, so is there any problem to do like this? I also have tried change the data to data: {searchinput:"text"}, but still don't work.
ajax(
'http://localhost/test.php',
{
type: 'POST',
data: "searchinput=text",
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
this is the php code, sorry for changing the code wrong while pasting it on.
$searchinput = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
then the error is
Undefined index: searchinput
I have search some method like change onsuccess function to setTimeout, and do ajax again, but it doesn't work, just send the data again but the php still can't get the data
this is the ajax function
function ajax(url, options) {
if (!options.type) {
options.type = "post"
};
var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true);
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
options.onsuccess(xhr.responseText, xhr)
} else {
options.onfail(xhr.responseText, xhr);
}
};
}
}
Well, since you used the ajax wrong, I'm not surprised. There should be a error in the console.
jQuery AJAX is used like this:
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
url is a part of the object the ajax expects, so it needs to be inside and not outside of it. Also, data is expecting another object, you gave it a plain string.
Also, as #Muhammad Ahmed stated in his answer, you are using a wrong variable in your php code.
Edit: AJAX in JavaScript without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/test.php', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// worked
var data = JSON.parse(this.responseText);
} else {
// failed
}
}
};
request.send();
request = null;
$searchcon = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
In This code there is a mistake on ist line you are using variable $searchcon
and on query you are using $searchinput change ist varaible name to $searchinput instead of $searchcon. and also change your ajax code.
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseTxt, xhr) {
console.log(responseTxt);
}
}
);
send data value like below and use print_r($_POST) on php page to see values are coming or not
$.ajax(
{ url: 'test.php',
type: 'POST',
data:{
searchinput:text
},
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
Try with this code you were using ajax in wrong manner. You can learn more about how ajax works and how to code for ajax over http://api.jquery.com/jquery.ajax/
$.ajax(
{
type: 'POST',
url : 'http://localhost/test.php',
data: {searchinput:text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
and within your PHP file you need to update your typo i.e. you were getting value of your POST in $searchcon variable
$searchcon = $_POST["searchinput"];
^^^^^^^^^^
and within your query you were using
$query = "select * from text where data like'".$searchinput."%' ";
^^^^^^^^^^^^^^
it should be like
$query = "select * from text where data like'".$searchcon."%' ";
^^^^^^^^^^
Try this code :
var other_data = $('form').serializeArray();
$.ajax({
url: 'work.php',
data: other_data,
type: 'POST',
success: function(data){
console.log(data);
}
});
or
you can also pass the data in url also.
Try the code which suits your requirement.
$.ajax({
url: 'work.php?index=checkbox&action=empty',
type: 'POST',
success: function(data){
console.log(data);
}
});

Categories