I have a problem with the following code.
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: 'sendMail.php',
type : "post",
data: sendJson,
success: function(data){
alert("Comanda dumneavoastra a fost trimisa");
}
});
Seems like data is not sent.... any idea why?
Ok... I know nothing is sent because I monitor requests with firebug.
I get no errors, nothing in console. Checked if it is activated, it is.
Here's what I meant with my comment:
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
Note that the ajax request has an error callback now. All requests should have an error callback so you can easily identify when errors are happening (as you've seen, firebug doesn't catch everything).
Another thing that I find helpful sometimes is StatusCodes:
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
statusCode: {
404: function() {
/*implementation for HTTP Status 404 (Not Found) goes here*/
},
401: function() {
/*implementation for HTTP Status 401 (Unauthorized) goes here*/
}
},
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
This will execute a function when a specific status code is returned by the server (404 and 401 in this snippet) and you can have a specific handler for the status codes you need.
You can find more about this here.
Related
I am trying to use the JIRA REST API to preform some requests. One of the first things that you must do, according the docs, is authenticate in some way.
Atlassian offers 2 methods; Basic Auth and Cookie Based Auth, the later of which uses cookies to establish a session.
The issue comes into play when I involve Jquery/JS.
Here is the request when preformed in ARC (Advanced Rest Client) for Chrome:
If I run that request, I will get a HTTP 200 response with the correct JSON, which is what I want.
However, when I attempt to do this with Jquery/JS, I recieve an error every time.
Here is that code:
function cookieLogin() {
//Grab username and password from the fields on the page
var user = $("#loginUsername").val();
var pass = $("#loginPassword").val();
$.ajax({
//URL
url: baseURL + path,
//Method
//type: 'POST', //analogous to 'method'
method: 'POST',
//Headers
accept: 'application/json',
dataType: 'application/json',
contentType: 'application/json',
//Payload to be sent
data:
{
"username": "admin",
"password": "admin"
},
//Responses to HTTP status codes
statusCode: {
200: function () {
alert("Success!");
},
401: function() {
alert("Invalid Credentials");
},
403: function () {
alert("Failed due to CAPTCHA requirement/throttling.")
}
},
success: function (data) {
var result = jQuery.parseJSON(data);
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error!!!");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
I have assured that the URL is correct. As you can see, I also hard-coded the credentials (this is merely a test page) just to test as well. I'm not sure why I am receiving errors in JS when I replicated the same thing that worked in ARC.
As per the documentation, I am seeing that "accept" should be "accepts" and "dataType" takes the string "json", not "application/json".
I have some ajax that's returning a 403 error message but when it does, the click() function that was associated with the ajax call no longer works. I don't append or add any HTML before or after the ajax call, and if the ajax doesn't receive a 403 error, there are no problems. It's just simply if I receive a 403 error from the ajax POST, then the click() breaks. How can I fix this?
Here is my code:
$( "#add_comment" ).on('click', null, function() {
var data = {token:"{{ Session::token() }}", comment:$('#game_comment_form form textarea').val() };
$.ajax({
type: "POST",
dataType: 'json',
url: '/game/comment/{{$game->id}}',
data: data,
success: function(data){
alert("Success");
},
statusCode: {
403: function() {
alert( "Forbidden" );
}
},
error: function(e){
alert("Error");
console.log(e);
}
});
return false;
});
Why dont you try $.post(); method ?
like this...
$.post('/game/comment/{{$game->id}}',data,function(data){
alert("Success");
}).done(function(data, textStatus, jqXHR) {
// called on success
}).fail(function(jqXHR, textStatus, errorThrown) {
// called on failure
}).always(function() {
// called in both cases
});
Turns out I was completely overlooking the fact that I manually disable the input button and just simply forgot to re-enable it after the 403. I was going to delete this but hopefully someone else possibly realizes their simple mistake as I have and this helps them out.
I am attempting to integrate the Instapaper Simple API into something but I am struggling to understand how to handle the response that the API sends back in Javascript. The article is adding to Instapaper just fine so I know that the submission is working just not my response handlers.
This is the code I have so far and I'm guessing that the success function is not the correct way of handling the response.
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function( data, status ) {
alert("yay");
},
error: function(status) {
alert("oh noes");
}
});
return false;
Instapaper returns a 201 when the article has been added. I can see that in the Google Chrome Network tool that the GET returned a 201 status. Just wondering how I handle that status within the code above.
Thanks.
Edit
When I click the link to activate the code below it pops up the alter under the error function right now even though it has worked.
jQuery.ajax() provides statusCode map for such purposes:
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
statusCode: {
200: function( data ) {
alert("yay");
},
201: function( data ) {
}
},
error: function(status) {
alert("oh noes");
}
});
http://api.jquery.com/jQuery.ajax/
$.ajax({
statusCode: {
201: function() {
alert("201!");
}
}
});
this should work with any http status code
When making a ajax call see example below success does gets a 201 status retuned. How do you handle these better i.e. 200, 201 within the success function?
$.ajax({
type: "POST",
dataType: "json",
url: "http://api.domain.com/sms",
data: {
// Send value in mobile input field.
mobile: $("#mobile").val(),
},
// On successful AJAX call do the following.
success: function(data) {
$('#messageText').text('SMS successfully sent');
},
error: function(jqXhr) {
data = JSON.parse(jqXhr.responseText);
}
});
Use the statusCode object:
var handle200 = function(data, textStatus, jqXHR) {
alert('200'); // success codes have the success signature
};
var handle201 = function(data, textStatus, jqXHR) {
alert('201'); // success codes have the success signature
// test it if you are in doubt:
console.log(data);
console.log(textStatus);
console.log(jqXHR);
};
var handle404 = function(jqXHR, textStatus, errorThrown) {
alert('404'); // failing codes have the error signature
});
var request = $.ajax({
type: 'POST',
url: '/myresource/posttarget',
data: { name: 'john' },
statusCode: {
200: handle200,
201: handle201,
404: handle404
}
});
This is an old question but I'd like to comment anyway.
I had the same problem and one thing that solved it for me was leaving the "dataType" unsetted. When you do this jQuery will try to guess the data type the server is returning and will not throw an error when your server returns a 201 with no content.
Hope it helps.
We had a similar problem; Looking at the jquery 1.9 source, a 201 status code expects content. If there is no content (or of the wrong content type) returned with the 201, then the fail callback is invoked.
Data inserted successful but jquery still returning error
The answer here appears to be a work around you can use for now. However, if you're using cross-domain, AJAX has some issues with that. Check out this SOF thread on it:
Problems Reading the HTTP Status/Error Code from jQuery AJAX
Instead of
ResponseEntity<?> responseEntity = new ResponseEntity<>(HttpStatus.CREATED);
I used
ResponseEntity<?> responseEntity = new ResponseEntity<>(detailVO, HttpStatus.CREATED);
Where detailVO is my object to rutrun in case of success. Then in browser I got response in success function.
I have got this function:
var current_url=window.location.href;
$.ajax({url: 'http://api.apps.com/html/'+appid,
data: {url:current_url},
dataType: 'jsonp',
timeout: 10000,
jsonp: "set_url_target",
success: function(data) { console.log(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
}).done(function() {
console.log("Message has been complete!!");
});
What I want is to trigger this function on http://api.apps.com/html/ (Note it is a different domain).
function set_url_target(url){
console.log("Url has been recieved: "+url);
}
So far the set_url_target isnt being triggered, and I get nothing being printed to the console, no error or nothing.. why?
if the external application isnt under your control I am afraid you cannot do much as you need to update the response that is sent by the server to the client side to use JSONP successfully..
thus you have two options:
a) make the call on server side in your application and return it to the client
b) alternatively to entirely make it client side you could use something like yahoo pipes or other services which transform the json response to valid jsonp response.
here is an example on how to do it using yahoo pipes: https://gist.github.com/316660
I am not sure about the license, do check upon them and if there are and associated API/Bandwidth costs. Let me know how it works out for you..
Try this, note the jsonp and jsonpCallback attributes
var current_url=window.location.href;
$.ajax({url: 'http://api.apps.com/html/'+appid,
data: {url:current_url},
dataType: 'jsonp',
timeout: 10000,
jsonp : false,
jsonpCallback: "set_url_target",
success: function(data) { console.log(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
}).done(function() {
console.log("Message has been complete!!");
});
For more info on this, AJAX