Sneak out JSON data from failed JSONP AJAX call - ajax

When I make this AJAX call
var inputText = $('#job-search-field').val(); //for example "CSS"
$.ajax({
url: 'http://api.arbetsformedlingen.se/platsannons/matchning',
type: 'GET',
dataType: 'json',
crossDomain: true,
data: {nyckelord: inputText}, //searches arbetsformedlingen.se for jobs containing the keyword "CSS".
success: getAPIResponse,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
I get this error in the console
"XMLHttpRequest cannot load http://api.arbetsformedlingen.se/platsannons/matchning?nyckelord=CSS. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost is therefore not allowed access."
When I make this AJAX call (http://jsfiddle.net/MSCbP/)
var inputText = $('#job-search-field').val();
$.ajax({
url: 'http://api.arbetsformedlingen.se/platsannons/matchning',
type: 'GET',
dataType: 'jsonp', //jsonp, not json
crossDomain: true,
data: {nyckelord: inputText},
success: getAPIResponse,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
I get this error in the console
"Uncaught SyntaxError: Unexpected token : "
The first error tells me I don't have permission to retrieve the data, right? Since I find no information on how to gain access to the API I'm very interested in getting the response from the second call, which seems to work. Although I get the console error, I see the json data I want in the Network>Response tab in Chrome's dev-tool.
I can't seem to get the JSON data from "success: function()", is there any other way to get it?
Thanks!

Related

React AJAX post request does not go to success/error method

I have a React Component which calls an AJAX POST request.
The POST request creates an entry in the database as expected. (status 201 returned) However the success/error methods of the same are not called.
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend: function(xhr) {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success: function(data) {
console.log('success');
this.loadData();
},
error: function(xhr, status, err) {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});
The request is called through a button click. Also the browser hangs once the request is made, and the solution is to open a new tab.
Also i do not see the POST request on the Network tab of Chrome, but see it on the backend.
Any hints?
Try using ES6 arrow functions or bind your functions with this
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend:(xhr) => {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success:(data) => {
console.log('success');
this.loadData();
},
error:(xhr, status, err) => {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});

Unable to bind data in ajax through webapi

I am getting data by verifying through "jsonp" but it is going to error.
$.ajax({
type: 'GET',
url: _BaseUrl,
contentType: 'application/json;charset=utf-8',
processData: false,
crossDomain: true,
dataType: 'json',
success: function (data) {
sourceGrid = data;
return true;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.error);
return false;
}
});
Error is:
XMLHttpRequest cannot load url. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin url is therefore not allowed access.
Please mention URL you are using for AJAX.. One reason could be you are using full url with http.. Try relative URL.
I have got the answer.Need to call a class which contains in detail to allow access.

Ajax Call with PUT method

i am trying to make ajax call with PUT method. Below is the code, but i am getting with the error XML Parsing Error: no element found Location: moz-nullprincipal:{c847a4af-f009-4907-a103-50874fcbbe35} Line Number 1, Column 1:
$.ajax({
type: "PUT",
async: true,
url: "http://localhost:8080/karthick/update",
data: JSON.stringify(params),
contentType: "application/json",
dataType: "JSON",
processdata: true,
success: function (json) { //On Successfull service call
},
error: function (xhr) {
alert(xhr.responseText);
}
});
return false;
};
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
But this service is working Good with Rest-client jar. Also my POST method works fine in my browser. Please help me in this.
Regards
Karthick
Usually, this error comes, when making a cross browser request. Try data: JSONP and see if it helps.

How to use an ajax call's response to manipulate a dynamic page?

I am trying to submit a form with the user's inserted data and get the html back from the page called (update.asp).
How do I get the html response and how do I write it to a div on the page? The response would be "success".
If my page throws a 500 or other type of error, how can I handle that?
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
// how do i catch the response? is this the right place?
},
error: function(data) {
// how do I catch the error code here?
}
});
The response from the server in both cases would be passed to the callback as the data variable in your example. Try using console.log(data) inside of your callbacks to see the result in your developer console.
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('#myForm').serialize(),
success: function(response) {
$("#yourDIV").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //output, 500
}
});
});
More on this: ajax()

How do I know if a JSON string has loaded?

Forgive me, I am a complete JSON newbie here. I'm trying to load a file of json information from an external file, and I'm not sure how I can tell if the information has loaded or not. Here's what I have so far:
$(document).ready(function(){
$.ajax({
dataType: 'json',
success: function(string) {
data = $.parseJSON(string);
console.log(data);
alert(data);
document.write(data);
},
url: 'http://www.site.com/mystuff.php'
});
});
I've tried putting all kinds of stuff to see if the info has loaded, as you can see, and nothing has. How do I know if I've even gotten anything? I would really appreciate any help!
As already pointed out, two things:
You don't need to parse the string when setting the datatype as JSON
Check if the request returned successfully at all
Which could look like this:
$(document).ready(function(){
$.ajax({
dataType: 'json',
success: function(json) {
console.log(data);
},
error : function(xhr, text) {
console.log('An error occurred', xhr, text);
},
url: 'http://www.site.com/mystuff.php'
});
});
When setting the datatype to JSON you also have to make sure that mystuff.php sets the Content-Type header to application/json:
<?php
header('Content-Type: application/json');
?>
No need to parse to json again.. you can directly use the object
Also add the error Function to keep a check if you are getting any error..
$(document).ready(function(){
$.ajax({
dataType: 'json',
beforeSend : function() {
console.log('Before Ajax Request Starts !!');
},
success: function(data) {
console.log(data);
alert(data);
document.write(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Error occurred: " + errorThrown);
},
beforeSend : function() {
console.log('Ajax Request Complete !!');
},
url: 'http://www.site.com/mystuff.php'
});
});
This makes sure you have feedback at every step..

Resources