I have this Kendo UI datasource. I am trying to pass the data parameter
transport: {
read: {
url: "http://clientstoprofits.paupertopresident.com/api/Schedule/Tasks_Read",
data:{
UserId:id,
startDate:startTime
},
dataType: "jsonp"
},
but the only thing that is being sent is
Request URL:http://mydomain.com/api/Schedule/Tasks_Read?callback=jQuery19107631381487008184_1398210088201&_=1398210088207
can anybody tell me why i am getting this callback=Jquery*?
The callback url parameter is the name of the callback jQuery created for this JSONP request (for a more detailed explanation, take a look at the dataType option for jQuery.ajax().
As to why your data is not being sent: you can only do that with POST requests, and JSONP requests are by definition GET requests. So you'll have to encode the user id and start date as url params instead.
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 am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.
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.
I have enabled Codeigniter's CSRF protection on my site that uses AJAX to submit a user form and handles some other user interaction which require data submission via AJAX. As a result I came up against the "action not allowed" server side error. I quickly worked out that only the data my javascript collected and submitted via AJAX was passed to the server and as a result the CSRF code was not being sent.
The generated token tag looks like:
<input type="hidden" name="csrf_test_name" value="dsflkabsdf888ads888XXXXXX" />
So it seems to me the simplest way to submit the token to the server for verification is using a jQuery selector on csrf_test_name to get the value and then adding this to my post data for the server to verify. As per the code below:
//get CSRF token
var csrf = $('[name="csrf_test_name"]').val();
//build the form data array
var form_data = {
csrf_test_name: csrf,
... ... ...
... ... ...
}
//send the form data to the server so it can be stored
$.ajax({
type: "POST",
data: form_data,
url: ...,
dataType: "html",
success: function(msg){
... ... ...
}//end success
});//end ajax
I have followed this procedure for every ajax submission that sends data to the server and the server side error is fixed and everything works fine.
To test this I have hard coded in an incorrect CSRF token and the server detects the inconsistency and returns an erro code 500 so on the surface this works.
My question is this, is this a safe way to do this and is there an expected best practice to follow? I have done some google searching on this and it seems all the other methods are more complex and I am wondering if my way creates an attack vector that I can't see/workout.
I like to add it to the Ajax setup. Set it once and have it automatically add it to the post data for all of your requests.
$.ajaxSetup({
data: {
csrf_test_name: $("input[name='csrf_test_name']").val()
}
});
an easier method is to pass that csrf to $.ajaxSetup() that way it's included with any $.ajax() request afterward.
var csrf = $('input[name="csrf_test_name"]').val();
var data = {};
data[CSRF] = csrf;
$.ajaxSetup({ 'data': data });
then no need to include data: { csrf_test_name: 'xxx', ... } in requests after setup.
I was trying to send an ajax request as POST request. But when i verified it on httpFox on firefox, the request is sent as GET. I tried both $.ajax() and $.post().
Many had a query regarding the same and had missed the "type" in $.ajax(), but even if i mention the type as "POST", the request will be of type GET.
Here is my code:
$('.test').click(function(){
alert("clicked");
$.ajax({
type: "POST",
url: "www.testsite.com",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
Any idea why it happens?
A possible cause might be the fact that you are trying to send an AJAX request to a different domain: www.testsite.com than the one hosting your page which of course is not possible and jQuery tries to use JSONP instead which works only with HTTP GET.