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');
})
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.
I am trying to have my site use Ajax from another file but it never works unless the code is actually in the view.
The site successfully calls my other Javascript file but does not seem to recognize the one with Ajax in it.
The following is in my external Javascript file with Ajax in it (ajax.js):
$(document).ready(function(){
$("#idForm").submit(function(e) {
$.ajax({
type: "POST",
url: "{{ url('/auth/login') }}",
data: $("#idForm").serialize(),
success: function(data)
{
location.reload();
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
And the following is in my master layout file that successfully uses the form.js file but not ajax.js .
<html>
<body>
<!--Other Stuff-->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/forms.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/ajax.js"></script>
</body>
</html>
Any ideas?
By default, external js file don't support blade syntax. So, to send the ajax request from external js file need to do the followings:
create a global variable to ur template.blade.php file as follows:
var SITE_URL = "{{URL::to('/')}}";
then when to send the ajax request do:
$.ajax({
url: SITE_URL + '/route_name'
});
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
I am creating a simple web application for a comic using HTML and JavaScript. Because people that are not very technical should be able to add new comics, I thought about using an XML file as a configuration file.
I thought about using JSON and decided against it, mainly because the way comma's are used(no comma between two items breaks it, but a comma at the end of the list also breaks it.).
However, my question is now: How can I embed this XML file? Do I use the <link rel= /> tag, or something else like the <embed src= /> tag? And how can I then read information from the XML nodes in JavaScript?
I would recommend loading a JavaScript library that makes this easy. jQuery is one. If you include jQuery in your page then you use it to load the document and get access to the browser's XML parsing capabilities fairly easily.
http://api.jquery.com/jQuery.parseXML/ shows a simple example of finding values in an xml document once it's loaded.
This site http://think2loud.com/224-reading-xml-with-jquery/ gives a good example of how to load XML from a remote site. The basic idea is to use AJAX: here's a tiny snippet for posterity that will load foo.xml after the html document has loaded (relies on jQuery):
$( function() {
$.ajax({
type: "GET",
url: "foo.xml",
dataType: "xml",
success: myHandler(xml) {
}
});
});
Use xml tag. Example :
<html>
<xml Id = msg>
<message>
<to> Visitors </to>
<from> Author </from>
<Subject> XML Code Islands </Subject>
</message>
</xml>
</html>