Error and Success Handling in JQuery Ajax PHP - javascript

how can i handle error and success messages in Ajax? I have an ajax call where my datas are saved into a db. My php script first checked if a user have x amount. if he has less then x then he should fire a alert (amount < x) Else insert into db.
my php file:
...
.....
if ($wallet_amount < "100") {
$wa1 = 0;
echo $wa1;
} else {
$inito = $connection->prepare("INSERT INTO bs (title, start, end, userid, typ, code) VALUES (:title, :start, :end, :pid, :col, :code)");
$inito->bindValue(':pid', $pid, PDO::PARAM_INT);
$inito->bindValue(':title', $title, PDO::PARAM_STR);
$inito->bindValue(':start', $start, PDO::PARAM_STR);
$inito->bindValue(':end', $end, PDO::PARAM_STR);
$inito->bindValue(':col', $col, PDO::PARAM_STR);
$inito->bindValue(':code', $code, PDO::PARAM_INT);
$inito->execute();
exit();
}
My js file:
$.ajax({
url: 'add.php',
data: {
'title': $('#Name').val(),
'start': start,
'end': $('#End').val(),
'code': $('input[name="code"]:checked').val()
},
type: "POST",
error: function () {
alert('There was an error while adding events.');
}
});
My first try goes wrong. I write something like that:
success: function (response) {
if (response === 0) {
alert("Amount < X!");
} else if (response === 1) {
alert("Amount > X);
}
},
error: function () {
alert('There was an error while adding events.');
}

I guess in success block you have used a strict check ===, this checks the type and value both:
success: function (response) {
if (response === '0') { // update this
alert("Amount < X!");
} else if (response === '1') {
alert("Amount > X"); //<---quote is missing i guess it's just a typo.
}
},
error: function () {
alert('There was an error while adding events.');
}
Also i am not sure if this check } else if (response === '1') { would ever happen because i don't see if you get '1' in the response.

To make the code a little more cleaner, I would suggest you start by returning the values with json (even if it is only one variable)
So the PHP look like
php
/* ... */
echo json_encode(array('wal' => $wal));
/* ... */
Next, in your ajax code, you need to read it correctly. E.g.
ajax
success: function(response) {
var wal = response.wal
if (wal == 0) {
alert("Amount < X!");
} else if (wal == 1) {
alert("Amount > X);
} else {
// ...
}
}
Try that, and as Jai said, only check for the value, and not for the type (x == 0 instead of x === 0)

I would not use the content of your respone to switch your error and success cases. Think about different status codes like status code 200 or 204 on success and status code 400 on error for example. Than, you can also code a more type-safe application with explicit return values:
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});

Related

Error part in jQuery is missing

I build following JavaScript part and everything works fine. But I'm not sure if the code is completely right. Because in my script I only use success: function() but I don't use error. Is it a MUST to have error in a jQuery AJAX call?
Currently I'm catching the errors in my php controller function and echo them in the success part.
$(document)
.ready(function() {
var groupName = '';
var groupid = '';
$(".grp")
.click(function() {
$('.text-danger')
.html('');
groupName = $(this)
.data('groupname');
groupid = $(this)
.attr('id');
$('.text')
.html(groupName);
$('#dataModal')
.modal({
show: true
});
});
jQuery(".grpval")
.click(function(e) {
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
, });
jQuery.ajax({
url: "{{ route('request_group') }}"
, method: 'post'
, data: {
'Gruppe': groupid
}
, success: function(data) {
if (typeof data.successsuccess != 'undefined') {
jQuery('.alert-success')
.show();
jQuery('.alert-success')
.html('<p>' + data.successsuccess + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else if (typeof data.successdberror != 'undefined') {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + data.successdberror + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else {
jQuery.each(data.errors, function(key, value) {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + value + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
});
}
}
});
});
});
EDIT: Here is the function from my Controller:
public function setGroupRequest(Request $request){
$validator = \Validator::make($request->all(), [
'Gruppe' => [new ValidRequest]
]);
$groupid = $request->input('Gruppe');
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
try{
$groups_request = new GroupRequest();
$groups_request->idgroups = $groupid;
$groups_request->iduser = Auth::id();
$groups_request->request_active = 1;
$groups_request->save();
$db_status = 'success';
}catch(\Exception $e){
$db_status = 'error';
}
if($db_status == 'success'){
return response()->json(['successsuccess'=>'Record is successfully added']);
}else{
return response()->json(['successdberror'=>'DB Error! Values could not be saved.']);
}
}
Error handling is required as you never know different things on the internet might result in failure of request for example,
Network failure.
Lost database connection
Unauthorised access/access denied
Any variable being not defined
There is nothing wrong in your way of writing PHP error in success, but writing it in $ajax error callback function is preferred as it helps in separating error & success logic.
In fact you can add a jquery error callback function as well to your $ajax which will handle all the errors originating from above mentioned internet failures.
You can add error function, which will receive any type of error coming from backend.
jQuery.ajax({
url: "{{ route('request_group') }}",
method: 'data: {
'Gruppe': groupid
},
success: function(data) {
//code here
},
error: function (jqXHR, exception) {
//error handling
}
})
In your PHP file,
if ($query) {
echo "success"; //whatever you want to show on success.
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
This way you can catch PHP error as well as any internet Network errors in your jquery ajax.

Response values overlapping in ajax

I am making an application where I need to have multiple Ajax requests. But the problem is that I am getting same response values for both Ajax requests.
In each request there needs to be a data named activityCode but doing that I keep getting the value of ScoreBoardResponse even in the heartbeat function too. If I rename anyone of the activityCode to any other name the problem gets sorted. But why does this happen?
Here is the following code:
JS
var allJoined = false;
var roomName = $('#room').val();
var playerNameSet = function () {
if(!allJoined) {
$.ajax({
type: "POST",
url: "gameEngine/app.php",
data: {
activityCode: 1,
room: roomName
},
success: function (ScoreBoardResponse) {
var obj = JSON.parse(ScoreBoardResponse);
var count = Object.keys(obj).length;
if (count == 1) {
playerOne_name.html(obj.p1_name);
setTimeout(playerNameSet, 3000);
}
else if (count == 2) {
playerOne_name.html(obj.p1_name);
playerTwo_name.html(obj.p2_name);
allJoined = true;
//Start the heartbeat to check if the other player is alive
setTimeout(startHeartbeat, 15000);
clearTimeout(playerNameSet);
}
},
error: function (error) {
console.log(error);
}
});
}
};
setTimeout(playerNameSet, 3000);
function startHeartbeat() {
$.ajax({
type: "POST",
url: "gameEngine/app.php",
data: {
activityCode: 2,
room: roomName
},
success: function(beat) {
console.log(beat);
},
error: function(error) {
console.log(error);
}
});
setTimeout(startHeartbeat, 15000);
}
PHP
.
.
.
elseif (isset($_POST['activityCode']) == 1 && isset($_POST['room'])) {
$response = $gameHandler->getPlayerOrder($_POST['room']);
echo $response;
}
elseif (isset($_POST['activityCode']) == 2 && isset($_POST['room'])) {
echo "request reached here";
}
isset() returns either true or false if the POST variable exists or not. It does not return the variable value, the you need to add another check in your condition :
elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 1 && isset($_POST['room'])) {
$response = $gameHandler->getPlayerOrder($_POST['room']);
echo $response;
}
elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 2 && isset($_POST['room'])) {
echo "request reached here";
}

how to solve this in java script and ajax one Alert show in ajax if value are right

I know this is silly Question but i have occurred this error again and again
My Question is
php script are send me the right data but when i set the if condition in
success:function(data)
data then show me the one alert if i put the right value and wrong value
This is Js Code
function SetTheAmount_man()
{ //Get
var member_id = $('#mem_un_id').val();
// alert(member_id);
$.ajax({
url:"<?php echo
base_url();?>demo_insert.php",
data: {member_id:member_id},
type: "POST",
success:function(data){
//alert(data);
// alert(member_id);
if (data == 'success')
{
alert("123");
}
else
{
alert("456");
}
//window.open('http://www.google.com');
//alert(data);
// $("#secheme_interest_value").html(data);
}
});
}
This is PHP Code demo_insert
if(isset($_POST['member_id']))
{
$mem_un_id=$_POST['member_id'];
$sql_in= mysql_query("select mem_un_id,deleted from phppos_customers where mem_un_id='".$_POST['member_id']."' and deleted='0'");
//$row = mysql_affected_rows($sql_in);
$row=mysql_fetch_array($sql_in);
if($row['mem_un_id']!=''){
echo "success";
}else{
echo "error";
}
//echo $row['mem_un_id'];
}
#Deepak Acharya: Use the datatype in you ajax hit and then check if it helps, try all the datatypes available most likely to use
text
html
json
What is the result of alerting the incoming response?Uncomment this:
//alert(data);
Try to change this:
if(data == 'success')
{
alert("123");
}
else
{
alert("456");
}
to this:
if( data == "success" ) {
alert("123");
}
if( data == "error" ) {
alert("456");
}

Ajax validator function doesn't work

I have to validate my form which does a scheduling. I used ajax and php to do a query and search that time - that was choosen in a select - in the database. If there's one row saved, it returns 1 (or false), if doesn't, returns 0 (or true). Anyway, in the function callback, even it's true, the validate error appears, as if it had a real error. Printing the value, we see the value, but i dont know why it shows the error. I've tried everything, and nowhere i found the answer for this.
The js file: alteraDiv.js
jQuery.validator.addMethod('confereDia', function(value){
alert("entrou no método");
if (conf(value) == '0'){
alert("entrou no if");
return true;
}else{
alert("entrou no else");
return false;
}
});
var verifica;
function setVerifica(x){
verifica = x;
}
function conf(value){
$.ajax({
async: false,
url: 'confereDia.php?horarioInicial='+value,
dataType: 'text',
success: function(data) {
alert("entrou no success");
setVerifica(data);
alert("value:"+value);
return verifica;
},
error: function(data){
alert("ERROR. Dados: " + data);
}
});
}
The php file: confereDia.php
$horarioInicial = $_GET["horarioInicial"];
$query = "SELECT idAgendamento FROM agendamento WHERE horarioInicial = '$horarioInicial'";
$results = mysql_query($query);
if (mysql_num_rows($results) == 0) {
echo '0'; //good to register
} else {
echo '1'; //already registered
}
There are more codes in the files, but i think these are necessary for you understand and help me.. THANK YOU!!!

AJAX cannot read echo data from PHP?

I've been testing my register, and to an extent the code works. But it seems to not be able to compare the text from the PHP script.
I tried using existing email AND username, existing email, existing username and two non-existing username and email. But all give me the echoed data + Fail (which is the end conditional statement in JQuery).
JQuery:
$( function ajaxRegCheck() {
$('#reg_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'save_register.php',
data: $(this).serialize(),
success: function(data)
{
if(data == "un_em_exists"){
alert(data+" Username and Email exists.");
} else if(data == "un_exists") {
alert(data+" Username exists.");
} else if(data == "em_exists") {
alert(data+" Email exists.");
} else if(data == "success"){
alert(data+" Created account.");
} else {
alert(data+ " Fail.");
}
}
});
});
});
PHP Register:
if(($exist_check_user->rowCount() > 0) AND ($exist_check_em->rowCount() > 0)){
echo "un_em_exists";
} else if($exist_check_user->rowCount() > 0) {
echo "un_exists";
} else if($exist_check_em->rowCount() > 0) {
echo "em_exists";
} else {
$sql = "INSERT INTO Users (username, email, password) VALUES (:r_un, :r_em, :r_pw)";
$q = $cdb->prepare($sql);
$q->execute(array(':r_un'=>$reg_username,':r_em'=>$reg_email,':r_pw'=>$reg_pw));
echo "success";
}
I do not why it skips the if statements in the JQuery and go straight to the last else condition. It clearly outputs the string from the PHP side correctly, but it doesn't seem to be able to compare the string?
For example, if I register with existing username and email, it'll echo 'un_em_exists' response. On the JQuery the alert matches this as it says, "un_em_exists Fail.", which is the last statement.
UPDATE:
Found the problem, but not too sure how to fix. I tested the string length, and in return I get string length 16 (testing from the JQuery side), and on PHP I get 12 - which is the correct amount for "un_em_exists".
I do not know what the extra 4 amounts come from though.
After success trim your data by using data.trim(), might be there is whitespace
Make sure the returned value is text like so:
$( function ajaxRegCheck() {
$('#reg_form').submit(function(e) {
e.preventDefault();
$.ajax({
dataType: 'text',
type: "POST",
url: 'save_register.php',
data: $(this).serialize(),
success: function(data)
{
if(data == "un_em_exists"){
alert(data+" Username and Email exists.");
} else if(data == "un_exists") {
alert(data+" Username exists.");
} else if(data == "em_exists") {
alert(data+" Email exists.");
} else if(data == "success"){
alert(data+" Created account.");
} else {
alert(data+ " Fail.");
}
}
});
});
});

Categories

Resources