Sending javascript dictionary with array values via ajax through a bookmarklet - ajax

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']),

Related

Ajax request error with elasticsearch

I simple make get req with ajax to elasticsearc to get all indices,
in browser it works here:
its same in my ajax, I expected the json data in browser return to my success method but failed:
Response is not JSON, you can change the response to a JSON in your server program.
It should work if you replace json by jsonp in your dataType parameter, like this:
$.ajax({
url: "http://localhost:9200/dicoms/dicoms/_search",
dataType: "jsonp", <--- change this
type: "GET",
success: function(data) {
...
});

jQuery Cross Domain Request to get JSON Response without Callback

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.

Malformed JSON response being sent by Play Server

I am using jquery Ajax to send data to the client and get reply from the Client.
I am using Play Framework as backend.
AJAX:
$.ajax({
type: "GET",
url: '/authenticate',
data: {'type':type, 'redirectURL':getRedirectURL},
contentType: "application/json; charset=UTF-8",
dataType: 'json'
}).success(function( msg, txtStatus, jqXHR) {
console.log("asdasd5= "+msg);
console.log("asdasd5= "+msg.authUrl);
console.log("asdasd5= "+jqXHR.authUrl);
window.location = msg;
});
SERVER DATA CREATION:
response.setContentTypeIfNotSet("text/plain; charset=UTF-8");
Logger.info("response content type ="+response.contentType);
renderJSON("{\"authUrl\": " + authUrl +"}");
The server is sending something like "www.mywebsite.com/yoohoo/auth/1231"
But the response received by Ajax is �����������������{"authUrl": www.mywebsite.com/yoohoo/auth/1231}
DUE to these weird character the JSON response received cannot be parsed by jQuery.
Kindly, help on this.
Thanks
I noted that you are sending back (server-side) a MIME type of "text/plain". Perhaps switch to "application/json". Additionally, you could take the return string and strip any junk from the string before parsing the JSON out on the client side. This would help sanitize in case you change something again server-side and accidentally introduce new/different "junk".

Attach requestbody to jQuery ajax

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.

Not able to send POST request through jQuery Ajax

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.

Resources