jQuery and JSON vs IE - SCRIPT5007: Unable to get value of the property - json

I'm struggling to get this script working. It's basically a simple ajax call to retrieve data from a php which returns a JSON code.
function refreshWindows(){
if(AjaxPull && AjaxPull.readystate != 4){
AjaxPull.abort();
}
AjaxPull = $.ajax({
type: 'POST',
url: $path,
data: {
ajax: true,
mode: 'update',
to: Math.round(currentDate.getTime() / 1000),
from: Math.round(previousDate.getTime() / 1000)
},
dataType: "json",
success: function (data) {
alert(data); //that's for debug
$replies = data.Updates;
$.each($replies ,function(group,value) {
if (value!=''){
$("#group"+group+" .content").append(value);
$("#group"+group+" .content").stop().animate({ scrollTop: $("#group"+group+" .content")[0].scrollHeight }, 800);
if (!$("#group"+group+" .Window").is(':visible')) {
$("#group"+group+" .BottomBox").fadeTo('fast', 0.5).fadeTo('fast', 1.0);
}
}
});
previousDate = currentDate;
currentDate = new Date();
timeController.push( setTimeout(function(){refreshChatWindows();}, 500) );
}
});
}
The error I get in Internet Explorer is:
SCRIPT5007: Unable to get value of the property 'Updates': object is null or undefined
Everything works fine in Firefox and Google Chrome.
Initially my code was made using .get but someone suggested switching to the .ajax - well, it didn't help. I tried using .done(function(data){ but it didn't work either. I also tried sending all of the data in my URL opposite to the data property, it worked fine in FF, but IE still popped the same error. Finally I tried adding different headers to the PHP, like for example header('Content-Type: application/json'); but it didn't change anything. I run out of ideas / possible solutions I could fine on stackoverflow, so any help would be appreciated.
In IE I went to Developer Tools, network tab and tried to see if everything works - yes, the request is being sent correctly with all the data, and a response I receive is correct JSON, just as it is in Firefox:
{"Updates":{"1":"","2":"","3":"","5":"","6":"","7":"","8":""},"time":{"from":"1367489761","to":"1367489761"}}
which gets me really confused, cause I'd have thought that Undefined error might happen only because something is not being sent back in IE for whatever reason, but clearly: It's not the case. I get my JSON back. Only IE for some unknown reason still thinks that data is undefined.

Ok, I found a solution finally.
Basically:
Remove any headers sent by PHP script. Especially: Content-type headers. (luckily - seems like sessions still can be used)
Use }).done(function ( data ) { instead of success: function (data) {
and that's all. Suddenly it started to work. It's very weird. Seems like the shotgun tactic (randomly changing bits of code till it works) is actually a valid way of solving problems. hehehe

I have a similar json call that returns data that looks like this:
{"GetTombstoneDataRestResult":{"AlphaSort":"Arai Junichi","Classification":"A&D Design Object"...etc
In other words, a lot like your json data. To reference it in jQuery, I use the callback name.
$.ajax({
type: "GET",
dataType: "jsonp",
url: url,
success: function (result) {
$('#screenshot').append('<p><strong>Title: ' +
result.GetTombstoneDataRestResult.Title + '</strong><br />Year: ' +
result.GetTombstoneDataRestResult.Dated + '<br />Artist: ' +
result.GetTombstoneDataRestResult.DisplayName + '</p>');
}
});
Looks like you want to try this too:
var replies = data;
$.each(replies.Updates ,function(group,value) {

You have a character called ​ in your JSON.
See a description here:
What's HTML character code 8203?
It's right before your colon here "time"​:
Can you clean your output and validate the JSON and try again?

Related

Shopify Chrome Extension For Admin

I'm trying to create an extension that adds 2 fields to the admin product page of shopify in order to add a metafield.
I know there are some extensions out there, like ShopifyFD and CustomFields, but mine is really, really simple, i'm by no means trying to copied it, this is very custom for my shopify store.
All I want, is to add 2 specific metafields to the page, and save it when i click the button Save.
That said, Everything is already working, but i'm having a problem during POST/PUT. It keeps returning status '303 See Other' and redirecting me to login, behavior that I do not encounter on neither of the 2 extensions i cited in the beginning. I wonder if the approach i'm using is the problem or what else could it be, so i'm resourcing to your help.
here how the header look like:
Request URL:https://mywebsite.myshopify.com/admin/products/461395295/metafields/9911129091.json
Request Method:PUT
Status Code:303 See Other
Remote Address:23.227.38.70:443
Like I mentioned I used a different approach as ShopifyFD or CustomFields, instead of loading a script, i'm using the content script.
here how my manifest look like:
"content_scripts": [
{
"all_frames": true,
"matches": [
"https://*.myshopify.com/admin/products/*"
],
"run_at": "document_end",
"js": [
"scripts/vendors/jquery.js",
"scripts/vendors/handlebars-v3.0.0.js",
"scripts/vendors/handlebars-helpers.js",
"scripts/utils.js",
"scripts/shopify-product-addon.js"
]
}
]
1 - I replace the current Save button with a new one so i can save the metafields before submitting the native form
2 - I append the POST/PUT method to the new Save button i have replaced
here how my post/put looks like:
Note: record is the values i'm saving.
var metaJSON;
if (record.update) {
metaJSON = {
'metafield': {
'id': record.metafield_id,
'value': record.value,
'value_type': record.value_type
}
}
method = 'PUT';
url = '/admin/' + route_url + '/metafields/' + record.metafield_id + '.json';
} else {
metaJSON = {
'metafield': {
'namespace': record.namespace,
'key': record.key,
'value': record.value,
'value_type': record.value_type
}
};
url = '/admin/' + route_url + '/metafields.json';
method = 'POST';
}
$.ajax({
type: method,
url: url,
data: metaJSON,
dataType: 'json',
success: function(d) {
console.log('SUCCESS');
},
error: function(d) {
console.log('ERROR');
}
});
The problem is that It fails everytime. I wonder what's wrong. Is the method i'm using?
I'm doing pretty much as the ShopifyFD is when posting/putting to the ajax api, just not sure what's missing. the only difference i've found was that on the ShopifyFD, there is a cookie set to request_method=PUT or request_method=POST. I don't know how this cookie is set, because it's not on the script. I even tried to set it manually, but it doesn't work.
As you can see, i have tried pretty much everything.
Does anyone else has any other suggestion?! :P
Thanks
I didn't figure it out why ShopifyFD works, i would really like to understand thou, but i found another way to make it work.
You need to set the CSRF token before you request the header.
Works like a charm!
$.ajax({
type: method,
url: url,
data: metaJSON,
beforeSend: function (request) {
var token = $("meta[name=csrf-token]").attr('content');
request.setRequestHeader("X-CSRF-Token", token);
},
.
.
.

Transmitting a JSON-Object to a new HTML side

Hello guys i have a big problem, which i somehow cant fix. I am having some JSON- Objects which i am giving out with a table, this part works perfectly fine. But than i would like to have a button or link that posts one of this JSON- Objects (the ID) to a new .html page. In this new .html page i would like to use the ID in Javascript code.
Does anybody know if there is a way how i can accomplish this and if yes how can i do it?
I tried to post it via the php _get methode but it just doesnt work it tells me that there is an " Uncaught TypeError: Cannot read property 'value' of null"
My JS-Code looks like this:
function dataRequest() {
var output = $('#output').text('Loading data...');
$.ajax({
url: 'http://test/html/getmeineFahrten.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
output.empty();
var ort ='<table border="dashed" width="30%">'
$.each(data, function(i,item){
var ServerDatum = item.abfahrt
var Datumonly = ServerDatum.substring(0,4) + ServerDatum.substring(5,7) + ServerDatum.substring(8,10);
var calcDatum = Datum - Datumonly
if(item.user_user_id == userID){
if(calcDatum < 0){
ort += '<tr>'+'<td>'+item.abfahrt+'</td>'
+ '<td>'+item.rueckfahrt+'</td>'
+ '<td>'+item.StartOrt+'</td>'
+ '<td>'+item.Zielort+'</td>'+'<td>'+'<form action="http://test/html/meineFahrten_Karte.html?FahrtenID= + item.fahrten_id" method="get"><input type="submit" value="Karte">'+'</form>'+'</td>'+'</tr>';
}}
});
ort +='</table>';
output.append(ort);
},
error: function(){
output.text('There was an error loading the data.');
navigator.notification.confirm(
'Something went wrong. Would you like to retry?',
yourCallback,
'Error',
'No,Yes'
);
}
});
}
You can't access URL parameters unless you create your own function to do so. Unfortunately, there is no native function for this yet, however, user Quentin answers this question in greater detail and provides a function for getting URL parameters.
How to get the value from the GET parameters?

MVC 3 jQuery UI autocomplete not displaying the results

I have searched many times and find examples which match my code structure perfect. Yet I am not getting the results from my ajax to display on the input box.
I get results from the POST that have been evaulated with firebug and everything looks great.
Here is the javascript im using.
<script type="text/javascript" language="javascript">
$(function () {
$("input.FamousPerson-List").autocomplete({
source: function (request, response) {
$.ajax({
url: "/FamousPeople/FPPAutoComplete",
type: "POST",
dataType: "json",
data: {
searchText: request.term,
maxResults: 12
},
success: function (data) {
response($.map(data, function (item) {
return {
value: item.DisplayName
}
}))
}
});
}
});
});
Here is a link of the actual code I am using on the web.AutoCompleteTesting Type just about any letter in one of the boxes below to invoke it.
Thanks.
If you look closely at the request being sent up, you'll notice that a callback parameter is being added. Weird, right? Since you're doing a local AJAX post, not a cross-domain (JSONP) one.
I noticed that your project includes jQuery Validate. According to this answer to a question dealing with a similar problem (performing a JSONP request instead of a normal JSON request even though you asked for one), it's a known issue in jQuery validate.
Judging by the other answer, you can change your version of jQuery or perhaps use a patched version of jQuery validate (found here).

jQuery $.ajax() is firing the server request but never gets response on google chrome only

I tested this on firefox and ie and worked. But when testing on chrome, I see in the firebug console that the request never loads.
This is the test page: http://gotune.to/index2.php
And here is the function + $.ajax() request.
function getProgress(id) {
$.ajax({
type: 'POST',
cache: false,
url: "getprogress.php",
//Pass our upload identifier as a parameter.
data: {uid: id},
success: function (d) {
//Get the output as an integer.
var progress = parseInt(d, 10);
//If upload progress is not 100, change bar percentage and update again.
if (progress != '100') {
$('#ProgressBar').css('width', progress + '%');
//We aren't done, update again.
getProgress(id);
}
}
});
}
UPDATE
Tried with
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus+" - "+errorThrown);
}
But still not working.
After a web research for this issue if found this:
Turns out it's a bug, in any webkit
based browser all ajax is essentially
blocked until the file upload is
complete. to bypass this you have to
dynamically create an iframe and run
the ajax requests from within it.
So is a problem of the webkit browsers, thanks #ifaour for your time.
THE BUG REPORT CAN BE FOUND HERE: https://bugs.webkit.org/show_bug.cgi?id=23933

jQuery AJAX request failing in IE

The following AJAX call is failing in IE.
$.ajax({
url:"{{SITE_URL}}/content/twitter.json",
dataType:"json",
error:function(xhr, status, errorThrown) {
alert(errorThrown+'\n'+status+'\n'+xhr.statusText);
},
success:function(json) {
...Snip...
}
});
The error function returns
Undefined
parsererror
OK
No request is made to the server so I don't think its a problem with the JSON.
Fixed, See #1351389
Fixed, I changed the content-type from application/json; charset=utf8 to just plain application/json.
I hate IE :)
Also to avoid IE super-caching try this:
var d = new Date();
$.ajax({
url:"{{SITE_URL}}/content/twitter.json?_="+d.getTime(),
...Snip...
That way each request is a new url for IE to get :D
For the caching problem why don't you simple use the cache: false parameter?
$.ajax({
url: "yoururl",
cache: false,
....
is this a copy/paste? the one thing that gets me all the time is leaving the last ',' in an object constructor. that is, most browsers JS accept:
o = { a:1, b:2, c:3, };
but IE chokes on this because the comma after the last item. change it to:
o = { a:1, b:2, c:3 };
and it works.
In newer versions of internet explorer (IE7) it is necessary to write the next line before calling $.ajax, otherwise it would never call the function:
$.ajaxSetup({ cache: false }); //this line before $.ajax!!!
$.ajax({
//codes
//codes
//codes
});
IE caches AJAX requests really aggressively (more so than Firefox, anyway). You need to set the Cache-Control headers in the response appropriately if this is not right for your site.
One major problem with statically generated JSON and IE are the leading "commas", for examples this throws an error in IE:
{
"one":"hello",
"two":"hi",
}
Note the last comma.
What is the {{SITE_URL}} chunk giving is about. Try looking at the code in view source code of the browser. If the {{SITE _URL}} chunk has a trailing slash and that would make the request url:
http://modomain.com//content/twitter.json
Which could creep IE out?
IE: JSON not defined error resolved at
http://funkatron.com/site/comments/safely-parsing-json-in-javascript/
by using dataType: "json" and avoid parsing