I am trying to brush up on my jquery and ajax. In Jquery in 8 hours there is this:
<!DOCTYPE html>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A JQuery Sample Program</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
$.ajax({
type:"POST",
url:"postFile.php",
data: {data:100},
success:function(data) {
$("div").html(data);} });});
</script>
</head>
<body>
Response: <div></div>
</body></html>
and postFile.php is this:
<?php
if ($_POST["data"]=="100") {echo "100";}
?>
I'm running this under IISExpress. BUT all I get from the browser (Chrome) is method not allowed in jquery.min.js:4. This seems so simple and yet, doesn't work.
Method not allowed usually happens when you're trying to request a file that's on another domain. I assume that's not your real code since it looks like you're calling a file that's on the same domain. Read about cross domain scripting. You can't do AJAX calls to a script that's on a different domain.
Related
I have a very simple HTML file which has one button. When this button is clicked the function loadDoc() runs in the javascript file (ajax.js). The div with ID ajax_text gets changed into 'clicked'. So far so good.
Now I am trying to make ajax call to a php document. The php document should echo "Hello World!". I am trying to show this message by using an alert (alert(msg)). The php document is located in the same folder as my HTML document.
What am I doing wrong in my ajax call??
I already tried multiple urls such as:
- 'http://localhost/ajax_info.php'
- the complete path to the file
- 'localhost/ajax_info.php'
etc. etc.
HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="name">John</div>
<div id="demo">
<h2>Header 2</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script src="jquery-3.2.1.js"></script>
<script src="ajax.js"></script>
</body>
</html>
JavaScript:
function loadDoc() {
document.getElementById('name').innerHTML = "Steven";
$.ajax({
type: 'GET',
url: 'ajax_info.php',
success: function(msg){
alert(msg);
}
});
}
PHP:
<?php echo "Hello World"; ?>
It looks as if you call your html page as file from your file-explorer, but not - as you should - via your web-server.
If your address in the browser has file://somefolders/myhtml.html your php script (well, actually the server) will say "hello, that's not where I am!" -> It throws "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
Now you can tell your server "Nah, don't bother, I'll just allow everyone!"
This is what you do when setting the header('Access-Control-Allow-Origin: *');
But your initial problem was that the html-file wasn't called at the same origin, namely your (local) server.
So if you type in your browser's address bar http://localhost/ajax.html and don't just double click the file in file-explorer it should work, because now they both (html and php) live in the same environment.
try to write the javascript code inside the page that has html.
it should works .
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="name">John</div>
<div id="demo">
<h2>Header 2</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script src="jquery-3.2.1.js"></script>
<script>
function loadDoc() {
document.getElementById('name').innerHTML = "Steven";
$.ajax({
type: 'GET',
url: 'ajax_info.php',
success: function(msg){
alert(msg);
}
});
}
</script>
I'm trying to get photos from instagram by get request,
I tried jQuery.get() which worked well for other purpose of get request which is not instagram,
but for this one it doesn't work.
I used postman and I get the request no problem at all,
I also tried to change from jQuery.get() to jQuery.getJSON() and still no luck.
By the way, tried to get the request with NodeJS using request module and it works fine.
Hope you can help, here is my simple code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(function () {
$.get("https://www.instagram.com/uefachampionsleague/media/",
function (data) {
alert(items[0].id);
},"json");
});
</script>
</head>
<body>
<p></p>
</body>
</html>
You need to register your application and then set the credentials in the AJAX request, or you can also use the crossorigenme proxy:
$(function () {
$.get('https://crossorigin.me/https://www.instagram.com/uefachampionsleague/media/', function(data) { console.log(data); });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
As Jaromanda added "It's worth noting the caveat on crossorigin.me - PLEASE DO NOT USE THE PROXY ON A PRODUCTION SITE - if you want to "bypass" CORS, use your own damned server to do it".
I have a page where I am loading another remote source using a element. Everything works great, except, now I want to be able to change the 'src' of the script depending on certain conditions when loading the page. The problem is, when I change the 'src', even though it changes in the DOM, it has no affect. The original 'src' is used and never updated.
Is it possible to dynamically retrieve the source of a remote site, or does this value have to be constant?
Edit: here is a sample of what I'm attempting:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://voap.weather.com/weather/oap/90210?
template=GENXV&par=3000000007&unit=0&key=XXX"></script>
<script>
$(document).ready(function(){
var newS = document.createElement('script');
newS.type = "text/javascript";
newS.src = "http://voap.weather.com/weather/oap/90210?template=GENXV&par=3000000007&unit=0&key=XXX";
$("head").append (newS);
});
</script>
</head>
<body>
</body>
</html>
You will notice that the 'script' which is at the top works fine. The script I attempt to add dynamically does not work at all. It shows up in the DOM-inspector, but not in the page.
Also, see the following:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getScript("http://w3schools.com/jquery/demo_ajax_script.js");
$.getScript("http://voap.weather.com/weather/oap/90210?template=GENXV&par=3000000007&unit=0&key=XXX");
});
</script>
</head>
<body>
</body>
</html>
In this example, the w3school example works, but the weather does not.
There's a couple things going on here:
The remote server is returning the wrong content type
The script returned by the remote server is using document.write
The first problem seems to mean you can't use $.getScript to get the remote script. But even if you could, you wouldn't want to because of the second concern because you can't run the script from weather.com inside your top-level document after the document is ready unless you want to destroy the whole page and replace it with the weather data.
You can, however, insert the script tag dynamically using your own document.write before the document is finished loading (don't wrap it with $(function(){})), $(document).ready(function(){}) or any other variant of document readiness event handler:
<script type="text/javascript">
document.write('<script src="http://voap.weather.com/weather/oap/90210?template=GENXV&par=3000000007&unit=0&key=XXX">' + '<\/script>');
</script>
And you can build those string parameters using some dynamic logic if you need to.
The script is not being loaded because its it being returned with text/html headers. It would need to be served and returned with the Content-Type header of application/x-javascript.
If you dont have control over the headers that the script is served with then I would suggest you contact the provider and request that they change those.
Right now it gives a warning:
Resource interpreted as Script but transferred with MIME type text/html: "http://voap.weather.com/weather/oap/90210?template=GENXV&par=3000000007&unit=0&key=XXX&_=1387307745041"
Have a look for yourself using this fiddle: http://jsfiddle.net/sVAP9/
#!
How about fiddling with the <iframe> element, and using it to do xrequests?
I approach ( hardcore one ):
Doing document.write() thing after window.onload wipes out all the content you've got loaded before running it. Async script load is using 'document.write', and browsers don't like it very much ( check out the A call to document.write() from an asynchronously-loaded external script was ignored. error in the console ).
Something like this maybe ( fiddle ):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>x</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$( function () {
var widg$ = $("#widg");
$("#btn")
.on({
click : function () {
widg$.attr({
src : "http://voap.weather.com/weather/oap/90210?template=GENXV&par=3000000007&unit=0&key=XXX"
});
}
});
} );
</script>
</head>
<body>
<button id="btn" style="display:block;">load</button>
<iframe
id="widg"
src=""
frameborder="0"
style="margin:0; padding:0; border:none; width:300px; height:500px;"
seamless
></iframe>
</body>
</html>
II approach ( a little bit of hack ):
You cannot send xdomain requests via ajax inside browser sandbox,
without the help of backend curl that is. Make this php file ( hope your server supports it ):
_xdread.php
<?php
header('Content-Type: '. $_POST['url_mime']);
$url = $_POST['fetch_url'];
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
echo curl_exec( $ch );
exit;
Place it in the same directory where your page is. Use jQuery to send http request to local php file. Set .dataType to text/plain, to avoid script auto-interpretation. It will curl the url and echo the response back. eval the response in the context of <iframe>'s .contentWindow. That way it will not ignore 'xdomain document.write()', because it is done localy:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>x</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function () {
var widg$ = $("#widg");
$("#btn")
.on({
click: function () {
$.ajax({
url :'_xdread.php',
type :'post',
dataType :'text',
data :{
fetch_url :'http://voap.weather.com/weather/oap/90210?template=GENXV&par=3000000007&unit=0&key=XXX',
url_mime :'text/plain'
},
success:function ( jstxt ) {
//console.log( jstxt );
widg$[0]
.contentWindow
.eval( jstxt );
}
});
}
});
});
</script>
</head>
<body>
<button id="btn" style="display:block;">load</button>
<iframe
id="widg"
src=""
frameborder="0"
style="margin:0; padding:0; border:none; width:200px; height:300px;"
seamless
></iframe>
</body>
</html>
You're using jQuery, so use getScript. http://api.jquery.com/jQuery.getScript
Don't reinvent the wheel if you already included the car factory.
Most of above answers clearly tell that you are accessing content from cross domain and also
the return type is text/html rather jsonp which could have solved this problem.
It seems like you using only that service and not designing it, that is why you could not change to response of script.
There is one solution that you include all possible scripts in html like this
<body>
<div id="script1">
<script src="{url of script 1}"></script>
</div>
<div id="script2">
<script src="{url of script 2}"></script>
</div>
<div id="script3">
<script src="{url of script 3}"></script>
</div>
</body>
and according to your manipulation show only that div which is required and hide other
because normally we can change the scr value of script but it will not load fresh content from that URL.
Therefore strategy will be load all script then show only one of them
I think this is a very simple question, but I can't seem to get it to work. I need to use JavaScript (specifically jQuery, apparently) to grab some content from a page, and pull it into another page. I've researched this quite a bit, but can't seem to get even a very simple example to work.
Here is the page I'm trying to get content from:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
</head>
<body>
<p>This is the test html page.</p>
</body>
</html>
Here is the page I'm trying to use to pull the content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PullData</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
<body>
<ol id="result"></ol>
<script type="text/javascript">
$('#result').load('test.html');
</script>
</body>
</html>
When I open the page it doesn't seem to do anything. I'm basically trying to follow the examples from jquery.com: http://api.jquery.com/load/
Both html pages are in the same folder somewhere on my C drive.
What am I missing?
Thanks in advance for your help!
What browser are you using?
Because of same-origin policy, some browsers won't permit AJAX requests to file:/// URLs, even if the original file was loaded that way. I know this is true of Chrome, but haven't tested others.
What does your .load() error handler say? Oh...
It seems to make logical sense.
Checking the API on load you may want to see if it actually loads, or if it encoutners an error
$("#result").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#result").html(msg + xhr.status + " " + xhr.statusText);
}
});
API LINK: http://api.jquery.com/load/
sometimes the debugging information is a good first step to any solution.
You have your script tags at the end of your page, which means the enclosed JS will be invoked as soon as the browser reaches it, which may not be before the DOM is ready (which means the <ol> might not be set up to get the content of test.html). Try enclosing your load in a $(document).ready() callback as follows:
<script type="text/javascript">
$(document).ready(function() {
$('#result').load('test.html');
});
</script>
Also why are you inserting a full HTML page into an ordered list? You should try an HTML snippet (no head & body tags) into a content holder such as <div> or <span> where it will be semantically correct.
If none of these things work, attach a callback as follows:
$('#result').load('test.html', null, function(responseText, textStatus, xhr) {
alert(textStatus); // see what the response status is
});
Where is the closing script tag?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
Your code needs to be
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
You must first check if your HTML is ready.
$(document).ready(function() {
$('#result').load('test.html');
});
To ensure #result1 is loaded, you need a document.ready event handler:
<script type="text/javascript">
$(document).ready(function(){
$('#result').load('test.html');
});
</script>
Hope this helps. Cheers
Hey guys,
I have a little problem with a simple ajax request. I can't figure it out why jquery ajax method doesn't work with the last version of chrome ... on ff work great so as on opera but on chrome i don't get any response and no errors. This is my js code:
function load(idno){
var url = 'index.php';
$.get(
url,
{
pagina:"ajax",
show:"cars",
brand:idno
},
function(data) { document.getElementById("model").innerHTML=data },
"html"
);
}
Any reason you're not just using jQuery.load()? Eg
$('#model').load('index.php', {
pagina: 'ajax',
show: 'cars',
brand: idno
});
At a guess, I'd say the problem is with the innerHTML call. A more robust method would be to use jQuery.html(), eg
function(data) { $('#model').html(data); }
Edit
Just whipped up this test and it works fine
<?php
// test.php
echo '<pre>', print_r($_REQUEST, true), '</pre>';
<!-- test.html -->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="model">
Default text
</div>
<p><button id="fetch-data">Fetch Data</button></p>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('#fetch-data').click(function() {
$('#model').load('test.php', {
pagina: 'ajax',
show: 'cars',
brand: 123
});
return false;
});
});
</script>
</body>
</html>
When I click the button, I can see all the request variables sent to the script
After a long long nith I've managed to resolve the problem. My JS code is good and maybe Phil's too ... I didn't try that in this version but the real problem in Chrome is that onclick attributes on option tags aren't allowed. So I made the event
<select onchange='loadData(this.value,'models')'></select>
and it is working great. Thank you Phil anyway.
because of Security reason chrome not allow cross-domain communication if request is not from a trusted sites,
if you want to use $.ajax in chrome so you need to disbale web security of chrome
use this comman.
your_chrome_path --disable-web-security
after doing this $.ajax works fine.