Headers using ajax request - html

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');
}
});

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 does not write the returned object to the console

I have this piece of code that consumes a restful API using ajax. I am just trying to write on the console the returned data from the API, to my surprise it does not show any data, what's to be corrected?
$.ajax({
type: "get",
url: "http://localhost:8800/dialects",
crossDomain: true,
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
When I query the endpoint directly from the browser it returned the object's endpoint: http://localhost:8800/dialects. Sample of returned objects:
[{"glottocode":"zyud1238","names":"Zyuzdin","isocodes":"","macroarea":"Eurasia"},{"glottocode":"zwal1238","names":"Zwall","isocodes":"","macroarea":"Africa"},{"glottocode":"zuwa1238","names":"Zuwadza","isocodes":"","macroarea":"Papunesia"},{"glottocode":"zuti1239","names":"Zutiua","isocodes":"","macroarea":"South America"},]
Try using content-type attribute in ajax
$.ajax({
url: "http://localhost:8800/dialects",
type: "get",
crossDomain: true,
contentType: "application/jsonp; charset=utf-8",
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});

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;
});

Ajax Call using jsonp for calling rest webservice from other domain

How I use the jsonp when call to rest webservice from different domain.becouse my simple json does not working for rest webservice.how can i call rest webservice for ajax call.i use both jsonp and javascript for that.server responce i seen on only browser in firebug but how to show it on my application
my JS code.
function callService() {
$.ajax({
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
crossDomain: true,
cache: false,
async: false,
contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
alert("Server Responce Successfully!..");
},
error: function (msg) {
alert('error ' + msg.d);
}
});
}
function countryProvinceWCFJSONMulti() {
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = 'JSON';
script.src = "http://192.168.15.213/myservice/Service.svc/GetEvents";
script.type = "text/javascript";
head.appendChild(script);
varType = "GET";
varData = '{"username": "' + "Suhasusername" + '","password": "' + "suhaspassword" + '"}';
varContentType = "application/JSONP; charset=utf-8";
varDataType = "JSONP";
varProcessData = true;
callService();
}
If the same-origin policy isn't an issue, your code should look something like this:
$.ajax({ url: url,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
alert("Server Response Successful!..");
}
});
Here is a question that talks about circumventing the same-origin policy