Javascript object declaration in IF statement - javascript

I'm sorry about the title I'm just not sure how to describe this one.
Basically I'm using JQUERY/ajax to invoke a php script to validate some input and get some data. The returned data is encoded JSON, so i set the datatype to JSON in JQUERY and it returns an object.
I have just discovered that under certain (it has to be said unusual) conditions where a network connection is not responding in an expected way, the ajax call invokes the error option in JQUERY.
In most cases I have an error message coming back from the server, but sometimes the error is reached and no JSON has been sent back from the server side script. I haven't tracked down exactly what can provoke that network situation yet, but in any case I thought I'd just deal with it back in Javascript whilst I don't yet know.
The idea was to check to see if the expected object had been created, and if not then create it with the two expected properties and run a dialogue. This way I'd avoid repeating writing the error messages. It's not a big saving, but I wanted to try the principle.
$.ajax({
url: 'getmetadata.php',
type: "POST",
data: entereddata,
dataType: "json",
timeout: (7000), //wait 7 seconds
error: function(data)
{
// handle errors
if(data)
{
// Do nothing error message will be issued from the data object
}else{
// no message was returned. Some other error occured.
function tempdata()
{
this.errortitle = "Error title";
this.errormessage = "Error text";
};
var data = new tempdata();
};
// issue error message
runDialogue(data.errortitle,data.errormessage);
}, //ERROR
success: function(data)
{
}; // SUCCESS
}); // AJAX
in the code above, the data object should either exist or not before the "if" statement. And when I get to the runDialogue(); the object data should always exist in order to pass the errortitle and errordescription properties.
When the "data" object exists, there is no problem. What isn't working is when the "data" object does not exist, ie if fails the "if" test. The else should create the object "data" but doesn't.
What have i done wrong?

You are redefining the variable data in your else block(more specific scope) and hence the global scope variable will still be undefined.
Change var data = new tempdata(); to
data = new tempdata(); //In the else block
So, now your ajax call should look like:
$.ajax({
url: 'getmetadata.php',
type: "POST",
data: entereddata,
dataType: "json",
timeout: (7000), //wait 7 seconds
error: function(data)
{
// handle errors
if(data)
{
// Do nothing error message will be issued from the data object
}else{
/******************NOTE THE CHANGE HERE********************/
data = {
errortitle:"Error title",
errormessage:"Error text"
};
};
// issue error message
runDialogue(data.errortitle,data.errormessage);
}, //ERROR
success: function(data)
{
}; // SUCCESS
}); // AJAX

Javascript throws an error on undefined references; you can't test existence just using the object. You can use the typeof operator to test whether the data exists, or instead whether it is of type "object".
For example:
if (typeof data === "undefined")
{
// You don't really need a closure for this...
errordata = {'errortitle' : 'Error Title',
'errormessage' : 'Error Message'};
runDialogue(data.errortitle, data.errormessage);
}

When $.ajax fails (because of a HTTP error), the .error method is called and passed the following params:
error(jqXHR, textStatus, errorThrown)
So the first parameter, which you have called "data", is not "what the webserver sent you" but a jquery wrapped xmlhttprequest object. Testing it via "if" [eg if (data)] will always return true.

Related

jQuery ajax errors out if file not exists, even though error handler is set

I have the following code in my javascript:
ajaxCall() {
return new Promise(function(resolve, reject) {
jQuery.ajax({
async: true
data: {
ajaxCallid: "e4f7b812-579b-a347-11f7-ce660ce79b72",
javascript: true
},
dataType: "jsonp",
timeout: 10000,
type: "GET",
url: "https://my.site.url.com/my.json"
xhrFields: {
withCredentials: true
}
}).done(function(data) {
// ...process the data...
resolve(data);
}).fail(function(jqXHR, textStatus) {
// ... process errors...
// test the nature of the error, and build an error = {} object
resolve(error);
});
};
}
What I am expecting, is that, if I call the following function, and the https://my.site.url.com/my.json file does not exist, the fail callback of the jquery ajax should be ran, and my Promise should resolve to an error object built by the fail callback.
Instead of this, the fail callback fires, the error object is built and returned, but I also get an error in my console, sent by jQuery, that looks something like this:
SyntaxError: expected expression, got '<'
jQuery 6
DOMEval
globalEval
text script
ajaxConvert
done
callback
It seems to me, that altough an error is fired, jQuery tries to parse the result sent by the server, as a JSON result (which it is not, in the case the file does not exist, apache is throwing a html error message in this case).
If I am correct regarding on the nature of this error, is there any way to tell jQuery, to not try to parse the result as a json, in case any kind of error is being raised, and the fail callback is being fired?
I am using jquery 3.4.1.

Sending a json object using ajax to a servlet and receiving a response json object

I'm trying to send a json object using ajax to a servlet. The object is to be changed and sent back to the client. This is the code I used to send the json object from client to server.
function sendJson(jsonObj)
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
},
error: function(data) {
alert('fail');
}
});
}
I only have a basic knowledge of javascript. As I understand this piece of code just sends a json object to a servlet. When receiving the response from the servlet, how do I get it? I searched for this and found functions similar to above function to receive response. I don't understand what this success: function(data) part does.
Can someone explain me the way to send a json object and receive the response to and from a servlet.
When I send a json object to the servlet, is there any way I can know whether it is received by the servlet, other than sending the object back as the response.
Ver simply, the answer is already in your code.
The ajax method of jquery has to callback methos for success and error.
Both are already impl. in your example but doing nothing!!
Here your code with comments pointing to the callback impl.
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
// PROCESS your RESPONSE here!!! It is in "data"!!!!
},
error: function(data) {
// This is called when the request failed, what happend is in the "data"!!!
alert('fail');
}
});
}
Impl. something in the success callback and debug it with your browser dev tools to see what's inside of "data".
As you changed your question more about how to handle the communication in general and how to know if your request was received. Here my normal approach.
First I define an envenlope for every request and response which is always the same. It can look like this:
{
status: OK | ERROR,
message: "possible error message etc."
data: JSON Object representing the payload.
}
After doing this I can impl. a generic logic to send and receive message between server and client and every side nows how to handle the envelope. To make sure a message is received, could be processed etc.
Then you have this:
Make an ajax call to your server.
2a. If there is topoligical problem your error callback on client side is called. Request failed, server not reachable!
2b. The message was received by the server. The server can now process the payload regarding the URL used to call the server. The server method succeed it will write an OK in the envelop and his possible result in "data" as payload. If the method fails, it sets "status" to "ERROR" and provides an proper message, data is empty.
The client receives data on the success callback and it can inteprete the "status" field if it's a usefull response or if it's an error.
Hope that helps
The success:function() part goes like this
A function to be called if the request succeeds. The function gets passed three arguments:
The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified
a string describing the status
the jqXHR (jQuery-XHR) object
What this means is - if your ajax request was successful, the server will return you some response, ie, the data. This "data" can be used in the function.
$.ajax({
...
success: function(data) {
// process the "data" variable
console.log("SERVER RESPONSE");
console.log(data);
}
});

Ajax fails 5% of time, response is "error"

I'm using jQuery to handle Ajax-calls.
I've noticed that, about 5% off the time, the ajax call fails. To make sure I get a good understanding of what's going wrong, I use this code:
$.ajax({
type:'POST',
url:'somepage.php',
data:{somedata:somedata},
success:function (data) {
var IS_JSON = true;
try
{
var newdata = jQuery.parseJSON(data);
}
catch(err)
{
IS_JSON = false;
}
if(IS_JSON)
{
//this is the part where a correct response is handled
}
else
{
//In case somepage.php gives a php-error, I put the exact error (=data) in the error-table at error.php.
window.location = "error.php?errorstring="+data;
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
//In case the ajax errors, I store the response (timeout, error, ...) in the database at error.php
window.location = "error.php?errorstring="+textStatus;
}
});
"Good" responses contain JSON, which I parse. If it's not JSON (for example just raw text from an php error) I don't try to parse it, but store the error in my database.
I would understand errors containing php errors that occured on somepage.php (since it's quiet a large page), but I'm supprised that the main errors I get, are errors of the ajax failing. The response data is just "error".
Anyone knows what the cause could be? What causes ajax-calls to fail? It's not a timeout, and it's also nothing like that somepage.php wasn't found or something. It's also not an error on somepage.php, since in that case, the Ajax-call would be successful, and the php-error would be logged in my database.
Edit: I used this obfuscator to make the script a little harder to read... Don't know if this could be causing the errors...
You should set dataType: 'json' in your ajax call. Coz if your not setting this up and your expecting a json result, the result will be treated as 'string' by default.

How do I read this weird server response and get the "success" key?

I am using this jQuery basic ajax reader:
$.ajax({
url: url,
dataType: 'jsonp',
success: function (data) {
console.log('data is', data);
}
});
The full server response I get is:
jQuery17107194540228229016_1350987657731({"action":"", "type":"", "callerId":""},
{"errorCode":0,"errorDescription":"OK","success":true,"payload":null});
However, when I try to output it with the console.log('data is,data); the output I get is:
data is Object {action: "", type: "", callerId: ""}
How do I receive the other part of the server response?
ie: The part that tells me success:true:
{"errorCode":0,"errorDescription":"OK","success":true,"payload":null}
Try this, I don't know if it will help:
success:function(data, second){
console.log('data is',data, 'second is ',second);
As several people has pointed out, the success function will only return if the request is a success. But if you have some special reason why you want to use those return values, you could add an extra parameter ( I think, still haven't tested it myself ).
success callback from jquery request will always be success even if the response is a 404. As long as the server was reachable, that is always a success. Only when server is not reachable or request got lost in the way the error callback is triggered. From that perspective, you'll always have to analyze the output to see if the result is the desired (that or check the status code of the response. If it's 40x, then it's probably an error from your perspective).

$.getJSON - ajax is sent but callback function is ignored - Internet Explorer

So here is my function
function ajax(addr,loading, loadTo, json){
addr = addr.replace(' ', '');
if (loading){
$("#"+loading).fadeIn();
}
if (json){
$.getJSON(addr, function(data){
alert('whoooo working'); // <--- it never goes here
if (loading){
$("#"+loading).fadeOut();
}
procJSON(data);
});
return true;
}
}
and I'm calling it with
var postid = $(this).attr('data-postid');
ajax(url+'tools/delete/'+postid, 'loading'+postid, false, true);
ajax is sent, image (loading image) is showed, but callback function is never called.
Isn't that just new reserved value from that IE's big list? Yes I know, IE is not a valid browser, but I can't blame my customers
As it fails in specific browsers, it's likely that it is a combination of unexpected headers in the response, and how the browser handles the data based on that.
If for example the response has the content type text/html instead of application/json, the browser might try to turn the response content into a HTML document (by adding pre tags around it), which would then cause the JSON parsing to fail.
If you use the $.ajax method, you can also catch any error message, which would give you a clue to what's going on:
$.ajax({
url: addr,
dataType: 'json',
success: function(data){
alert('whoooo working'); // <--- it never goes here
if (loading){
$("#"+loading).fadeOut();
}
procJSON(data);
},
error: function(o,c,m) { alert(m); }
});

Categories

Resources