Cross domain Ajax call from HTML page (can't use any proxy) - ajax

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

Related

Laravel open url in server side after action

is there any way to open url in "server side".
I'm using https://www.lightsms.com/ as my sms gateway. And to send sms, you need to visit (for example) https://www.lightsms.com/send.php, so i don't want to redirect user to that url. I just want to open it in server background, and close.
after route and before real redirect, example's here:
Route::get('/sms', function() {
//i need to excecute that url here
redirect('success.html');
});
Is there any way to do this?
I think you need to do this asynchronously using xhr or ajax if you use jquery, you basically post the information asynchronously and your server (your php script) just returns a json back, in your success function / promise you can get the data and do something with it if you like, this process does not require any redirect.
This is a simple example which you may need to modify:
function asyncPost(event){
$.ajax({
url: "https://www.lightsms.com/send.php",
data: {
name: "any value or variable,"
id: "any value or variable"
},
datatype: "json",
type: "POST",
success: function(data) {
console.log("success");
// do something with data if you need, data contains the returned data from your php script
},
error: function(data) {
console.log("an error occured");
}
});
}

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.

How to send and retrieve cross-domain ajax data in userscript

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

Ajax with JQuery: 200 ok, but not "success"

I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:
var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
success: function(data, status){
alert(status);
}
});
Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?
Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.
You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.
Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.
http://code.google.com/apis/books/docs/js/devguide.html#execute
Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute
It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.
if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.
Docs here:
http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query
jQuery example
var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;
$.ajax({
type: 'GET',
url: URL,
dataType: 'jsonp',
success: function( data, status ){
alert( data.responseData.results.length + ' results found!' );
},
error: function() {
alert( 'Something goes wrong!' );
}
});
Ciao!

Why is this jQuery Ajax request failing?

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).

Resources