Very often it is necessary to load contents from files that are stored in server into a Javascript variable or display it in a HTML element in order to accomplish some task inside a webpage.
How can I do that without relying in JQuery?
One of the easiest ways I have found of doing that is by creating a function that gets a file and call's back another function when the download is ready.
So in the example below, when the "test.txt" file content is loaded, it is displayed in a pre element.
<html>
<body>
<pre id="output"></pre>
</body>
<script type="text/javascript">
function get_file(url, callback)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.send();
}
get_file("test.txt", function(response)
{
document.getElementById("output").innerHTML=response;
});
</script>
</html>
IMPORTANT
If you want to make your XMLHttpRequest synchronous, just change the line
xmlhttp.open("GET", url, true);
To
xmlhttp.open("GET", url, false);
But it will come at the expense of hanging your webpage until the data is loaded.
Try using fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
It's much easier to use than XMLHttpRequest.
Then, once you've fetched the resource, use insertAdjacentHtml to add it to the document body: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
i.e.
fetch("test.json")
.then(function(response) {
return response.json();
})
.then(function(json) {
document.body.insertAdjacentHtml("afterbegin", "<p>" + json + "</p>);
});
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
Related
I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)
I'm new to coding and now I'm trying to write a code that gets the text data form a file and replace the present text with the new one. I'm using AJAX to do the task but the problem is first I'm getting the error message and then expected answer The error message is what I have included in the code to display when there is error. Even though i'm getting the desired answer I want to know why the error message is displayed. Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
function loadXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
}
else {
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
}
else {
alert(" there is a error in your code");
}
}
xmlhttp.open("GET","robots.txt", true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<p id="p1">This is Text</p>
<button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>
The problem is your if-block in onreadystatechange. During the request and response, xmlhttp.readyState changes multiple times and onreadystatechange is called every time this happens.
If you do it like this, it may work:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
} else {
alert(" there is a error in your code");
}
}
It is simpler, however, to use the other event-methods like onload and onerror, as described here.
1- include 1 jQuery file jquery-1.9.0.js same as jquery-1.9.0.min.js but jquery-1.9.0.min.js is minified file
2- what is the Error message from javaconsole log ?
3- you are using jQuery so why you are working with XMLHttpRequest when jQuery $.get already using best of HttpRequest for all browsers
you can replace your JS code with this
<script type="text/javascript">
$( document ).ready(function() {
$.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>
Are you using a webserver ? Ajax doesn't work from local file url : 'file://...'
alert(" there is a error in your code");
Actually there is no error in your code. xmlhttp.onreadystatechange is called in different states of the request. Thats why you check for xmlhttp.readyState == 4. Learn more about the different stages here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
So your code is running fine, you just alert an error message, that is not an error at all.
I have a small,simple application.Its on Tomcat 7.Testing on Firefox browser.
My html page resides in
%CATALINA_HOME%\webapps\examples\servlets.
So, I access my html page using the URL:
http://localhost:8080/examples/servlets/userinputs.html
My java servlet(calls a third party API and returns a text/html response) resides in %CATALINA_HOME%\webapps\examples\WEB-INF\classes.
I am using AJAX call in my js file to call this servlet via the URL:
http://localhost:8080/examples/servlets/servlet/challengetask
The responseText returned is empty.If I access the servlet from browser,I can see the response.
I did go through the same-domain policy and searched
the internet for similar problems.However, I am unable to figure out as to why the responseText is empty and what EXACTLY is the problem.
My AJAX call :
var request =false;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
}
}
if(request){
request.open("GET",url,true);
request.onreadystatechange = callBack;
request.setRequestHeader("Connection","Close");
request.setRequestHeader("Method","GET"+url+"HTTP/1.1");
request.send();
}
else {
alert("Sorry could not create an XMLHttpRequest");
}
}
function callBack(){
if(request.readyState == 4){
if(request.status == 200){
alert(request.responseText);
}
} }
P.S: Both the html and js are in the same folder.
Please help.
In your code there's unwanted curly bracket (see like in the and of my snippet), remove it.
Second thing is why are you using connection=close, remove it if you don't really need it.
if(request){
request.open("GET",url,true);
request.onreadystatechange = callBack;
request.setRequestHeader("Connection","Close");
request.setRequestHeader("Method","GET"+url+"HTTP/1.1");
request.send();
}
else {
alert("Sorry could not create an XMLHttpRequest");
}
}
Fixed it by replacing localhost with 127.0.0.1.
Here's my problem.
1) I'm wanting to create a txt file (or possibly a html file) to hold a paragraph of information to be written onto a when a user clicks a word. It's part of a game I am working on.
If you go to www.w3schools.com and go to their "try it" editor they have...
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp = XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
p = document.createElement("p");
p.innerHTML=xmlhttp.responseText;
document.getElementById("story").appendChild(p);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="story"><h2>Let AJAX <i onclick=loadXMLDoc()>change</i> this text</h2></div>
</body>
</html>
This is exactly what I want my program to do (not the actual words of course) but I'm running html with an external .js sheet. Should I store my ajax somewhere else? Or, should my .txt file look different than just a bunch of words in it? I'm completely confused.
The fun part will be once this actually starts working, I'm going to have to implement an "onclick" event with italics inside of the txt file.
If there is a better way to do this then appendChild(p.innerHTML("lfjhdfh")) and AJAX please let me know asap. I have a total of 11 weeks to get this thing working for a school project LOL.
Try this, it just appends the text to the HTML of the body element:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange();
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
function ajax() {
getFileFromServer("Test.txt", function (text) {
if (text === null) {
// An error occurred
} else {
document.body.innerHTML += test;
}
});
}
Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created