I have a div called totalvalue.
<div id="totalvalue"></div>
I wrote a function to get value from my PHP script (on the same server).
function totalvalue() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
totalvalue = (ajax5.responseText);
console.log(totalvalue);
document.getElementById("totalvalue").innerHTML = ajax5.responseText;
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
The php script does output a value.
Neither my console nor the div display the output.
This worked for me.
function test5() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
xxx5 = (ajax5.responseText);
console.log("this is the total value: "+xxx5);
if (xxx5 == 0) {
document.getElementById("totalvalue").innerHTML="Loading...";
} else {
document.getElementById("totalvalue").innerHTML="Total: "+xxx5;
}
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
I presume that where I write the div matter + there could have been an issue with the cache. I cannot tell for sure why the above just started working.
For simpler code, and better cross browser support, i would use jQuery.ajax like so:
$.ajax({
url: 'totalvalue.php',
success: function(data){
$('#totalvalue').html(data);
}
});
Read more about it in the documentation
Related
Good evening guys,
I program a symfony website by using webpack encore bundle to manage js & css.
I used to work with jquery which is quite simple, but would like to evolve to pure javascript.
I try to translate the following code in javascript :
<html>
<button class="exercice-class" data-id="x">exercice button</button>
</html>
when an user click on the "exercice button", i want to get the value of data-id to generate an URL
<script>
$(function() {
$('.exercice-class').on("click", function(e) {
e.preventDefault();
let id = $(this).data("id");
let url = "../exercice-class/" + id + "/";
$.get(url, function(data){
$(".container-fluid").append(data);
$('#showModal').modal('show');
});
});
});
</script>
Then i get the content of the URL and add it to the modal window
What I want to do first is to open a modal window by using a variable as a parameter.
Second question, I would like to get data from a modal (using a form) and send them to a database. I read things about asynchronous request by it's not really clear for me, i'm looking for something close to ajax request.
Thank you in advance.!
Juuk
here is a small example, you can test it
var classbutton = document.querySelector('.exercice-class');
classbutton.addEventListener('click', (e) => {
e.preventDefault();
let id = element.getAttribute('id');
let url = "../exercice-class/" + id + "/";
let requete = new XMLHttpRequest();
requete.open('GET', url);
requete.send();
requete.onload = function() {
if (requete.readyState === XMLHttpRequest.DONE) {
if (requete.status === 200) {
let reponse = requete.response;
document.querySelector('.container-fluid').append(reponse);
document.querySelector('#showModal').showModal();
}
else {
}
}
}
});
Thanks for your response! i tried your code and work on it...
This is what i did :
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.send();
httpRequest.onload = function (){
if (httpRequest.readyState === XMLHttpRequest.DONE){
if (httpRequest.status === 200){
let httpResponse = httpRequest.response;
console.log(httpResponse);
}
}
}
It seems that fetch is a newer way to work with data since vanilla.
I did the same thing we tried to do before and i succeeded to get data.
document.addEventListener('click', function (event) {
if (!event.target.closest('.exercice-class')){
return null;
}
else {
event.preventDefault();
let exercice = event.target.closest(".exercice-class");
let dataAttribute = exercice.getAttribute('data-id');
let url = "../exercice-class/" + dataAttribute + "/";
fetch(url)
.then(function (response) {
return response.text();
})
.then(function (data) {
console.log(data)
})
.catch(function (error) {
console.log(error);
});
}
});
In reality i get the same result with the two solutions.. the problem is that i get "data" i can't exploit...
Imagine i use the second example :
if i try to do :
.then(function (data) {
let exerciceData = data.getElementById("#adiv");
document.querySelector('container-fluid').append(exerciceData);
document.querySelector('showModal').show();
"exerciceData" can't be used.
Modal just don't open.
Thank for your help.
I would like to test if the ajax request is identical so it can be aborted or some other alert action taken?
In reality clients can change the request via a few form elements then hit the refresh button.
I have made a poor attempt at catching the identical request. Need to keep the timer refresh functionality.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var current_request_id = 0;
var currentRequest = null;
var lastSuccessfulRequest = null;
function refreshTable() {
$('#select').html('Loading');
window.clearTimeout(timer);
//MY CATCH FOR DUPLICATE REQUEST NEEDS WORK
if (lastSuccessfulRequest == currentRequest)
{
//currentRequest.abort();
alert('Duplicate query submitted. Please update query before resubmission.');
}
var data = {
"hide_blanks": $("#hide_blanks").prop('checked'),
"hide_disabled": $("#hide_disabled").prop('checked'),
};
json_data = JSON.stringify(data);
current_request_id++;
currentRequest = $.ajax({
url: "/calendar_table",
method: "POST",
data: {'data': json_data},
request_id: current_request_id,
beforeSend : function(){
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(response) {
if (this.request_id == current_request_id) {
$("#job_table").html(response);
$("#error_panel").hide();
setFixedTableHeader();
}
},
error: function(xhr) {
if (this.request_id == current_request_id) {
$("#error_panel").show().html("Error " + xhr.status + ": " + xhr.statusText + "<br/>" + xhr.responseText.replace(/(?:\r\n|\r|\n)/g, "<br/>"));
}
},
complete: function(response) {
if (this.request_id == current_request_id) {
$("#select").html("Refresh");
window.clearTimeout(timer);
stopRefreshTable();
window.refreshTableTimer = window.setTimeout(refreshTable, 10000);
lastSuccessfulRequest = currentRequest;
}
}
});
}
//TIMER STUFF TO refreshTable()
//THIS SECTION WORKS FINE
var startDate = new Date();
var endDate = new Date();
var timer = new Date();
function startRefreshTable() {
if(!window.refreshTableTimer) {
window.refreshTableTimer = window.setTimeout(refreshTable, 0);
}
}
function stopRefreshTable() {
if(window.refreshTableTimer) {
self.clearTimeout(window.refreshTableTimer);
}
window.refreshTableTimer = null;
}
function resetActive(){
clearTimeout(activityTimeout);
activityTimeout = setTimeout(inActive, 300000);
startRefreshTable();
}
function inActive(){
stopRefreshTable();
}
var activityTimeout = setTimeout(inActive, 300000);
$(document).bind('mousemove click keypress', function(){resetActive()});
</script>
<input type="checkbox" name="hide_disabled" id="hide_disabled" onchange="refreshTable()">Hide disabled task<br>
<br><br>
<button id="select" type="button" onclick="refreshTable();">Refresh</button>
I'd use the power of .ajaxSend and .ajaxSuccess global handlers.
We'll use ajaxSuccess to store a cache and ajaxSend will try to read it first, if it succeeds it will trigger the success handler of the request immediately, and abort the request that is about to be done. Else it will let it be...
var ajax_cache = {};
function cache_key(settings){
//Produce a unique key from settings object;
return settings.url+'///'+JSON.encode(settings.data);
}
$(document).ajaxSuccess(function(event,xhr,settings,data){
ajax_cache[cache_key(settings)] = {data:data};
// Store other useful properties like current timestamp to be able to prune old cache maybe?
});
$(document.ajaxSend(function(event,xhr,settings){
if(ajax_cache[cache_key(settings)]){
//Add checks for cache age maybe?
//Add check for nocache setting to be able to override it?
xhr.abort();
settings.success(ajax_cache[cache_key(settings)].data);
}
});
What I've demonstrated here is a very naïve but functional approach to your problem. This has the benefit to make this work for every ajax calls you may have, without having to change them. You'd need to build up on this to consider failures, and to make sure that the abortion of the request from a cache hit is not getting dispatched to abort handlers.
One valid option here is to JSON.Stringify() the objects and compare the strings. If the objects are identical the resulting serialised strings should be identical.
There may be edge cases causing slight differences if you use an already JSONified string directly from the response so you'll have to double check by testing.
Additionally, if you're trying to figure out how to persist it across page loads use localStorage.setItem("lastSuccessfulRequest", lastSuccessfulRequest) and localStorage.getItem("lastSuccessfulRequest"). (If not, let me know and I'll remove this.)
Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps
I have created the following JavaScript function to load images of a vehicle, or load the alternate image if it is not available. The problem is that this page is 1kb, meanwhile it has to load the entire jquery library at 85+kb just for this one function. So my question is, is there some way to accomplish the same without having to load the jQuery library?
function GetImages() {
var Query = location.search;
//If query exists
if ((Query != "") && (Query != "?")){
var chunks = Query.split("=");
//If passed the right parameter
if (chunks[0] == "?unit") {
var Unit = chunks[1];
for (var i=1; i<11; i++) {
var unitimageURL = "/pics/"+Unit+"-"+i+".png";
$.ajax({
type: 'HEAD',
url: unitimageURL,
async: false,
success: function() {
$('.pictures').append("<img src="+unitimageURL+" width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
},
error: function() {
$('.pictures').append("<img src=nopic2.png width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
}
});
}
}
}
else {
alert("No query");
}
}
Yes, there is a way - the good old var oRequest = new XMLHttpRequest(); way!
Don't forget to to set all the needed callbacks, check response statuses and everything will be fine.
To create a HEAD request, just specify "HEAD" as parameter to .open() method.
You will also need document.createElement() to append the results to your page (or you may use .innerHTML property as well.
Also, documentation like this http://www.tutorialspoint.com/ajax/what_is_xmlhttprequest.htm may be handy.
function saveMe() {
var strValues = "";
var boxLength = document.choiceForm.choiceBox.length;
var count = 0;
if (boxLength != 0) {
for (i = 0; i < boxLength; i++) {
if (count == 0) {
strValues = document.choiceForm.choiceBox.options[i].value;
}
else {
strValues = strValues + "," + document.choiceForm.choiceBox.options[i].value;
}
count++;
}
}
if (strValues.length == 0) {
alert("You have not made any selections");
}
else {
$.post("rolGridPermition.php", {
rolId: strValues
});
}
}
in this code $.post function between else paranthesis does not work... is there any problem? can anyone help me?
Use the url properly,
$.post("http://yourdomain/rolGridPermition.php", {rolId: strValues }, function(data) {
// code here
});
Failed to load resource: the server responded with a status of 404 (Not Found) means the php file is not in the server or url is not correct.
If you have jQuery included in your script, this should work.
$.post("rolGridPermition.php", { rolId: strValues},function(result){
alert(result);
});
Keep in mind that you can not make a call to a page in a different domain because of the cross domain policy. Still you can do some hacks to get it done ( using jspnp as datatype)