How to stop IE from caching my XHR - javascript

<?php
if(isset($_GET['dt']))
{
echo 'a';
die();
}
?>
<div onclick="call('data_call.php?dt=a')">DATA</div>
<script>
function call(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
alert(xhr.responseText);
} else {
alert("");
}
}
};
xhr.onerror = function (e) {
alert("");
};
xhr.send(null);
}
</script>
If I run the above code in chrome (the latest version) and click the div it alerts a
If, without refreshing my window I edit the php file and change the echo 'a' to echo 'b' then save it and click the div, it alerts b.
The above is the expected behaivor. In the lastest version of internet explorer, for some reason it always alerts a.
Why please?

To prevent caching issues (typically response headers should mitigate this to a certain degree), you're better off busting the cache yourself:
function getUniqueURL(url)
{
return url + (url.indexOf('?') == -1 ? '?' : '&') + '_=' + new Date().getTime();
}
xhr.open("GET", getUniqueURL(url), true);

Related

Send PHP Variable with Ajax Call

I wrote a PHP application that makes an AJAX call (XMLHttpRequest) and is called every 5 seconds. The page called makes a database query. However, I need a variable from the main page and am unable to find a solution to attach it to the Ajax call.
Using $_GET seems a bit too insecure to me. Is there another way here?
This is my first expierence with ajax so please dont be to hard with me :)
Here is my Ajax Call
const interval = setInterval(function() {
loadText() }, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.'&name='.$_SESSION['name'].'&org='.$_SESSION['org'];?>', true);
xhr.onload = function() {
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText; }
})
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
// console.log(xhr);
}
Ill hope i provided enough Information
WIsh u all a great weekend
You do not need sending session variables at all: those are already known to the called page, because it can share the session information of the calling page.
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?= $role ?>'
is enough, provided that "table_view.php" issues a session_start() command.
I have fixed your code; It's here:
(Note: \' means that the character ' doesn't closing the string.)
const myInterval = setInterval(function(){loadText();}, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.\'&name=\'.$_SESSION[\'name\'].\'&org=\'.$_SESSION[\'org\']; ?>', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText;
}
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
}

XMLHttpRequest() returning 0

I have the following javascript which runs when an image is clicked:
function dateBack () {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("hell").innerHTML = httpRequest.responseText;
}
else {
document.getElementById("hell").innerHTML = httpRequest.readyState;
document.getElementById("hell").innerHTML = httpRequest.status;
}
};
httpRequest.open('POST', 'subtractDay.php?depDate=sal', true)
}
and the subtractDay.php which looks like this:
<?php
$depDate = $_REQUEST["depDate"];
echo $depDate;
?>
The code has been edited slightly from my original code for simplicity sake.
When I click the image, the element with id "hell" gets the value of 0 which means that the request was not initialized.
The file subtractDate.php can be accessed from the same server as the file with the javascript code. Please advise.
it missing .send()
httpRequest.open('POST', 'subtractDay.php?depDate=sal', true)
httpRequest.send(null);

onclick function not getting called

I have a dataSend AJAX function that I am calling onclick but it is not getting called.
I checked the it in the Inspector of my browser and it the click handler attached to it and yet when I put a breakpoint in the function using the Debugger, it never reaches there.
PHP/HTML Snippet (RAW)
<td onclick="dataSend('<?php echo $year;?>','12','<?php echo $rs->StudentId;?>');"><?php echo $count12[$rs->StudentId]."/248"; ?></td>
Now, this is cluttered because of the PHP, here's how it looks after being run in the browser.
After running on browser
<td class=" " onclick="dataSend('2015','02','186');">/224</td>
AJAX Snippet (Function)
function dataSend(year, month, studentid) {
parameters = 'StudentId='+studentid+'&Month='+month+'&Year='+year;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('iframe').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'attendancestu.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
FYI - This function is not inside any other function or trigger. It is not even inside $(document).ready();
I've written codes like this hundreds of times but I can't seem the figure out the problem here
You can rewrite this to another binding level which also makes the structure of your table way easier to read.
<td class="send-data" data-year="<?= $year ?>" data-month="12" data-student-id="<?= $rs->StudentId ?>"><?= $count12[$rs->StudentId]."/248"; ?></td>
<script>
$( document ).on( 'click', '.send-data', function( e ) {
//stop everything what would happen on click of td
e.stopPropagation();
e.preventDefault();
// keep track of the clicked item
_this = $( this );
studentId = _this.data( 'student-id' );
month = _this.data( 'month' );
year = _this.data( 'year' );
parameters = 'StudentId='+studentId+'&Month='+month+'&Year='+year;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('iframe').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'attendancestu.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
});
Please load JS before HTML. Means Put your js files in
Also change parameters to this:
parameters = window.location.href + '/StudentId='+studentid+'&Month='+month+'&Year='+year;
And try to run it LIVE OR localhost

Using JavaScript code for navigating (InnerHTML)

I'm using this code below for the navigation system on my site, the purpose is to open an HTML page within a div .. (InnerHTML), but, when I'm clicking one of my menu links I'm getting the JavaScript notification "Problem: " (see "else" in the JavaScript code block). This code is fixed (good) for SEO aspect.
Can someone please tell me what the problem with it is? I'm trying to preserve the code as it is as much as possible.
Thank you in advance for your help!
JavaScript code:
function processAjax(url)
{
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
}
catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
return false;
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
In HTML body:
<a onclick="return processAjax(this.href)" href="example.html">CLICK ME</a>
<div id="containerDiv"></div>
The server returned a non-200 response. If you're using a debugger like Firebug, Chrome Developer, or IE Developer, check the Network tab to see exactly where your XHR went, and what the response was.

xmlHttpRequest.send(Params) not working in tomcat 7

I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.

Categories