jQuery undefined value for some elements - javascript

I have a response in json format and check some value in my Jquery code its working fine if i check
dataObject.deviceType==='mobile'
then it's always working fine but for
dataObject.mobileRedirect
Its always return undefined. Please help if i forgot something.
My json response is
{"successType":11,"notificationMessage":"Sucess message","feed_seourl":"chandoo","deviceType":"mobile","mobileRedirect":"\/mobile\/directories\/#category_id=all&subcategory_id=0&country=India&countryFlag=in.png"}
And jquery is
if(dataObject.successType === 11 && dataObject.deviceType==='mobile') {
var mobileuser = dataObject.mobileRedirect;
if(typeof mobileuser == 'undefined'){
window.location.href = window.location.protocol+"//"+window.location.host;
}else {
window.location.href = window.location.protocol+"//"+window.location.host+dataObject.mobileRedirect;
}
}

Related

jquery ajax request returns undefined

I am trying to have a link perform a really simple, request, but I can't seem to figure out why what I returned is "undefined".
Currently the link does a manual page request, but it's such a simple subscription thing, I want it to not refresh the page (hence the preventDefault). But if the JS doesn't work or it's blocked, the link should do a normal page request (best of both worlds?).
Here is the JS that captures the click on a link
$('#subscribe-link').click(function(e)
{
e.preventDefault();
var type = $(this).data('sub');
$.post('/includes/ajax/subscribe-article.php', { 'type':type },
function(data)
{
alert(data.result);
if (data.result == 'subscribed')
{
alert('subscribe');
}
else if (data.result == 'unsubscribed')
{
alert('unsubscribe');
}
});
});
And here is the PHP that feeds it:
if($_POST && isset($_SESSION['user_id']) && $_SESSION['user_id'] != 0)
{
if (isset($_POST['type']))
{
if ($_POST['type'] == 'subscribe')
{
echo json_encode(array("result" => "subscribed"));
return;
}
if ($_POST['type'] == 'unsubscribe')
{
echo json_encode(array("result" => "unsubscribed"));
return;
}
}
}
Now, I've checked what "data" returns by itself which is this:
{"result":"unsubscribed"}
Which is correct, I'm not sure what I'm missing this time.
As the variable data contains the JSON representation of your expected result, it is plainly a String. Yet you try and access information contained in that string as an object. For this to work, you first need to create an object from the string by decoding the returned JSON:
var myData = JSON.parse(data);
alert(myData.result);
...
You need to parse the result as JSON. IE, data_array=JSON.parse(data);

Javascript OR statment result different in Chrome

I have a problem with following code:
var status = null;
var action = 1;
function test() {
if(status != null || action == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
I get expected results in Firefox and IE alert('I should be here'). But in Chrome i get alert('Why am i here?').
I'm not able to reproduce this for you, but I might just have the answer:
if(status !== null || action === 3) {
Compare the variable not just by value but also by type, by using an extra =
status and action var names seem too good to not be system reserved. maybe your chrome has something running with a status var allocated. try changing them to something else and see if it makes a difference.
var myStatus = null;
var myAction = 1;
function test() {
if(myStatus != null || myAction == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();

javascript check if null from json

Im using the following javascript. it writes fine until it gets to a result which doesn't have a value. in console log it shows this
Uncaught TypeError: Cannot read property 'text' of null
but my script below doesn't seem to work
var checkCaption = photo.caption.text;
if (checkCaption == null) {
caption = 'meh';
} else {
caption = photo.caption.text;
}
In your example, photo.caption is null, so your code breaks on the photo.caption.text call, before the check is done.
var caption;
if(photo.caption != null) { // Covers 'undefined' as well
caption = photo.caption.text;
} else {
caption = "meh";
}
In my case i use the JSON.stringify to check I have received {} (null) response from the REST server:
if (JSON.stringify(response.data)=='{}') {
//the response is null
}
else {
//the response of JSON is not null
}
It works fine for me to check if the response is null or not.
For me the check of length of the json object resolved the issue -
if Object.keys(jsonobj).length == 0){
// JSON object is null
}
else {
// JSON object has data
}

What's wrong with this javascript code?

var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod != '' && newprod != null) {
$.ajax({
//posting code here
});
}
if (act != false) { document.location.href = window.location; }
The page is refresh in every condition even act false or not.
It is fired on an event.
Can anyone tell me why it page is refreshed in all condition?
var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod) { // not null, undefined or 0
$.ajax({
//posting code here
});
}
if (act) { window.location.reload(1); }
assuming that is what the code was supposed to do. document.location is deprecated and in theory read-only.
This should work
if( newprod != null && newproda.length != 0) {
//Execute the code
}
To the reason why it was always working was that newprod was not the same as ''.
As the question is what is wrong with that JavaScript code i will advise.
if(act) {
document.location.href = window.location;
}
You may want to learn more about false-y values in JavaScript. My guess is that your if statement is giving you some problems because it does not compare the way you think it should compare.

How can javascript work perfectly in FireFox, but not work at all in other browsers?

I use FireFox as my main browser, especially when testing out my site, Avoru. However, when checking to see if my code was working properly across other major browsers (Google Chrome, Opera, and Safari), I found that none of my custom javascript seemed to work. Although the functions and code were clear in the page source, using typeof returned an 'undefined' value for all my functions.
What is the root of this problem? If it makes any difference, I use both the Prototype and jQuery libraries for my code, as well as load all javascript at the bottom of the page (for speed reasons). Thanks!
EDIT: Here is some of the code.
// === var $j frees up the $ selector. === //
var $j = jQuery.noConflict();
// === Function: loading(); and loaded(); Manually controls the #loading element. === //
function loading(){
$j('#load_ovrly').css({'display':'block'});
$j('#loader').fadeTo('fast',1);
}
function loaded(){
$j('#load_ovrly').css({'display':'none'});
$j('#loader').fadeTo('fast',.0001);
}
// === Function: content(); Using everything after the #, the hash is processed and requested. === //
function content(theHash){
var hashIndex = theHash.indexOf('-');
var commaIndex = theHash.indexOf(',');
// === Split the Hash accordingly. === //
if((hashIndex > commaIndex) || (commaIndex == -1 && hashIndex == -1)) newHash = theHash.split(',');
if((commaIndex > hashIndex) || (commaIndex == -1 && hashIndex != -1)) newHash = theHash.split('-');
// === Set some extra variables for proofing. === //
var url = newHash[0]+".php";
// === Get parameters if there are any. === //
if(newHash[1]){
var Json = jsonify(newHash[1]);
var pars = "p="+Json;
}else{
var pars = "p={\"forcepars\":\"true\"}";
}
// === Finally request the page. === //
request(url,pars);
}
// === Function: jsonify(); Turns the leftover hash from content(); into valid JSON. === //
function jsonify(str){
var Json = "{";
var split = str.split(",");
for(var a = 0; a < split.length; a++){
if(a > 0){Json = Json+",";}
var b = split[a].split(":");
if(b[1] != undefined) Json = Json+"\""+b[0]+"\":\""+b[1]+"\"";
}
return Json+"}";
}
// === Function: AJAX(); Sends an ajax request given the url, some parameters, and the onComplete. === //
function AJAX(url,parameters,complete){
$j.ajax({
type: 'POST',
url: url,
data: parameters,
complete: function($data){
var data = $data.responseText;
complete(data);
}
});
}
// === Function: request(); Takes the properly formatted url and parameters and requests the page. === //
function request(url,parameters){
AJAX(url,parameters,
function(data){
$j('#my_box').html(data);
}
);
}
// === Function: sendForm(); Sends the form and updates the page. === //
function sendForm(id,url){
var form = $j("form#"+id).serialize();
AJAX(url,form,function(data){$j("#my_box").html(data);});
}
// === Below are items that are activated once the DOM is loaded. === //
var curHashVal = window.location.hash;
document.observe("dom:loaded",function(){
$j("#loader").ajaxStart(function(){
loading();
}).ajaxStop(function(){
loaded();
});
if(window.location.hash.length > 1) content(curHashVal.substr(1));
new PeriodicalExecuter(function() {
if(curHashVal != window.location.hash){
content(window.location.hash.substr(1));
curHashVal = window.location.hash;
}
},.15);
});
If typeof returned undefined for your functions, chances are there was some parse-time error of the javascript. This means that something that firefox was lenient about accepting in your code, other browsers weren't.
What I'd do is pass the code through JSLint to see if there are any errors. I saw several errors in your code, but I'm not sure if it would be the cause of the problem. Once the JSLint errors are fixed, your code will either work directly, or the cause of the error will be obvious.
Possibly when you drill into the jQuery libraries, you'll find that there are browser specific implementations for its classes and methods. I noticed this with its AjaxManager.
Perhaps you've made the mistake I talked about here: http://my.opera.com/hallvors/blog/show.dml/26650 somewhere in your code?
Anyway, to really answer this question we'd need a link to a full page where the problem occurs.

Categories