I am trying to attach data to my requestbody while sendign using jQuery ajax.
If I tried to do it using the extension RESTCLient is either firefox or chrome it works fine, which means that my method on the serverside is working fine.
That is why I am pretty sure that it the ajax call I am making
$.ajax({
url: 'lingosnacks/delete/'+ id,
type: 'POST',
data: $('#email').val() + $('#password').val()
dataType: "json",
success: function(data) {
console.log("FILL| Sucess| ");
console.log("FILL| Sucess| Data| " + data);
fill(data);
}
});
The data line is wrong, it should be very similar to a JSON string, like this:
data: {email: $('#email').val(), password: $('#password').val()},
You need to have the data you are sending in this format:
email=blah%40blah.com&password=pass123
You can do that with jQuery using $('form').serialize()
Also, you are missing a , after your data string in the Ajax call.
Actually data param in jQuery Ajax method is for sending url params.
You can send the same by appending then into the url but to make the code more readable e and organized i would prefer to use data variable.
So your data content should look like :
data : "email="+$('#email').val()+"&password="+$('#password').val();
I am not pretty sure if sending params like a json object will work or not because i never used it.
Related
I am using AJAX to send a POST request to a Flask route, but I don't know how to get the post data in a format I can read.
My route looks like this:
#app.route("/sendinvites", methods=["POST"])
#login_required
def sendinvites():
print(request.get_data("emails"))
return jsonify("done")
My AJAX looks as:
$.ajax({
type: "POST",
dataType: "json",
url: "/sendinvites",
data: { emails : emails, usernames: usernames },
success: function(data) {
console.log(data)
}
});
An example of the data sent in the emails variable is:
0: Object { id: undefined, username: "me#mydomain.com" }
An example of the output from the route is:
b'emails%5B0%5D%5Busername%5D=me%40mydomain.com'
Does anyone know how I can get the post data into a dictionary object so it is easier to process?
There are many ways to do this, but first, verify that the request contains a valid JSON.
request.get_json()
request.get_json(silent=True)
With silent=True set, the get_json function will fail silently when trying to retrieve the JSON body. By default, this is set to False.
jsonify(request.json)
This will return the entire request object. You'll have to extract the required part by specifying the key posted while sending the request in your ajax code.
Refer this for Flask part, thread
Refer this for Ajax part, thread
I use this code to store and retrieve ajax data via http://openkeyval.org/
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify([123,456]),
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
$.ajax({ /* retrieve data */
url: "http://api.openkeyval.org/test-key-data",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
everything work fine in Chrome javascript console but in userscript I get error like this
Uncaught ReferenceError: jQuery110208458673823624849_1375932537303 is
not defined
I try to use GM_xmlhttpRequest to retrieve data like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data",
onload: function(response) {
console.log(response.responseText);
}
});
but it seem like openkeyval doesn't accept data via POST/GET method and log result was like when you access it directly from url of browser like this
{"error":"not_found","documentation_url":"http://openkeyval.org/"}
I include jQuery and it work fine with this code
// #require http://code.jquery.com/jquery-latest.min.js
I try to use Greasemonkey/jQuery XHR bridge with out change other code by like this
// #require http://courses.ischool.berkeley.edu/i290-4/f09/resources/gm_jq_xhr.js
and try use openkeyval official javascript library with code like this
// #require http://cdn.openkeyval.org/statics/openkeyval.packed.js
and retrieve data with code like this
var ourCallback = function(value, key) {
console('The value of ' + key ' + is ' + value);
};
window.remoteStorage.getItem('test-key-data', ourCallback);
still got error ERROR: Unexpected string
Please help, I mess with it more than 10 hours. Thank you so much.
It look like $.ajax always trigger error event function
but GM_xmlhttpRequest can retrieve mistype data, so I try looking for dataType: "jsonp" in GM_xmlhttpRequest and I got that jsonp header content-type is "application/javascript" OR "application/json" and the first one work well.
my new code for retrieve data look like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data?nocache=" + new Date(),
headers: {
"Content-Type": "application/javascript"
},
onload: function(response) {
console.log(response.responseText);
}
});
and retrieve data using $.ajax even it always trigger error event function but it still send data.
I try both content-type on GM_xmlhttpRequest and still not work.
my code to store data look like this
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify(myVarObject),
dataType: "jsonp"
});
Add this into $.ajax({...})
crossDomain: true;
It is because by default cross domain ability is disabled. See http://api.jquery.com/jQuery.ajax/
EDIT:
Sometimes there will be a issue with different charset between local script and remote script. Try using:
scriptCharset: "utf-8";
Also look at JQuery AJAX is not sending UTF-8 to my server, only in IE
Elaborating my comment
The reference is to the callback function generated by jquery.
It Sounds to me the way you invoke your userscript unloads the jquery functions before the callback is executed.
Perhaps you use a link and forgot the preventDefault?
If you ajax and have
$("#linkid").on("click"
or
$("#formid").on("submit"
it is MANDATORY to continue like this:
,function(e) {
e.preventDefault();
Otherwise the link is followed or the form is submitted which may not have any visible effect, but the asynchronous scripts have been (partially) unloaded unless the form and link has a target other than the current window
I was trying to get some information from another server using ajax post call as .
$.ajax({
type: 'POST',
url: testURL,
data: data,
//dataType: 'jsonp',
dataType: "script",
success: function (data) {
alert("Successfully posted (Test) : " + data);
},
error: function (ts) {
alert("Inside Error : " + ts.responseText);
}
});
Here testURL is the URL where i am posting the data (Cross domain requests are only possible if datatype is either jsonp or script), and it suppose to return text/html data back (what fiddler says will be the return type for the data).
I am not sure if i can use any proxy as pages are normal HTML pages.
Isn't there any way to get the [data] as text (as for now success expecting JASONP data and alert("Successfully posted (Test) : " + data); only showing data as undefined). I can't make any changes to API or whatever it is on the remote Server.
Thanks for the help in advance.
Regards
Without a proxy you cannot do it. If that is in a windows box, you can create a COM object to make the call to that server and from your JavaScript you call that COM.
UPDATE:
Well it seems you can with JSONP
jsonp with jquery
I have data that I want to send through an ajax GET request in following format -
{'url':['www.google.com','www.yahoo.com']}
Here is the ajax request - $.ajax({type:'GET',url:'http://www.example.com/',processData:false,data:JSON.stringify({'url':['www.google.com','www.yahoo.com']})
And since I am doing this in a bookmarklet it looks like this -
<a href="javascript:function iprl5() { $.ajax({
type:'GET',
url:'http://www.example.com/',
processData:false,
data:JSON.stringify({'url':['www.google.com','www.yahoo.com']}),
dataType:'json',
contentType: 'application/json',
success: function(json){$('#confirm').html('<p>Thanks!</p>');},
error: function(){$('#confirm').html('<p>Something went wrong :( please reload</p>');} })}} iprl5(); void(0)">BLAH</a>
The problem is that when I hit the bookmarklet browser sends a get request like this -
GET http://www.example.com/?{"url":["www.google.com","www.yahoo.com"]}
I want to send a json as a string but unable to do so, I also tried encodeURIComponent to encode string but that didn't work either.
I would try: data: 'url=' + JSON.stringify(['www.google.com','www.yahoo.com']),
The FCC recently made available a small set of API calls to access FCC data. In particular, I'm interested in the Consumer Broadband Test API. I'm trying to access this API through jQuery but am failing. Please let me know if I'm doing something wrong with my code or if this seems to be a problem with FCC's API.
If you visit this API request in a browser, it returns a XML response just fine: http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999
So I've tried to load this data in jQuery using various methods:
var url = "http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999";
$.ajax({
type: "GET",
url: url,
success: function(data) {
console.log("ajax: " + data);
}
});
$.getJSON(url, function(data) {
console.log("getJSON: " + data);
});
$.get(url, function(data) {
console.log("get: " + data);
});
In the Firebug console, all three requests show a 200 (OK) status, but the response body is empty. Also, the resulting console.log messages are:
ajax:
getJSON: null
get:
Am I doing something wrong here?
To work around the Same Origin Policy, you'll need to use JSONP. It is supported by the API. Add callback=? to the URL string in your .getJSON() call:
If the URL includes the string
"callback=?" in the URL, the request
is treated as JSONP instead. See the
discussion of the jsonp data type in
$.ajax() for more details.
So, something like this:
var url = "http://data.fcc.gov/api/speedtest/find?...&callback=?";
$.getJSON(url, function(data) {
// do stuff
});
References: http://api.jquery.com/jQuery.getJSON/
You can't make cross-domain calls using AJAX. It doesn't work like that.
What you probably want to do is to have your AJAX query URL be a local script on your own server, then have that script run a request for the API url (using cURL or something).