My Problem
I am trying to load JSON encoded data from a remote site using jQuery, however when jQuery tries to call this URL it appends the correct function to callback=? so it's something like callback=jsonp1256856769 but it also adds _=1256856769 to the url. So the url ends up being something like http://www.example.com/link/to/file.php?format=json&lang=en&callback=jsonp1256856769&_=1256856769
Now the problem is that that file that I am using that calls it can't interpret the _=1234234 and I can't change it so I have to fix the jQuery problems
My Question
How can I get jQuery to not appened that _= to the URL that it calls
What I have done to try to figure out my problem
Removed all other javascript libraries from the page
Tried several different versions of jQuery
My Code
function getData(){
url = "http://www.example.com/link/to/file.php";
url += "?format=json&lang=en";
$.getJSON(url+"&callback=?",function(data){formatData(data);});
}
*Above is the snippet of JavaScript that I am currently using
*Note the domain I am using is not example.com
UPDATE: added code
The _= part is there, because JSONP request are cache: false by default. You can set cache: true, which will make the _= part go away, but the browser will cache the requests.
function getData() {
url = "http://www.example.com/link/to/file.php";
url += "?format=json&lang=en";
$.ajax({
'url': url,
'type': 'GET',
'dataType': 'jsonp', // this adds &callback=? by design
'cache': true,
'success': function(data) { formatData(data); }
});
}
Related
Inside my controller I have this function for the route /backups
public function index()
{
$backups = \App\Backup::all();
if(request()->ajax()) {
return $backups;
}
return view('backups.index', compact('backups'));
}
My idea was that if I have my javascript ask for the data then return json if not return html.
This works fine, except when pressing the browser back button to go from lets say /backups/1 to /backups it shows the json.
Is there another function I can use that will only respond to ajax calls from my code and not the browsers?
I'd recommend adding an ajax-only query string parameter to the ajax request, e.g. ?ajax=1.
This way, you can 1. utilise the browser cache, and 2. keep the same Laravel route for both request types.
Make sure your AJAX requests use a different URL from the full HTML documents. Chrome (and most probably Firefox) caches the most recent request even if it is just a partial.
Source:
https://code.google.com/p/chromium/issues/detail?id=108425
Or:
Try setting cache to false
$.ajax({
dataType: "json",
url: url,
cache: false,
success: function (data) {...}
});
I need to make a request to a dedicate website , using jsonp for cross domain reason to get back a XML result and work on it.
So basicly I am doing this to start :
(function($) {
var url = 'http://www.website.....';
$.ajax({
type: 'GET',
url: url,
// async: false,
// contentType: "application/json",
dataType: 'jsonp',
});
})(jQuery);
I can finally get an answer from website, that I can see in the firebug plugin, but in XML tab
such as :
<Results xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.website.com">
<ResultSet id="searchResults" numResults="3" >
From my understanding jsonp is a json object and in my case it s returning a XML content.
My problem is how to manage the XML return from the website? I can parse it and play with in the javascript code.
You need to define your jsonpcallback in order to tinker with the return value of the request.
See:
jsonpCallback function not working
http://api.jquery.com/jquery.ajax/
I do not want the requested page to be cached by the browser. Would a post request fix this? Is there much downside to making a POST instead of a GET?
At the moment I am using like:
$.get("/Client/JSON_GetInvoiceLines/" + ClientID, function (data) {
//do stuff
});
you can use the cache option in jQuery.
$.ajax({
url: '/Client/JSON_GetInvoiceLines/',
type: 'GET',
cache: false,
success: function(data){
// do stuff
}
});
It will append a random character string as a GET parameter to the end of your URL, so the browser won't cache it.
However, the ideal solution would be to disable caching on the server-side by setting headers, assuming you have control over the resource that you're requesting.
I want to know the content type of a given url input by the user inside my Javascript code. Actually, I have a drop-down list (html,csv,xls etc.) and I want to make it so when the user inputs an url, I want to detect the type of the content of the url and based on this type I want to set the value of my drop-down list (html,csv,xls etc.). I know, I can get the content type using Ruby like this :
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
or, also, I could use curl to get the content and then parse it to know the content type. But, I need to do this inside my Javascript code because of my need explained above. Any thought ?
EDIT_1 :
I tried this code in my javascript :
$("#wiki_form_url").change(function(){
$.ajax({
type: "GET",
url: "content.rb",
data: {
// input_url: $("#wiki_form_url").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert('Success !!!');
}).fail(function () {
alert("failed AJAX call");
});
});
I have a ruby script content.rb inside which I do :
require 'open-uri'
str = open('http://www.ofdp.org/benchmark_indices/25')
str.content_type
But, it does not seem to work. I am getting Ajax failure. May be it's because of url path of the script content.rb ? How should I specify a script path here ? (Relative or absolute)
The same origin policy prevents you from using client side JavaScript to directly discover information about arbitrary URIs (URIs you control are a different story).
You'll need to get that information with another technology, such as your server side Ruby.
You could do this by simply submitting a form to the server and returning a new webpage to the browser.
If you don't want to leave the page, then you can pass the data using Ajax. There are no shortage of Ajax tutorials out there, here is a good one from MDN.
Here's an example of an AJAX call:
$(document).ready(function () {
$("#button_check").on("click", function () {
$.ajax({
type: "GET",
url: "Your URL",
data: {
input_url: $("#textbox_id").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
});
Where your HTML is something like:
<input type="text" id="textbox_id" />
<input type="button" id="button_check" value="Submit" />
And your Ruby code would be something like:
require 'open-uri'
class TestController < ApplicationController
def index
req = open(params[:input_url])
render :text => req.content_type
end
end
I have never used RoR before, so I have no idea if this is right or works in the slightest. But it's what I could quickly conjure up when scrambling through several tutorials. It's simply the concept you seem to be looking for. You'll need to figure out how to map a URL to this method, and then update the AJAX option url to use that.
So in the Javascript code - in the done method, that means the whole AJAX request was successful and the data variable should contain the result from the Ruby code req.content_type.
Atlast I could figure out the whole thing with the great help of #Ian. Here is my completed code : In javascript file :
$("#wiki_form_url").change(function () {
$.ajax({
type: "GET",
url: "/wiki_forms/content",
data: {
input_url: $("#wiki_form_url").val()
},
dataType: "text"
}).done(function (data) {
// `data` contains the content-type
alert('Success');
console.log(data);
// alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
Inside my wiki_forms controller I created a new method named content :
def content
req = open(params[:input_url])
render :text => req.content_type
end
Then added a new route in routes.rb file :
get "/wiki_forms/content" => 'wiki_forms#content'
and used /wiki_forms/content as the ajax request url. And, everything is working nicely now.
I'm not sure if this is crossdomain issue or not. I'm trying to use $.ajax to load file. But some file I get readyState=4 and some file I get readyState=1
This is the path where I run my jasmine test
file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html
And in the code I used jQuery.pyte to require relevant file. But it's stuck at readyState:1 when the code comes to $.ajax
if I do something like this, it returns readyState=4 correctly and print out the content inside SpecRunner.html
$.ajax({url: 'file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html', async: false}).responseText
but if I do something like this, I only get readyState=1 and nothing is returned.
$.ajax({url: 'file:///home/myname/development/path1/path2/src/main/webapp/static/js/core/application/FileThatIWant.js', async: false}).responseText
you should avoid file:// URLs in general, because browsers do not allow them in many different places. Try XAMPP it's a simple to use local webserver, you will definitively need one.
Yes, this is a cross-domain issue. You can solve this problem by forcing jQuery to use crossdomain AJAX (JSONP).
$.ajax({
url: "yoururl",
cache: false,
crossDomain: true,
data: {}, //put your GET parameters here or directly into the url
dataType: "jsonp",
processData: true,
success: function(data, textStatus, jqXHR){
//This will be executed if it worked
},
error: function(data, textStatus, jqXHR){
//This will be executed if it failed
},
timeout: 4000, //You can put any value here
traditional: true,
type: "GET"
});
jQuery will automatically add a callback parameter containing a random string (&callback=XXXXXX).
The target URL needs to output the following:
XXXXX(your_output_encoded_in_JSON);
where XXXXX is the random string. The PHP code to do so is:
echo $_GET["callback"]."(".json_encode($myoutput).");";
Make sure that the PHP (or whatever language you're using) page ONLY outputs that!
If, instead, the page you are querying is not built dynamically, such as an HTML page, you need to add the following options to the $.ajax options object:
jsonp: false,
jsonpCallback: "mycallback",
mimeType: "text/javascript",
Your .html file will contain something like this:
mycallback("<html><head></head><body>TEST PAGE. This is a double quote: \" and I didn't forget to escape it!</body></html>");
This technique is very handy to bypass the strict crossdomain restrictions hardcoded in browsers, but it only supports GET parameters. XMLHTTPRequest v2 supports cross-domain requests, but we won't be able to assume that all users have a XHRv2-compatible browser before at least 2016.
http://caniuse.com/xhr2