I have a website where I need to update a status.
Like for a flight, you are departing, cruise or landed.
I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works. I also don't want them to have and click a button.
If anybody knows how that would be done I much appreciate it!
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:
selector the existing HTML element you want to load the data into
url a string containing the URL to which the request is sent
data (optional) a plain object or string that is sent to the server with the request
complete (optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load(), where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
You can read about jQuery Ajax from official jQuery Site:
https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div.
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = function () {}; // do something here...
xhr.send();
Related
I have a PHP file on a server that needs to take dynamic values from client-side use on a web page in order to query my database. The user will click a link which (as well as directing the user to a new tab) takes the document location string that the link is connected to. I am currently trying to pass these values to the server side code using jQuery/AJAX and an XHR call, but when I run it, it seems that the PHP does not execute properly. Here is the JavaScript code:
// Clicking the link
$('a.docs').on('click', function(){
// Getting the values needed for the query from existing table
var theData = subtable.row($(this).parents('tr')).data();
// The document string
var thedoc = theData[7];
// Pass the document value to the PHP file on the server
$.post('https://example.com/TEST/dashboard/change.php', {
document: thedoc
});
// Make XHR call to execute the PHP file on the server
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/TEST/dashboard/change.php", true);
xhr.send();
});
As you can see, I try to send the value of thedoc to the file on the server before making the GET XHR call. Here is the what PHP code on the server does:
<?php
// The line that grabs the document variable being passed
$document = $_POST['document'];
// ... MySQL query stuff using $document as parameter...
?>
When I test this and click the link on the webpage, the JavaScript correctly grabs the document link variable, it's just the passing that has not been working. Any ideas on what I am doing incorrectly?
I cannot comment :(
I agree with jorgonor1.
You are performing 2 separate requests to your server.
The first. You are sending data to the server with JQUERY in the section $.POST(...). And from the sample code, ignore the results.
Then secondly, you perform a clean request of the generic page with the xhr request.
If you use $.POST(), and want to perform something with the result from the server try:
$.post('https://example.com/TEST/dashboard/change.php', {document: thedoc}, function(result){
//do something with the data returned form the server, server response stored in "result" variable
});
See the example on W3Schools
if you want to use jQuery, just try
let data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
or if you want to use xhr, you need to send the data as key/value pair string:
let data = "document=thedoc"
I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!
I have a function in python which will return one of many Image URLs. I would like to implement a button on a webpage made with django which will change the image's source to the returned value. The issue I've run into is that django template tags are only accessible when the page is rendered, as explained here. Since the real code cannot be recreated in javascript, is there a workaround to get access to the python function's return data every time the button is pressed?
Here is some code to clarify my question:
class Foo(models.Model):
def get_image_url():
if(random.randint(0,1)):
return 'http://img1.jpg'
else:
return 'http://img2.jpg'
This is how I would want it to behave in javascript, if it were possible.
function updateImage(){
document.getElementById("testImage").src="{{ foo.get_image_url }}";
}
Thanks.
Sounds like you have to use AJAX for this. You can define a Django view which returns a JSON message with something like:
{
status: "ok",
url: "img1.jpg"
}
So in your code, you can define an event handler (in JavaScript) with something like this:
// Attach a listener to a button for a click event,
document.getElementById("testImageButton").addEventListener("click", function() {
var xhr = new XMLHttpRequest();
// This URL returns the above JSON.
xhr.open("GET", "/images/random");
xhr.onloadend = function() {
// Should have error handling in case response does not return correctly.
var imageResult = JSON.parse(xhr.response);
if(imageResult['status'] == 'ok') {
// update the image src
document.getElementById("testImage").setAttribute("src", imageResult['url']);
}
}
xhr.send()
})
So the only "dynamic function part" is whatever is inside your Django view function.
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
I'm pretty new to javascript and am working on an embedded system which decodes video over IP.
I have written a small app for setting up and changing channels using javascript and included a key handler for remote controls and an event handler so I can take some action or present a message if video stops or the network goes down, but now I also want to set up an automatic HTTP POST that gets sent when I change channel to include some data about the device and the url currently being played.
This is a small embedded hardware device running busybox, so I can't use Ajax or add any other normal web technologies, I just need to use Javascript to send a HTTP POST triggered by events I am monitoring, so my first goal is to be able to press a button and send that POST message then work out when to trigger it later.
Anyone familiar with doing such things that can give me a quick overview of how to send a post to a known listening device/location and include data in it?
Many thanks
This is easy if your Javascript engine supports XMLHttpRequest (XHR), which is ubiquitous on the web. Google it or see this page for details. I've provided a code snippet below. Read it carefully, particularly the comments on "async" being true and closures in response handlers. Also, this code is super lightweight as far as Javascript goes and I would expect it would work fine on just about any contemporary hardware footprint.
var url = "http://www.google.com/";
var method = "POST";
var postData = "Some data";
// You REALLY want shouldBeAsync = true.
// Otherwise, it'll block ALL execution waiting for server response.
var shouldBeAsync = true;
var request = new XMLHttpRequest();
// Before we send anything, we first have to say what we will do when the
// server responds. This seems backwards (say how we'll respond before we send
// the request? huh?), but that's how Javascript works.
// This function attached to the XMLHttpRequest "onload" property specifies how
// the HTTP response will be handled.
request.onload = function () {
// Because of javascript's fabulous closure concept, the XMLHttpRequest "request"
// object declared above is available in this function even though this function
// executes long after the request is sent and long after this function is
// instantiated. This fact is CRUCIAL to the workings of XHR in ordinary
// applications.
// You can get all kinds of information about the HTTP response.
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an HTML document.
}
request.open(method, url, shouldBeAsync);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// Or... request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
// Or... whatever
// Actually sends the request to the server.
request.send(postData);