jQuery ajax jsonp calls error after success - json

I'm using jQuery 1.9.1 performing jsonp against the Etsy API. Below is a routine used to call into the API; it accepts a signed request (url), a jsonp callback name and an error handler.
call: function (signedOAuthRequest, callback, errorFn) {
$.ajax({
url: signedOAuthRequest,
type: "GET",
dataType: "jsonp",
jsonpCallback: callback,
jsonp: false,
crossDomain: true,
cache: true,
processData: false,
error: function (jqXHR, textStatus, errorThrown) {
if (errorFn != undefined) {
errorFn(jqXHR, textStatus, errorThrown);
}
}
});
Usage:
call("http://the.api/?signedrequest", "myCallback", myErrorHandler);
And it works. myCallback fires, the json object received looks good. Everything's fine.
Except...
Immediately after myCallback completes, the error handler runs. In the error handler, the status code is 200 and the error message is "parsererror". errorThrown.message is "myCallback was not called". Thing is, myCallback was definitely called and the json object passed to it was parsed just fine, so I don't get this at all.
Why is this error being thrown on an otherwise successful call?

Based on comments and what's in your question, this is how i would write that code:
function (signedOAuthRequest, callbackName, successFn, errorFn) {
$.ajax({
url: signedOAuthRequest,
type: "GET",
dataType: "jsonp",
jsonpCallback: callbackName,
jsonp: false,
cache: true,
success: successFn,
error: function (jqXHR, textStatus, errorThrown) {
if (typeof errorFn !== 'undefined') {
errorFn(jqXHR, textStatus, errorThrown);
}
}
});
}
I made the following changes:
Added an additional parameter to pass a success callback. This is required because jQuery will define the callback for you so that it can retrieve the successful response and parse it.
Removed crossdomain: true because it is redundant
Removed proccessData: false because it doesn't affect jsonp requests and you aren't passing any data
Added success: successFn so that jQuery will execute successFn on success with the parsed json data.
Renamed callback to callbackName so that it's more obvious about what it contains.
An alternate solution if you still insist on defining the callback yourself is to use the script dataType (taken from comments below)
$.ajax({
url: signedOAuthRequest,
dataType: "script",
cache: true
});

Related

Ajax Success Wont Trigger

On submitting a form I wanted to provide the user with feedback that the ajax was executed successfully. My ajax is as follows:
$(function() {
$('#submit').click(function (e) {
var url = "{{ url_for('handle_data') }}"; // send the form data here.
var form_data = new FormData($('#mainform')[0]);
$.ajax({
type: "POST",
url: url,
data: form_data, // serializes the form's elements.
success: function () {
alert('success!!');
}
});
e.preventDefault(); // block the traditional submission of the form.
});
// Inject our CSRF token into our AJAX request.
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", "{{ form.csrf_token._value() }}")
}
}
});
});
And on the backend my flask is:
#app.route('/handle_date', methods=['GET', 'POST'])
def handle_data():
"""
:return:
"""
print("hi there")
return ""
I can never get that success alert message to fire.
The server is not receiving JSON, it’s a FormData. And for jQuery to send a FormData, it needs
$.ajax({
type: "POST",
url: url,
data: formData,
// these three additional parameters
processData: false,
contentType: false,
dataType: "json"
})
The second edit i did was at the backend, when returning a response from flask I had to wrap it under jsonify for the ajax success to trigger

flask-cors is not parsing the data from ajax client

I am using flask for creating some endpoints for a blockchain project . I need to accept json data from ajax client . Since it is cros platform , i am using flask cors . But i cant seem to find a solution. It is not working
I have already tried doing
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origin = '*')
Basically my client code is as follows .
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: true
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
And at my server i have an endpoint of
#app.route('/ratings/new', methods = ['POST','OPTIONS'])
def rating():
values = request.get_json()
if values == None:
return "No data received", 400
#ratings = values['rating']
index = blockchain.new_ratings(values)
response = {
'Message': f'New transaction will be added to the block {index}',
}
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin','*')
return response, 201
At the server side i am not receiving the required data and at the client side i am getting the following error .
Access to XMLHttpRequest at 'http://localhost:8080/ratings/new' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Please help me solve this problem . Thanks in advance.
Silly mistake , make the withCredentials: false
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: false
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});

JSON API to HTML

I try using different instructions to use a JSON API from a Wordpress-System in a HTML-Teamplate. Unfortunately I do not succeed. Does anyone have any idea how I can read the section "Content" of http://www.earnyour21.de/api/get_page/?id=1588?
blog: function () {
$.ajax({
url: 'http://www.earnyour21.de/api/get_page/?id=1588',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
If the data structure of the JSON will always be the same, you can simply access the object directly using the objects name in JS.
blog: function(){
$.ajax({
url: 'http://www.earnyour21.de/api/get_page/?id=1588',
type: 'GET',
dataType: 'json',
success: function(data){
$('#content_test').append(data['page']['content']);
},
error: function(data){
$('#content_test').append(data['page']['content']);
}
});
}
Basically you need to use jquery to grab the div with an id of content_test and then append your data from the json. http://api.jquery.com/append/ and http://www.json.com/ for further reference.

Chrome extension transfer to manifest 2 - No ajax response

Hayush!
Been trying to transfer my Chrome extension to manifest 2. Everything is working except for one script which calls an ajax. I have a variable that contains a JSON content which needs to be transferred to the server.
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
For some reason the ajax part is not executed at all. No error message was triggered, nor in the server error log.
All of the inline scripts and scripts in general were included in the popup.js. So it's probably not the issue.
Any thoughts?
Thanks!
The following code works perfectly on previous manifest
function importbookmarks(){
$('#formadd').css('display','none');
$('#importing').css('display','block');
_gaq.push(['_trackEvent', 'chromextension','importbookmarks', username]);
chrome.bookmarks.getTree(function(bookmarks) {
sendlist(bookmarks);
});
}
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
// processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
}
});
}
The problem wasn't with the function. The button execution wasn't calling it correctly.
Here is the code I used to get the function to work in manifest 2
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("import-bookmarks").addEventListener("click", function () {
importbook();return;
});

Headers using ajax request

How to set headers using Ajax request? in below code
$.ajax({
type: type, //GET or POST or PUT or DELETE verb
url: requestURL, // Location of the service
// contentType: "application/x-www-form-urlencoded", // content type sent to server
dataType: "xml", //Expected data format from server
processData: false, //True or False
success: successCallback, //On Successfull service call
error: serviceFailed// When Service call fails
});
Request headers can be managed using beforeSend(jqXHR, settings) function and the setRequestHeader method, e.g.
$.ajax({
...
beforeSend : function(xhr) {
xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded');
}
});