Strange ajax issue with IE - javascript

I've come across an IE issue I can't find an explanation to. I have this code that fires an alert in Chrome and Firefox but it doesn't in IE. I don't even call GetDictBySubtitle().
<?php
header('Content-type: text/html; charset=UTF-8');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Something</title>
<link rel="stylesheet" href="../css/bootstrap.css" type="text/css">
<link href="../css/dashboard.css" rel="stylesheet"/>
<script>
function GetDictBySubtitle() {
var userid = "000000000027";
var subid = "6317450";
postData = {"userid":userid, "subtitleid":subid};
$.ajax({
url: "/cgi-bin/get_movie_dictionary.py",
type: "post",
datatype:"json",
async : true,
data: {postData},
success: function(response){
alert(response);
}
});
}
function GetAccountData() {
var userid = "000000000027";
alert(userid);
}
</script>
</head>
<body>
<script>
window.onload = function() {
GetAccountData();
}
</script>
AN ALERT SHOULD BE DISPLAYED
</body>
<script src="../js/jquery.js"></script>
<script src="../js/jquery-ui.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/light-bootstrap-dashboard.js"></script>
</html>
I also added cache: false to the request, but it's not a caching issue, because I deleted everything from IE, restarted it, and the alert is still lurking somewhere in the dark.
Note: While debugging the page in IE, I get GetAccountData() is undefined error in the window.onload block.
I'm using IE 10, Chrome 50, Firefox 45.
It's so great that I can always count on Microsoft if I have time to kill.

Change
data: {postData},
to
data: postData,
And test again.
Why?
Because postData is an object.
{postData} is incorrect. In this case Internet Explorer has detected the error and blocks the execution.

Related

Why does httpr.send() always fail?

I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}

txt file wont load by using vanilla javascript

I am trying to implement an ajax with simple txt file but the file won't load any suggestion
the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
xhr.send();
}
}
and this is the sample.txt file
This massage form the text file just to ensure you have the ability to
access the text file. so if you do good for you otherwise just keep
trying
Note, I'm trying to achieve it using vanilla javascript without any frameworks or library
As an output I get nothing once I click the button and even in the network tab in the inspector the txt file never even load.
Note, I'm using live sever on vscode
xhr.send() should be outside xhr.onload()
xhr.onload() is the callback function to be executed when the request completes successfully.
refer the docs here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
}
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>

HTML file as the response to a POST request?

I have seen questions and answers regarding this issue. For example How to return a HTML file as the response to a POST request? but am having problems implementing the solutions. Here is a sample of some php code in a directory called websiteIssue that does not work, and I am not sure why.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
$page = "";
}
include 'case.php';
?>
case.php
<?php
$testLog = 'testLog.txt';
$fileHandle = fopen('testLog.txt', 'a');
fwrite($fileHandle, '$page = '.$page."\n";
switch($page)
{
case "screen2":
include 'screen2.php';
fwrite($fileHandle, 'including screen2.php'."\n");
break;
default:
include 'screen1.php';
fwrite($fileHandle, 'including screen1.php'."\n");
break;
}
fclose($fileHandle);
?>
screen1.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen1.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen2</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen2.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen2.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen1"})> Screen 2 => Screen1</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
On initial load it works as I expected, the html in screen1.php is shown in the browser, but when the button on the page is pressed the html remains the same, rather than changing to that in screen2.php
The output to testText.log is something like:
$page =
including screen1.php
$page = screen2
including screen2.php
As is might be obvious, I am a newbie to this, and hopefully there is some basic thing I have not done. The browser I am running it on is Firefox. Any help would be much appreciated.
Small note:I retyped the code by hand for this post, and have not run it (the machine running the webserver is not connected to the internet), hopefully there are no syntax errors, but I may have made a typo somewhere.
By including the php file you are responding to the javascript, but you arent actually using that response for anything. If redirecting to that page is what you want, you need to use location.assign on the response. To do that:
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
// Redirects user to response when received.
xmlRequest.onreadystatechange=function{
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
location.assign(xmlRequest.responseText);
}
};
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
Based on the answer given by Felipe Souza I made the following modifications to allow the page to be dynamically modified rather than being a redirect. Thought I would share as it is another solution which some might be interested in.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
include 'case.php';
}
else
{
include 'base.php';
}
?>
case.php
<?php
switch($page)
{
case "screen2":
include('screen2.php');
break;
case "screen1":
include('screen1.php');
break;
default:
include('screen1.php');
break;
}
?>
base.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>base.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<div id="container" style="width:100%; height:100%">
<?php
if(!isset($_POST['page']))
{
$page = "";
include 'case.php';
}
?>
</div>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData = new FormData();
xmlRequest.onreadystatechange=function()
{
if(xmlRequest.readyState==4 && xmlRequest.status==200)
{
document.getElementById("container").innerHTML = xmlRequest.responseText;
}
}
for(name in data)
{
formData.append(name, data[name]);
console.log(name + ":" + data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen1.php
<button type"button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen 2</button>
screen2.php
<button type"button" onClick=dataSubmit({page:"screen1"})>Screen 2 => Screen 1</button>
There seem some potential advantages in that the amount of data sent for the new screens is smaller, and (not sure if it is useful) the structure of the website is more disguised. Anyway, it is based on the answer given by Felipe Souza and supplements it (shows a dynamic approach rather than a changing pages one). Just thought I would mention it, if that was what some were looking for.

Ajax - Return html page - on load function of that page not executing

I have one ajax call which return entire html page.
Now that html page have one function which execute on page load event.
But when i am calling it via ajax it is not executing but when I call it via browser it is executing.
For example ,
In browser www.abc.com/test/test1 (Load jquery function on load)
In ajax call www.abc.com/test/test1 (Not load jquery function)
I want to execute that function via ajax call.
Ajax call
function test(str)
{
var $ajaxJQuery = jQuery.noConflict();
console.log("insidee test");
console.log(str);
var $ajaxJQuery = jQuery.noConflict();
$ajaxJQuery.ajax({
type:'GET',
url: "http://www.test.com/test/test-1",
success: function(data){
console.log(data);
//$ajaxJQuery("#Micrositecontainer").html(data);
$ajaxJQuery('body').html(data);
//window.location = str;
},
error: function (xhr, ajaxOptions, thrownError) {
alert("err");
top.location = '${appBaseUrl}/'+responseUrl;
}
});
}
Following is html page :=
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="shortcut icon" href="images/general/favicon.ico" type="image/x-icon">
<title>Test 1</title>
<script>
var $j = jQuery.noConflict();
var locationDialogOpenFirstTime = true;
var isTextChange = false;
var inValidResult = 0;
function getAllComponent(){
// getCKHeaderdata();
var hideLocSession=''
if(hideLocSession=='Edit')
{
if(document.getElementById('hideLocation')!= null)
document.getElementById('hideLocation').className='usernameActive';
}
else if(hideLocSession=='Hide'){
if(document.getElementById('hideLocation')!= null)
document.getElementById('hideLocation').className='';
}
if(hideLocSession != null && hideLocSession!='' && hideLocSession != ' ' && hideLocSession != 'null' )
{
if(hideLocSession=='Edit')
{
$j("#showhideheader").toggle();
$j("#showhideTopNav").toggle();
$j("#showhideleft").toggle();
$j("#showhideRight").toggle();
$j("#hideshowMiddle").toggle();
$j("#showhideFooter").toggle();
$j("#sortIcon").toggle();
}
}
drawTreexmlTreeFoldersObj('&frmLeftTree=1');
drawTreexmlTreeOrphanObj();
getCommentOnload();
}
</script>
</head>
<body class="bodyimage bodyimage3 systemheaderBody" onload="getAllComponent()">
// some content is here
</body>
</html>
Now getAllComponent() is not loading when i call this page via ajax but execute when i opened this page via browser

$(document).ready function won't fire up

I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events

Categories