How to show error message if no data is found? - javascript

Can you help me with this code?
function blub() {
$.ajax({
type: 'GET',
url: 'blups1.php?rid=10',
async: true,
cache: false,
dataType: 'json',
success: function(data){
var name = data[0].name;
alert('ok = '+name);
},
error: alert('nix gefunden')
});
}
In case of success it shows me what I want, but the alert from error always pop up at first. Where do I have to place that error alert so that it will only appear if there is no database?

I'm really not sure why one would just place the alert statement singularly as the callback. Put the alert in a function:
error: function(xhr, status, error) {
alert('nix gefunden');
}

Related

how to detect a server error into a jquery ajax call?

I use Jquery to parse an json from url: the code is like this:
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
});
}
everything works fine, but if the server is not reachable I'm not able to detect it: I tried to do something in error: function, but seems that the code in error is fired only if the json has an error
have you got some ideas?
thank you!
You need to test the statusText from the jQuery textStatus response object. You can take advantage of your browser's developer console to inspect this object. You can expand the properties and methods for your perusal, however you wanna use it. Just click on the returned message of the console.log() to see these properties and methods that you wan't to use for error detection.
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(textStatus) {
console.log(textStatus);
console.log(textStatus.statusText, textStatus.status);
}
});
}
fetchdata();

I don't know why but my ajax POST method is not returning any response

This is my code , When I click on submit , somehow the data is inserting but that echo data in back php form is not showing in this front ajax js code , please tell me if anything is wrong in my data
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
ok this is my full js code
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
error: (err)=>{console.warn(err)}
// location.href='gst_chargeoff.php';
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
The ajax call is working fine. It is also getting response from the url. If there would be any server side error , It can be detected in the error: of the ajax parameter.
In your code it was written incorrectly, the same i have corrected in the below code, you will get the error in console if there will be any server side error. else the response will be returned properly.
Check the below code.
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
// location.href='gst_chargeoff.php';
alert(data);
},
error: function(err){
console.log(err);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
You forgot to add the error attribute to your AJAX request. It's most likely throwing an error.
error: (err) => {
console.warn(err)
}
Wrap the entire $.ajax block inside a console.log($.ajax({...}));.
Then look into the console for the response codes for more info
Also you can use this to find more about the case:
error: function(err){
console.log(err);
}

ajax not called..even alerts are not working

i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});

jQuery: Calling a function from AJAX request

I'm trying to call a function when I get success from my ajax call, but it's not working. This is what I've tryed so far.
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d) {
console.log(dt);
console.log(msg.d);
buildTableBody(dt, msg.d);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
function buildTableBody(dt, obj) {
dt.fnClearTable();
data = [];
$(obj).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
}
Thanks in advance!
Edit #1
I used console.log in order to show you what I got from dt and msg.d (Image)
Edit #2
If I paste the commands from buildTableBody function in the success: handler instead of calling buildTableBody function in the success: handler it actually works:
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
dt.fnClearTable();
data = [];
$(msg.d).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
But it makes no sense to me, since this actually should work in both ways.
Pretty sure you have a typo on your function call
buildTableBody(td, msg.d);
should be
buildTableBody(dt, msg.d);
Also what is the return type from Index.aspx/getMRPReasonCodeReport? If it is string, you've got to unescape the string before you can treat it as JSON.
Try removing contentType : "application/json utf-8" from your AJAX call. That is the type of the data sent to the server. It is likely that you want the default content type.
Unless your server-side resource was configured to accept json it likely accepts application/x-www-form-urlencoded
http://api.jquery.com/jQuery.ajax/

Jquery Display Message then Ajax then hide message

il give an example
document.ready(function() {
$("#Show").bind("click", function()
{
var F = Function2();
if (F)
{
// Do Other Stuff.
}
}
});
function Function2()
{
$("#Message").Show();
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").Hide();
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
}
</script>
<div id="Message" style="display:none;">
<!-- Loading Image In here -->
</div>
<a href="#" id="Show" onclick="return:false;">Show then Hide</false>
</code>
Now what I want to happen is for this messagebox to show however the AJAX for some reason wont show it until the AJAX Request is finished by which point it is too late. I have set async to false which hasent helped either.
I think the root of this issue is a syntax error. JavaScript is case sensitive, so the correct syntax would be lowercase show() and hide()
If you're still having an issue after fixing the syntax errors, try using the ajaxStart event to show the message and hide it on success.
//use the ajaxstart event to display the message
$('#message').ajaxStart(function() {
$(this).show("slow");
});
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").hide("slow"); //hide message on success
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
Delaying the show or hide
$("#message").delay(3000).hide("slow");
Here's a jsFiddle: http://jsfiddle.net/rs83R/
Try hiding the Message div in the click event after getting true or false.
Remove the async:false, I do not think that is anyway relevant to fixing this problem. The purpose of AJAX call is to make an asynchronous call.
Also, there is an error its not $("#Message").Show() its $("#Message").show() with all lowercase, same goes for hide().
Try changing these, I hope it should work.

Categories

Resources