I am converting my webapp from PHP / HTML to JS/HTML so that it can work with phonegap. I am keeping the php server side files separate and on the server. I am having issues with executing AJAX calls from my local HTML file. When i check the console on chrome, it doesn't show any errors, but the ajax call doesn't return any value either. Ive simplified the issue so that people can easily understand what the problem is.
My JS code is
<head>
</head>
<body>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$.ajax({
url: "http://www.betsmart.org/betsmart/models/test.php",
method: "get",
dataType: "json",
crossDomain: true,
success: function(result){
console.log(result);
$("#text").html(result);
}
});
</script>
<h1 id="text"></h1>
</body>
My PHP code in test.php is
<?php
header("Access-Control-Allow-Origin: *");
echo "test";
?>
The success callback isn't executing. I understand the same origin policy will probably come into play here but i thought that doesn't matter with Phonegap.
Please do let me know where i'm going wrong or an alternate way to do this. If i have to use jsonp, what will be the client side and server side code?
Thanks
Gagan
Related
I am working on a project in which I'm in need to get the data stored in XML file using javascript or jQuery. My Script code is
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST", //I also tried POST method
url: "match.xml",
dataType: "xml",
success: function(data){
$(data).find("mchdata match").each(function(){ //match is a tag
$(".container").append('<div class="head">'+ $(this).attr("src") +'</div>'); //src is an attribute of match tag.
});
},
error: function(){
$(".container").text("Error occured");
}
});
});
</script>
Html code is
<body>
<div class="container"></div>
</body>
Every time I run this code it's showing 'Error occurred' message in container div. I tried to inspect the page, it shows an error message like
Failed to load file:///C:/Users/vinay%20Dahiya/Desktop/match.xml:
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https.
I don't know what does it mean. Is this the right script url 'm using
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
I'm trying to solve this for last 2-3 days but don't know what actually wrong in the code
XML file is View XML file
Thanks in advance.
I'm suggesting a quick fix for this, since you are testing this on a local machine and nowhere near production,
go to the folder where the xml is and start a simple python server there.
use
python -m SimpleHTTPServer
then you can access your file using,
http://localhost:8000/xxyy.xml
I am working on a project and I am trying to use jquery to send a variable to php. This a file called test2.php that I have been using to test out the code, can anyone tell me what I am doing wrong because it should be printing out the variable when you click on the button but nothing is happening.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var something="hello";
$("button").click(function(){
$.ajax({ url: 'test2.php',type: "GET", data: { q : something }});
});
});
</script>
</head>
<body>
<button>Get External Content</button>
</body>
</html>
<?php
if(isset($_GET['q']))
{
$q = $_GET["q"];
echo $q;
}
?>
Your code looks generally correct but you have to remember that an AJAX call sends the data "Asynchronously", which means when you click on the button this data is being sent to a separate instance of "test2.php" for processing. It is not reloading the current page with this new data.
The "test2.php" code you are viewing in browser is only run on the server side once when you first start up the page, and there is no 'q' in the '$_GET' variable at that time. The AJAX request is sending data to a separate instance of the same "test2.php" file and it is receiving some data back, but it is not using that information to load anything into your browser.
Depending on what you are trying to achieve there are many different solutions. You could use what you receive from your AJAX request to update information on the page like so:
$.ajax({
url: "test2.php",
type: "GET",
data: { q: something},
success: function (response) {
// do something with 'response' here
}
});
Or you could have the button instead be a simple <a> tag that reloads the current page in browser with information stored in '$_GET' like so:
Button
Then when your PHP code looks for 'q' it would actually find it in the $_GET variable because you reloaded the page.
Trying to do a simple AJAX call (teaching myself). I have a .txt file in same folder as html. What am I doing wrong here? Thanks.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#poo").submit(function(e){
e.preventDefault(); //stop submit
$.ajax({
type: "GET",
url: "data.txt",
data: "",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
}
});
});
});
</script>
</head>
<body>
<form id="poo">
<input type="text"> </input>
<input type="submit"> </input>
</form>
<br>
<br>
<div style='display: none;'>
<p id="foo">this shows</p>
</div>
Start Over
</body>
</head>
</html>
This is a convenience function that loads remote files via AJAX and uses .innerHTML() to load it into any elements in your jQuery selector.
// Does the exact same thing as the entire block of code you wrote..
// These jQuery methods are chainable so you can do this in 1 statement.
$("#foo") // Contains the DOM reference,
// so no need to use getElementById().
.load("data.txt") // Loads "data.txt" into "#foo".
.show(); // Makes "#foo" visible.
Relevant:
jQuery selectors and method chaining
jQuery load() method
jQuery show() method.
Per your comments, you had some other issues.
You said you weren't sure if jQuery was loaded. jQuery is just javascript, so you include it in <script></script> tags. The easiest way is to use jQuery's CDN. Click on the link, then choose the version and format you want. There will be a pop-up containing the script tag, just copy it into the page, preferably before any other Javascript you have on the page. If you're not sure which version/format to use, v1.x, minified is the way to go.
You mentioned that you were running it locally. The problem is, Javascript isn't supposed to have direct access to your filesystem. It will attempt to request the file over the http protocol, without having server software you can only request files over the file:// protocol.
There are zillions of topics on this all over the internet, but to solve it you should install a server. XAMPP is a good one and it's cross platform. Download that and your application will work in all your browsers. It will work in your browsers when you upload it to a server as well
try to add the dataType: "text"
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
})
I have made an Ajax call to Bing to get its daily image, however i get an error in the console:
this is the full code its on a localhost using wamp
index.php
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
$.ajax({
url : "http://bing.com/HPImageArchive.aspx?format=js&idx=0&n=1",
dataType:"jsonp",
});
function mycallback(data)
{
$('#output').html(data.images[0].url);
}
</script>
I think you should study the documention for jquery ajax call.
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
(function() {
var bingImagesUrl = "http://bing.com/HPImageArchive.aspx";
$.getJSON( bingImagesUrl, {
idx:0,
n:1,
format: "js"
}).done(function( data ) {
$('#output').html(data.images[0].url);
});
})();
</script>
#Below_the_Radar: your answer does not really help as OP is likely getting the same error even if he makes the Ajax call correctly.
According to Is there a way to get Bing's photo of the day?, it seems that Bing.com only supports XML, JSON, and RSS. I guess OP want to make the call with dataType: "jsonp" probably because he would like to bypass the browsers same-origin policy.
This can be solved client-side in browser by using a Chrome extension, but I guess that is not OP's use case. I bet OP is trying to get a picture from Bing's archive and thus use it in his own website. If that is the case, it has no solution as we need to have "Access-Control-Allow-Origin": "*" in the response's headers returned by Bing, which we do not have control.
I suggest considering an alternative. Try this: https://source.unsplash.com/
I'm developing a website based in to servers. One is a free host and another is a Raspberry Pi. When you access a webpage in the free host, you get a form where you enter a link. The link is send to the Raspberry Pi which is permanently running a script that downloads some content of the link recieved and saves a big txt file. The script takes a bit to load (30 secs aprox) so I want to create a Javascript script in the primary page (free host one, with the form) wich shows a load icon and checks in the raspberry downloads folder until the file exists.
I think AJAX will be the best for this. The workflow is:
user access form.php and enters a link
the form is send directly to the RPi
the RPi begins to download things and returns the user to the refferrer page with the get parameter id=
here the ajax code begins to work checks into an url if .txt exists if it exists, it shows the download link else, it waits checking until it gets a 200 status code (This is what i need)
I know the problem with javascript and different servers so i've created a php script named check.php in the same server and folder of form.php which gets id as parameter and return 200 or 404 so the ajax code just needs to get that answer and act in consecuence
How can I do it? I'm new to AJAX, I know just a bit of Javascript. Could you help me withe the AJAX code?
My form.php?id= page:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>downloader</title>
</head>
<body>
<div id="content">
<?
if (!$_GET){
?>
<form action="<<rpi server>>" method="post">
URL: <input type="text" name="link">
<input type="submit" value="Download">
</form>
<?
}else{
?>
<script>
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'<? echo $_GET['id']; ?>'},
//check if response is 200 or 404, if it's 404 keep checking every second, else show mesage
}
});
</script>
<?
}
?>
</div>
</body>
</html>
Use this
function checkFile()
{
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'999'},
error : function(){
setTimeout(function(){ checkFile(); }, 3000);
},
success : function(data) {
//do whatever you want
}
});
}
$(function() {
checkFile();
});