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 codeigniter website which is done 1 year ago. No, I want to implement new HTML5 history API (pushstate) function to enable change content based on the url without header refresh. Is there any simple way, to avoid url restructure and load whole content using new HTML5 history API? I was trying to find some way, but most of them are using get methods.
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.replaceState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
Here is demo for this : http://sandbox.cergis.com/html5-historyAPI/page1.php
I want to implement new HTML5 history API (pushstate) function to enable change content based on the url without header refresh.
pushState is there to allow you to change the url without loading a new page.
Is there any simple way, to avoid url restructure and load whole content using new HTML5 history API?
Changing the content is the job of DOM.
You can use XMLHttpRequest (or other Ajax techniques) to load new content from the server (and then insert that into the page using DOM manipulation)
Generally, you should use the history API in combination with DOM manipulation. You change the content of the page with DOM, then change the URL to one that the server can use to generate the same page from scratch. This means the page still works for users (including search engines) without JavaScript, and it avoids the homepage loading before being replaced (after a few seconds) with different content.
I've got a div that randomly shows 1 of 10 files on each pageload. I'd like this to reload on a set time interval of 8 seconds, giving me a different one of the 10 files each reload.
I've read a few of the related questions using jQuery .load as a solution but this doesn't quite work with my code since I'm not loading a specific file each time.
This is my div content:
<div id="tall-content">
<?
$random = rand(1,10);
include 'tall-files/' . $random . '.php';
?>
</div>
Thanks
Using only PHP to accomplish this is impractical. This example uses jQuery and PHP.
$(document).ready(function() {
$("#div").load("random.php");
var refreshId = setInterval(function() {
$("#div").load('random.php');
}, 8000);
$.ajaxSetup({ cache: false });
});
random.php
$pages = array("page1.php", "page2.php", "page3.php", "page4.php", "page5.php");
$randompage = $pages[mt_rand(0, count($pages) -1)];
include ($randompage);
while using PHP to generate the random content, you cannot get the div to reload that content without refreshing the entire page.
A better solution is to use AJAX. You can store that PHP code that's inside the div container as a seperate file, and use ajax to request that php file. You can also set an infinite loop to request the php file every 8 seconds. Here is a sample, but you will need to re-code it to your specification:
<script language="javascript" type="text/javascript">
<!--
function ajaxFunction(){
var ajaxRequest;
try{ajaxRequest = new XMLHttpRequest();} catch (e){try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Browser/Settings conflict");return false;}}}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('tall-content').innerHTML = ajaxRequest.responseText;
}
}
var url = "random.php";
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
//-->
</script>
The only missing part is the refresh timer, since I do not program a lot in javascript I can't help you there. But the goal in this case is to create a file "random.php", put the random generator there, and use this script above to make an ajax request to random.php, which will place the output of that php script in the div container with the id of "tall-content". So really, you need to create another javascript which loops indefinitely calling the function "ajaxFunction()" and wait 8000 milliseconds .
If you want to do this while the user is sitting back in the chair on your page, the answer is javascript.
You could use this function for example.
function recrusive_timeout_function() {
setTimeout(function() {
recrusive_timeout_function();
}, 8000);
}
If you want to include a php file in that div (which outputs some html). Ajax is your friend and JQuery as a user friendly and easy to use javascript framework which handles your thinks really nice.
I want to load a dynamic content to specific div name with multiple querystring from a menu.
Example dynamic menu link
index.php?tag=2
index.php?category=1&tag=2
index.php?category=2&tag=2&location=3
Example query process in PHP for link index.php?category=1&tag=2
$tag = intval($_GET['tag']);
$cat = intval($_GET['category']);
if(isset($tag) && isset($cat)) {
$select = $db->query("SELECT * FROM table WHERE cat=".$cat." AND tag=".$tag."");
... // fetch results
}
Question - With jQuery how to tell user clicked the link then send the callback to PHP process & show the results in the specific div name without refresh the page.
Let me know
Description
You have to create another php page that returns data in json format for the given substring. Your substring is dynamic so you have to get the substring from another element. I suggest a <input type="hidden" value="YourQueryString"/>, its simple. You can put the element next to your link and get the value using jQuery.val().
Then you use jQuery.ajax() / jQuery.get() or jQuery.post() in your index.php to get the data from that page / script. (jQuery.get() and jQuery.post() uses jQuery.ajax() internally)
In the callback method of jQuery ajax you grab the data and build the html from it.
After that you can use jQuery.html() to set the data to your div.
Sample
html / php
<a class="AnyClassName">Click me</a>
<input type="hidden" value="category=1&tag=2"/>
jQuery
$(".AnyClassName").click(function() {
// lets get the query string
var queryString = $(this).next().val();
$.ajax({
url: "yourNewPage.php?" + queryString,
context: document.body,
success: function(data){
var generatedHtml = "..." // build your html from the data object
$("#IdOfYourDiv").html(generatedHtml);
}
});
});
Update
Alternatively your php page can return html (simple page) for your query string. This is easier than build html in the jQuery Ajax Callback. If this is done you can do this
$(".AnyClassName").click(function() {
// lets get the query string
var queryString = $(this).next().val();
$('#IdOfYourDiv').load("yourNewPage.php?" + queryString);
});
More Information
Documentation
jQuery.ajax()
jQuery.post()
jQuery.get()
jQuery.load()
jQuery.html()
jQuery.val()
jQuery.next()
Tutorials
jQuery, Ajax, Json and Php
Use jQuery and PHP to build an Ajax-driven Web page
Use one of jQueries many AJAX functions, for instance:
$.post("ajax.php", "category=1&tag=2",
function(data) {
alert("Data Loaded: " + data);
});
Check:
http://api.jquery.com/jQuery.post/
Your PHP script should return the HTML you want to load into the div; the JS looks like this:
$('#your_menu').on('click', 'a', function(e) {
var $this = $(this),
url = $this.href;
$.ajax({
url: url,
success: function(html) {
$('#div_to_update').html(html);
}
});
});
It gets the URL from the link you clicked in the menu, passes the URL to the Ajax call, and fills the target div with the HTML response. See here for more info on this topic.
You can use jQuery.load() for this (Javascript - client side):
$('#id_of_the_div').load('index.php?category=1&tag=2');
Check out the http://api.jquery.com/load/ for more.
I'm having a problem..
Actually I do have an issue when sending a value from a child page to the parent page.
I'm actually loading a page via JQuery and that page is getting refreshed to display new results, but one of these problems is that the function from the parent page doesn't get called from the child page.
Although this works perfect on Google Chrome, Opera and Safari, it doesn't seem to work on Firefox.
I heard Firefox doesn't manage events the same way as Safari or Google Chrome does?
I've been searching on answers for this but I couldn't find anything pretty much..
Alright, here's what I'm doing:
The child page calls another file which has all the functions that make my site work, this is what should trigger the function:
$like = "<a href='$comment_poster' id='$msgid' class='like'
onclick='parent.likecomment(this);'>Like</a>";
echo "$like";
And this is the function that gets fired from the onclick event which is located in the parent page (the function is in the parent page the onclick is in the child page):
This function is the one that receives the id from the child page to later on add the value to the database.
function likecomment(commentID)
{
event.preventDefault();
var likeid = commentID.id;
var author = ($(commentID).attr('href'));
// forming the queryString
var data = 'likeid='+ likeid + '&author=' + author;
if(likeid)
{
// ajax call
$.ajax({
type: "POST",
url: "likeprofmessage.php",
data: data,
beforeSend: function(html)
{
$(".word").html(likeid);
},
success: function(html){
$("#resultsprofcomments").fadeIn('slow');
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $row['1'];?>').fadeIn("slow");
$("#resultsprofcomments").append(html);
}
});
}
}
I've tried the Firefox console and I've received the error: event is undefined so this should be a problem on how Firefox manages events.
Again, any help is appreciated, thank you very much.
I think the following will work as long as you set the onclick handler inline in your HTML (as you did in your example):
<A href="..." onclick='parent.likecomment(event,this);'>blah</A>
<SCRIPT>
function likecomment(evt, commentID) {
evt.preventDefault();
var likeid = commentID.id;
// etc
}
</SCRIPT>
For event handlers not set inline in HTML, the standards compliant browsers (including FF) should automatically pass the event object as a parameter to your handler function. IE, up to version 8, anyway, uses a different event model and lets you reference event directly - really it is window.event but generally as with most window properties it works even if you omit window..
So if you assign your click handler on document ready (or onload) you can do this:
function yourOnloadFunction() {
document.getElementById('yourElementId').onclick = clickHandler;
}
function clickHandler(e) {
// check if event object was passed in, otherwise use window.event
if (!e) e = window.event;
// but how to get a reference to the clicked element?
// use the event object's target property, except (of course)
// in IE, which uses srcElement:
var elRef = e.srcElement ? e.srcElement : e.target;
// rest of your function here, e.g.
e.preventDefault();
}
You have managed to make a mess of your code, but try to change
onclick='parent.likecomment(this);'
to
onclick='parent.likecomment(this);return false;'
and then remove
event.preventDefault();
from your function likecomment(commentID).
Instead of using the in-line onClick, have you tried sending back a script that does something like
<Script>$('#{id}').click(function() {
var id = this.id;
likecomment(id);
return false;
})</Script>
Is it possible to get an element id into a PHP variable?
Let's say I have a number of element with IDs:
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
});
});
</script>
I need to pass $(this).attr('id') into $newID in order to run
SELECT * from t1 WHERE id = $newID
jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.
Thanks.
This is like your question: ajax post with jQuery
If you want this all in one file (posting to active file) here is what you would need in general:
<?php
// Place this at the top of your file
if (isset($_POST['id'])) {
$newID = $_POST['id']; // You need to sanitize this before using in a query
// Perform some db queries, etc here
// Format a desired response (text, html, etc)
$response = 'Format a response here';
// This will return your formatted response to the $.post() call in jQuery
return print_r($response);
}
?>
<script type='text/javascript'>
$(document).ready(function() {
$('.myElement').click(function() {
$.post(location.href, { id: $(this).attr('id') }, function(response) {
// Inserts your chosen response into the page in 'response-content' DIV
$('#response-content').html(response); // Can also use .text(), .append(), etc
});
});
});
</script>
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
<div id='response-content'></div>
From here you can customize the queries and response and what you would like to do with the response.
You have two "good" choices in my mind.
The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.
In this even callback, you'd initiate the $.post as you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).
The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Plugin to handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.
In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):
var order = [];
$('span.myElement').each(function(){
// N.B., "this" here is a DOM element, not a jQuery container
order.push(this.id);
});
return order.join(',');
You're quite right, something along those lines would work. Here's an example:
(btw, using $.post or $.get doesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post(document.location, { id: $(this).attr("id") },
function (data) {
// say data will be some new HTML the server sends our way
// update some component on the page with contents representing the element with that new id
$('div#someContentSpace').html(data);
});
});
});
</script>
Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location (I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.
If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.
$.post(window.location, {id: this.id}, function (data) {
//one
location.reload();
//two
$("#responsedata").html(data);
//three
$("#responsedata").load("affected_page.php #output");
});
I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in data above for jQuery to handle however you wish.
By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.