internet explorer 9 & javascript variable scoping issue - javascript

this code works in Chrome & Firefox but not in IE9 ... need some hints ...
var obj = {
data: [],
json: function() {
var self = this;
$.getJSON("highscore.json", function(resp) {
self.data = resp.splice(0);
});
}
};
Update:
thx for your help ...
it was an issue from the ie9,
ie has thrown the error code "c00ce56e" - it's an issue with charset.
i'll try another header in the php scripts ...
thx # all

Your code looks fine to me, other than that data won't be populated until the json request is done, which is NOT instant because ajax is asynchronous.
obj.json();
alert(obj.data); // []
setTimeout(function(){
alert(obj.data); // ["foo","bar","foobar"]
},5000);
Update
I suggest adding a property to your object called request, and store the $.getJSON request in it. At that point it doesn't make sense to store the data directly on the object because you can always get it from the request.
var obj = {
request: {done:$.noop,fail:$.noop,always:$.noop},
json: function() {
this.request = $.getJSON("highscore.json");
}
};
obj.json();
// you can run the following as many times as you need to use the data.
obj.request.done(function(data){
alert(data.splice(0));
});
just note that in it's current form you must call .json() before you can add callbacks to the request.

Related

Ajax call via POST not working

I have a lil problem with an AJAX request.
We have a lil PHP, JavaScript application (Website). The application is running fine on all desktop browsers + on our old MDE's (some Windows CE6 MDE). Now on our new Motorola MC9200 (Windows Embedded Compact 7 formerly CE7) it's not working anymore.
The problem is some small JavaScript function. It disables the buttons/input fields, starts a Ajax.Request (prototype 1.72 but I tested jQuery 1.11.1 too), does something on the database and when everything went right it is refreshing the site via window.location. This function isn't working always on the new devices. Sometimes it does, sometimes not.
simplified code:
function loadSite(siteName) {
disableForm();
var parameters = {
/* SOME PARAMETERS */
};
new Ajax.Request('ajax/ajax_db_execute.php', {
method: 'post',
parameters: parameters,
onSuccess: callbackFunc
});
}
function callbackFunc(transport) {
response = transport.responseText.evalJSON(true);
if(response.retcode === 0) {
window.location = "start.php?id=<?php echo $id; ?>";
} else {
show_error_box(response.errortext);
enableForm();
}
}
I tried to output the response in the callbackFunc but that function wasn't even called. Next thing I tried was to put some alert at the end of the loadSite function, it was fired everytime. I already checked the parameters and they look fine too.
After that I put some simple fwrite in the php file. It looks like that file isn't even called sometimes. So the question is why?
By changing the method to 'get' I couldn't reproduce the problem and everything is working fine. Problem about that is that I don't want to use get + some parameters might be too long for get to handle.
The parameters in that example were just some simple integers and strings. Does anyone have an idea what might cause the problem and some workaround?
It seems that your post request response is not synchronized. So please use setTimeout function in your post callback like that
setTimeout(function(transport) {
response = transport.responseText.evalJSON(true);
if(response.retcode === 0) {
window.location = "start.php?id=<?php echo $id; ?>";
}
else
{
show_error_box(response.errortext);
enableForm();
}
}, 3000);

jquery $.post() getting canceled [duplicate]

This question already has answers here:
XHR request is denoted as being cancelled although it seems to be successful [closed]
(2 answers)
Closed 9 years ago.
I'm getting a "canceled" status whenever I do a jquery $.post(). It seems like an asynchronous problem? I access the local project with http://127.0.0.1:8933/myproject/default/index.html
index.html:
<script>
$(document).ready(function() {
$('#mybutton').click(function() {
var post_url = get_url(); // resolves to "/myproject/default/process_func"
var data = ...;
do_action(post_url, data);
});
});
</script>
Click me!
util.js:
function doPost(url, data) {
$.post(url, data).then(doSuccess, doFail):
function doSuccess(data) {
alert('Successful!');
}
function doFail(data) {
alert('Failed!');
}
}
function do_action(url, data) {
var jsondata = JSON.stringify(data);
// some other stuffs...
doPost(url, jsondata);
}
The idea is to post some data back to the server for processing using json data. A user will click on the anchor button, the do_action() will fire, and then it'll be posted in doPost().
This seems to work since my I'm seeing the json data passed to my processing function on the server. However, I'd see the alert message "Failed!" pop up every time even though the data has been processed. In chromium's debug panel, I see under "Network" tab that the post has a status of "(canceled)" and the entire line would be highlighted in red. The Type stated is "Pending".
I think this is an asynchronous problem, but I'm unsure how to fix it.
Use this, to cancel the default navigatin behavior of the <a>:
$('#mybutton').click(function(e) { // <-- Add `e` here
e.preventDefault(); // <-- Add this line
var post_url = get_url();
var data = ...;
do_action(post_url, data);
});
I believe the AJAX request is being aborted by the browser because when clicking the link, although the request does get sent off, the link tries to navigate to a new page so the browser must abort open AJAX requests.
You can try this...
$('#mybutton').live("click", function(e) {
e.preventDefault();
var post_url = get_url();
var data = ...;
do_action(post_url, data);
});
Depending on the version of jQuery you are using, you can use jQuery.live() or jQuery.on() method
When the e.preventDefault() method is called if this method is called, the default action of the event will not be triggered.
Resources:
event.preventDefault()
$.live()

Internet Explorer CrossDomain Request doesnt work correctly and MS doesnt give onerror reasoning

I added variables in the request as per the Microsoft standard below, var openRetVal and var sendRetVal... Odd thing is, that they dont get anything returned in them, so did Microsoft lie in their own documentation?
I was working on a ajax request, and like usual, IE is a difficult specimen to work with. I found that instead of doing a AJAX request, i can do an XDR. My code in chrome works, so i know the destination server is working and on a successful request does what is suppose to happen. Below is my code segment for an XDR.
if ($.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
//var webstring = location.protocol +"//"+ location.host +"/" + WEBSERVICE_URL + "/test";
//WEBSERVICE_URL = "webservices/FormDesigner.svc";
var webstring = WEBSERVICE_URL + "/test";
var openRetVal = xdr.open("GET", webstring); //added this var as it supposidly gets a return value from the function call.
xdr.onload = function () {
var JSON = $.parseJSON(xdr.responseText);
if (JSON == null || typeof (JSON) == 'undefined') {
JSON = $.parseJSON(data.firstChild.textContent);
}
//below is my onsuccess call which is called by both successes for IE and NON-IE processes allowing all stuff to be piped into 1 call.
ajax_success(JSON);
};
xdr.ontimeout = function () {
alert("XDR Error. Timeout");
}
xdr.onerror = function () {
alert("XDR Error. Unable to do a Cross Domain Server Request.");
};
var sentRetVal = xdr.send(); //added this var as the function is suppose to return success or error as per microsoft.
}
It always returns onerror which is NOT what i am aiming for, naturally. I am pinging something within the same domain for the moment for testing purposes which is why there is not other stuff. Like i said, it works with other browsers so far... Is there an improper formatting I am unaware of? There is no data submitted as well with this test request.
If you are already using jQuery, just use jQuery for ALL BROWSERS, then you should not have any issues in IE.

How to include JSON data in javascript synchronously without parsing?

I want to load a JSON file from my own server containing an array into a javascript Object variable.
I would like to do it at the beginning of page load in a synchronous way because data is needed during page load.
I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.
Is there a way to load JSON in a synch way without doing your own parsing? (more or less like using a <script language="JavaScript" src="MyArray.json"></script>)
Thanks in advance for any help, hope it makes sense since I am a javascript newbie.
Paolo
getJSON() is simply shorthand for the ajax() function with the dataType:'json' set. The ajax() function will let you customize a lot about the request.
$.ajax({
url: 'MyArray.json',
async: false,
dataType: 'json',
success: function (response) {
// do stuff with response.
}
});
You still use a callback with async:false but it fires before it execution continues on from the ajax call.
Here you go:
// Load JSON text from server hosted file and return JSON parsed object
function loadJSON(filePath) {
// Load json file;
var json = loadTextFileAjaxSync(filePath, "application/json");
// Parse json
return JSON.parse(json);
}
// Load text with Ajax synchronously: takes path to file and optional MIME type
function loadTextFileAjaxSync(filePath, mimeType)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
if (mimeType != null) {
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType(mimeType);
}
}
xmlhttp.send();
if (xmlhttp.status==200 && xmlhttp.readyState == 4 )
{
return xmlhttp.responseText;
}
else {
// TODO Throw exception
return null;
}
}
NOTE: This code works in modern browsers only - IE8, FF, Chrome, Opera, Safari. For obosolete IE versions you must use ActiveX, let me know if you want that I will tell you how ;)
if you're using a server script of some sort, you could print the data to a script tag on the page:
<script type="text/javascript">
var settings = <?php echo $json; ?>;
</script>
This will allow you to use your data synchronously rather than trying to use AJAX asynchronously.
Otherwise you'll have to wait for the AJAX callback before continuing on with whatever it is you're doing.
I only needed to read a small input file provided in json format and extract a small amount of data. This worked just fine in the circumstances:
json file is in the same directory as the script and is called data.json, it looks something like this:
{"outlets":[
{
"name":"John Smith",
"address":"some street, some town",
"type":"restaurant"
},
..etc...
read the data into js like this:
var data = <?php echo require_once('data.json'); ?>;
Access the data items like this:
for (var i in data.outlets) {
var name = data.outlets[i].name;
... do some other stuff...
}
If RequireJS is an option, you can make it a dependency using requirejs. I use it to mock data in my Angular application. It's essential that some of the mocked data is there before the bootstrap of the app.
//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});
Just wrap the json data in a define and declare it as a dependency. More info here: http://requirejs.org/docs/api.html#defsimple
AFAIK jQuery has deprecated synchronous XHR requests because of the potential for performance issues. You could try wrapping your app code up in the XHR response handler as in the following:
$(document).ready(function() {
$.get('/path/to/json/resource', function(response) {
//'response' now contains your data
//your app code goes here
//...
});
});
The modern HTML5 way without jQuery would be:
var url="https://api.myjson.com/bins/1hk8lu" || "my.json"
var ok=await fetch(url)
var json=await ok.json()
alert(a.test)

Problem when requesting a form using prototype on internet explorer 8

I'm trying to make a request using prototype 1.6.1 on ie 8, the following code works on Firefox:
var myForm = document.forms[0];
myForm.request({
onSuccess:
function(transport) {
var url = getPath() + nomeAcao+'?modulo='+modulo;
window.location = url;
}
});
When debugging, i get an error on the "myForm.request" line, it says i can't call this method on this object. Anyone knows how to fix it?
instead of
myForm.request(...);
try
Form.request(myForm, ...);

Categories