I am new to JavaScript. What I want to do is sending an ajax request and get the content of a JSON file and simply put it into a div. This is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
<script>
document.getElementById("button").addEventListener('click', loadText);
function loadText(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('text').innerHTML = this.responseText;
}
else if (this.status == 404){
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
</script>
</body>
</html>
And this is users.json:
[
{
"id":1,
"name":"Rick",
"email":"rick#gmail.com"
},
{
"id":2,
"name":"Negan",
"email":"negan#gmail.com"
}
]
This works fine. But, when I manually updated users.json and change it and refresh the browser, the browser does not show the updated json. It still gives me the previous json file. How can I fix it?
It is possible that the browser is responding with a cached response.
Try appending 'timestamp' so that every time a new request would be made to the server to get updated contents.
document.getElementById("button").addEventListener('click', loadText);
function loadText() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json?ts=' + Date.now(), true);
xhr.onload = function() {
if (this.status == 200) {
document.getElementById('text').innerHTML = this.responseText;
} else if (this.status == 404) {
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
As you have included jQuery in your webpage, I would recommend to use jQuery version of ajax. To disallow the use of the cached results, set cache to false.
$.ajax({
url: 'myurl',
type: 'GET',
dataType: 'json',
data: jsonDataObject,
cache: false, // Appends _={timestamp} to the request query string
success: function(data) {
// data is a json object.
}
});
try check the disable cache checkbox on network panel of the dev tool.
it might be caused by the cache of your web server
You need to pass header
content_type="application/json"
Related
I have a button similar to:
<button onclick="window.location='http://www.example.com';">Visit Page Now</button>
I would like the click of the button to send a request to the endpoint but not open a new window or new tab. Is this possible?
You can use JavaScript to make the request. You'd have to change your markup a bit
<button onclick="hitEndpoint('http://www.example.com')">Visit Page Now</button>
Then later on in the script section of your page you could write something like:
function hitEndpoint(url){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
//we're done making the request
if(this.readyState === 4) {
//status code was successful
if(this.status === 200) {
console.log("hit endpoint successfully")
} else {
console.log("error hitting endpoint");
}
}
};
xhttp.open("GET", url);
xhttp.send();
}
You can use jquery ajax method to send request without loading the whole page
$.ajax({
url:'sendrequest.php',
type:'post',
data:{id:id},
datatype:'json',
success:function(data){
}
)};
I am puzzled as to why PHP sees my request string as undefined.
$_GET['ask'] in my php file
produces this error -> Notice: Undefined index: ask.
But when I query the php file from the url bar in the browser like this
localhost/Websites/webProject/data.php?ask=myquery
I have set the php file to echo my string and it does do exactly that but only when I query it from the browser URL bar.
But when running the AJAX code normally from the parent html/php file
request.open("GET", "data.php?ask=myquery", true);
The PHP file does not see the query string and thinks its undefined.
Why is this the case?
I have tried to use
$_REQUEST[]; but to no avail.
I am using pure javascript for the AJAX requests.
Here is the javascript
requestResponse();
function requestResponse()
{
var READY_STATE_DONE = 4; /* request finished and response is ready */
var SUCCESS = 200; /* "OK" */
setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(this.readyState == READY_STATE_DONE && this.status == SUCCESS)
{
var response = this.responseText;
console.log(request.responseText);
document.getElementById("test").innerHTML += "<br>" + response;
}
}
request.open("GET", "data.php?ask=myquery", true);
request.send();
}, 3000)
}
Here is the PHP content
testRequest();
function testRequest()
{
$reqString = $_REQUEST['ask'];
include("dbCredentials.php");
include("dbConnect.php");
if($reqString == "myquery")
{
echo("<br />REQUEST IS: " . $reqString);
echo("<br /> Your request is granted");
}
}
DISCLOSURE: I have replaced the previous php file with data.php.
Try using Jquery Ajax request. this is mostly effective when you want to pass strings instead of serialized data
HTML:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.ajax({
type: 'post',
url: 'data.php?ask=whut',
success: function(response){
alert(response);
}
});
});
</script>
PHP Content:
echo $_GET['ask'];
I have a data.json in my server directory. I am using the following code from w3school to show the data in the browser. W3school Snippet Link
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "/static/data.json", true);
xhttp.send();
}
</script>
</html>
When i click the button, I am able to see the data.json in my webpage. But when i change the data.json and click the button again (without refreshing the page), the updated data isn't shown in the browser.
Am i missing something here?
Well since you are using XMLHttpRequest, you need to make sure that every request is kind of unique, you can do something like:
var uniqueId = (new Date()).getTime()
xhttp.open("GET", "/static/data.json?debug=" + uniqueId, true);
If you were using jQuery ajax (http://api.jquery.com/jquery.ajax/), you just have to pass cache=false, like this:
$.ajax({
cache: false,
//other options...
});
xhttp.open("GET", "/static/data.json?something=RANDOMGUID", true);
I want to autoupdate page using PHP and Ajax. Right now I have this code on a page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<i class="fa fa-heart-o"></i>
</body>
</html>
When the user clicks on the link it is redirected to another page called "Page-Like.php"
include("config.php");
//get vars
$idSubliminal=$_GET["idSubliminal"];
$idCategoria=$_GET["idCategoria"];
// mysql_query("insert into Rating .... (mysql insert query)
echo "<script>
location.href=\"AudioSubliminal.php?idSubliminal=$idSubliminal&idCategoria=$idCategoria\";
</script>";
What I want is to do this usig Ajax in order to not refresh the page. I know I'm missing the javascript code, but I would like to get some suggestions to complete this script.
Thanks!
All you need is a basic ajax request to achieve your functionality. check the sample request below.
function ajaxpr(){
var URLString="idSub=12&idCat=32";
ajax_request = $.ajax({
type: 'GET',
url: "Page-Like.php",
data: URLString,
dataType : 'html',
context: $(this),
success: function (msg)
{
//perform the required operation after success
});
}
add function onclick on tag . then define that function using :
$.ajax({
type: 'GET',
data: {idSub: "12", idCat: "32"},
url: "Page-Like.php",
dataType: 'JSON',
success: function (response, textStatus, jqXHR) {
//DEFINE FUNCTION HERE
}
});
This is using ajax function without refresh page.
You can use many methods to implement Ajax on you're code.
One of this is jQuery, other is mootools, etc.. Depends of wich library you know or want to learn.
Using ajax to load a page is easy. Follow this link http://www.w3schools.com/ajax/
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "Page-Like.php?idSub=12&idCat=32", true);
xhttp.send();
}
Now it's just a matter of putting event listener to run loadDoc() function. If the link is dynamic, you can parse the parameter to the function.
However, I notice you have a js script inside your php which will redirect again to AudioSubliminal.php. If this is your desired flow then it's okay. If not, you can create another function
function loadAudioSubliminal(idSub, idCat) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "AudioSubliminal.php?idSubliminal=" + idSub + "&idCategoria=" + idCat, true);
xhttp.send();
}
and modified loadDoc() to receive a parameter such that idSub and idCat can be passed again. for Example :
function loadDoc(idSub, idCat) {
var xhttp = new XMLHttpRequest();
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
// run the function after finished loading Page-like.php
loadAudioSubliminal(idSub, idCat)
}
xhttp.open("GET", "Page-Like.php?idSub=" + idSub + "&idCat=" + idCat, true);
xhttp.send();
}
Is it possible to call a text file similarily to how you would reference an image in a image tag? Similar to
<img src="http://link.to/image.png">
but
<p src="http://link.to/text.txt"></p>
?
Can you do this with javascript? Any advice would be super appreciated!
You can do this with XHR (XMLHttpRequest) . Pure Javascript:
<p id="text"></p>
<script>
text = document.getElementById('text');
xhr = new XMLHttpRequest();
xhr.open("GET", "http://link.to/file.txt");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) //the readyState if the status of the request
text.innerHTML = xhr.responseText; // (http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp)
// 4 is a completed request
}
</script>
Or, jQuery has the .load() function:
<p id="text"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#text').load('http://link.to/file.txt');
</script>
You can load the remote content via AJAX, as long as the remote server sends you proper CORS headers.
Something like this should work:
var $p = document.getElementsByTagName('p')[0];
var url = $p.getAttribute('src');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function insertContents() {
if (xhr.readyState === 4 && xhr.status === 200) {
$p.innerHTML = xhr.responseText;
}
};
xhr.open('GET', url);
xhr.send();
possible with ajax
<p data-src="http://link.to/text.txt"></p>
JS:
$('p').each(function () {
var $this = $(this);
$.ajax({
url: $this.data('src'),
dataType: "text",
success: function (data) {
$this.html(data);
}
});
});
var client = new XMLHttpRequest();
client.open('GET', 'text.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
You can display text file using IFrame. Like this-