How to get error response in Ajax? - javascript

I am trying to add data to a cart(using) Ajax jQuery, now I have added a primary key constraint and I want when the constraint is violated in get the error message in jQuery:
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function()
{
alert("Item has been added to cart");
},
error:
function()
{
alert("Item already present in the cart");
}
});
return false;
});
});
}
The error function never runs, the functionality in the DB is running fine but I don't see the error message in Ajax.
Here is Java code:
public int addintocart(String user,int pid)
{
try
{
conn = obj.connect();
String sql="insert into cart(userid,product_id,quantity) values(?,?,?)";
ps1 = conn.prepareStatement(sql);
ps1.setString(1,user);
ps1.setInt(2,pid);
ps1.setInt(3,1);
ps1.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception k)
{
k.printStackTrace();
}
return x;
}
What is going wrong?

You have to send the error back as a servlet response from Java. Here is an example: How to return Java Exception info to jQuery.ajax REST call?
Also, you are missing some parameters in the ajax error function. It might be another problem. Check out http://api.jquery.com/jquery.ajax/ You should evaluate the error and present the appropriate message.

That error code wwill never work. the onerror event of AJAX only runs when connection cannot be established or URL does not exist. You have to return something from your the server indicating success or faliure.
I would do it this way.
PHP(convert this code to JAVA):
if(success){
die(1);
} else {
if(notyetincart){
die(0);
} else {
die(2);
}
}
Then Jquery coded:
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function(response)
{
if(reponse==="1")
alert("Item has been added to cart");
else if(reponse==="0")
alert("Item could not be added to cart");
else alert("Item already present in the cart");
},
error:
function()
{
alert("Item could not be added to cart due to poor network connection");
}
});
return false;
});
});
}
Hope this helps

Related

ASP.NET MVC 500 (Internal Server Error) with ajax post method

I'm newbie in asp.net mvc, I try to create a post data using ajax, when in the development is run well, but when I try to publish web in server I get the error when post data, the error like this POST https://example.com/login-testing 500 (Internal Server Error). I try to look for many examples but fail all.
this is my code, may be you can find any problem in my code:
JS script in index.cshtml
function login() {
var email = $('#input-email').val();
var password = $('#input-password').val();
if (email && password) {
$.ajax({
url: '#Url.Action("LoginTesting", "Auth")',
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
dataType: 'json',
contentType: 'application/json',
success: function (data){
console.log(data);
if (data == 1) {
window.location.href = '#Url.Action("Index", "Home")';
} else {
$('#login-warning').show();
}
},
error: function (data) {
$('#login-warning').show();
}
});
} else if (!email) {
$('#text-danger-email').show();
} else if (!password) {
$('#text-danger-password').show();
}
}
controller
[Route("login-testing")]
public JsonResult LoginTesting(LoginViewModel smodel)
{
var email = smodel.email;
var password = smodel.password;
DBHandle sdb = new DBHandle();
var account = sdb.GetLoginVerify(email);
if (account.password != null)
{
if (BCrypt.Net.BCrypt.Verify(password, account.password ))
{
var detail = sdb.GetUserDetail(account.id);
if (detail != null)
{
Session["is_login"] = true;
Session["id"] = detail.id;
Session["fullname"] = detail.fullname;
Session["id_levels"] = detail.id_levels;
Session["levels"] = detail.levels;
return Json(1);
}
else
{
return Json(2);
}
}
else
{
return Json(3);
}
}
else
{
return Json(4);
}
}
Please anyone help me to solve this problem.
Thanks.
Internal Server Error probably means something is wrong with your program.cs file .The order in which they are placed is important,improper placements could actually give rise to these errors.
500 internal server also means , there is something wrong with your Code,
according to me Go to Chrome Dev Tool and Click on Network Tab, in that Click on XHR tab
there your API call must located with red Highlighted text (Since its 500 internal server error ), Click on it, right side window will be appear then
click on Preview Tab , you might see which line of Code causing the issue
You can also Debug the Code , and step over code line by line, and check what is wrong.

how to alert whatever response you want base on the ajax response

I was working on making a facial recognition system. I used the API called Kairos.The response I got back is the data of the feature of a face or an error message from a nonface image. How can I change the response and display them on the screen, such as "success! It's a face" or "There's no face". I tried to if/else statement, but it seems that there's no response from it. How should I do it?
<script>
$("#testDetect").click(function () {
var file = $('#imageFile')[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
var imageData = parseImageData(reader.result);
var data = {};
data.image = imageData;
$.ajax({
url : "http://localhost/Karios/simple-detect/form-post.php",
type : "POST",
data : data,
dataType : 'text'
}).done(function(response) {
console.log(response);
if (!response) { // Something unexpected happened. The message body is empty.
alert('Hmm, unexpected response from Kairos');
} else if (response['Errors'] && response['Errors'].size() > 0) { // If Errors is defined in the response, something went wrong.
if (response['Errors'][0]['ErrCode'] == 5002) { // This appears to be the error when no faces are found.
alert(response['Errors'][0]['Message']);
} else {
alert('Some other error occurred:\n' + response['Errors']['ErrorCode'] + ': ' + response['Errors']['Message']);
}
} else { // If there are no errors in the response, can we assume it detected a face? I guess so.
alert('Face(s) detected');
// The response has a ton of information about what it saw, including gender, age, ethnicity
// and more.
}
})
}
});
Based on the response that you receive, you can write what you want to be displayed:
if(response === true){
alert('success!');
}
else{
alert('fail!');
}
EDIT
To redirect to another page, use: window.location = http://mywebsite.com;
To make a button unclickable, you will need to set the disabled attribute: document.querySelector('button').setAttribute('disabled',true);
EDIT
If this is your response: {"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]} then you will have to parse it first because it will most likely be a string. Then in your conditional statement, check to see if it exists.
var obj = '{"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]}';
obj = JSON.parse(obj);
if(obj.Errors){
console.log("errors exist");
}
In addition to .done(), you can call .fail() which will run when the ajax was unsuccessful.
$("#testDetect").click(function() {
var data = {}
$.ajax({
url: "http://localhost/Karios/simple-detect/form-post.php",
type: "POST",
data: data,
dataType: 'text'
}).done(function(response) {
alert(response)
}).fail(function(error) {
alert("Not a face")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testDetect">Test</button>

alert() box is coming up multiple times in jquery

i am clicking on a simple add to cart button to add an item to a cart , if the item is already present it gives an error item already . all goes well , but when i click the button second time , i have to close the alert box twice , 3rd time i click , i have to close the alert box thrice and so on ... this goes on until i refresh the page , and same thing starts from scratch
jquery code :
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function()
{
alert("Item has been added to cart");
},
error:
function(xhr)
{
if (xhr.responseText=="already present")
alert("item is already present in cart");
else if(xhr.responseText=="error")
alert("item cannot be added , server error");
}
});
return false;
//e.preventDefault();
});
});
}
servlet code :
if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==2)
{
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
pw.write("already present");
}
else if(k==0)
{
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
pw.write("error");
}
}
error or success the behavior is same for both
You only need this
$(document).ready(function() {
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {
pid: pid,
user: user
},
success: function() {
alert("Item has been added to cart");
},
error: function(xhr) {
if (xhr.responseText == "already present")
alert("item is already present in cart");
else if (xhr.responseText == "error")
alert("item cannot be added , server error");
}
});
return false;
//e.preventDefault();
});});
No other event handlers required.
Simply use it after completing submit.It will off the click event.
$("#addtocart").off('click');

Jquery ajax() not working as expected

I have a function getActivityHP() which I am calling as soon as my page loads. This function makes an ajax calls to another test3.php page with certain data which will contain default values initially. However as soon as I add my ajax code the function stops working as if there is an error. Simple alert also doesn't work!
<script>
$(document).ready( function(){
alert("Welcome");// not working
getActivityHP();
}
function getActivityHP() {
$("#loading").show();
alert("Hello"); // not working
var search = $("#search").val();
var deployedon = $("#deployedon").val();
var platform = $("#platform").val();
var country = $("#country").val();
var carrier = $("#carrier").val();
$.ajax({
type: "POST",
url: "test3.php",
data: {
"action" : "activity",
"deployedon" : deployedon,
"platform" : platform,
"country" : country,
"carrier" : carrier
},
success: function(msg) {
$("#loading").hide();
$("#activity").html(msg);
}
error: function() {
alert("An error occurred while processing file.");
}
});
}
</script>
In my test3.php I am doing:-
$action=$_POST['action'];
$deployedon=$_POST['deployedon'];
$platform=$_POST['platform'];
$carrier=$_POST['carrier'];
$country=$_POST['country'];
and then I am using echo to print these in my html!
There is syntax error. You are missing ) at the end of -
$(document).ready( function(){
alert("Welcome");
getActivityHP();
});
And missing , at the end of success -
success: function(msg) {
$("#loading").hide();
$("#activity").html(msg);
},
Update your code and try to run.
You missed a comma right here:
success: function(msg) {
$("#loading").hide();
$("#activity").html(msg);
}, // <--- This comma
error: function() {
alert("An error occurred while processing file.");

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}

Categories