What's wrong with this javascript code? - javascript

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.

Related

jQuery undefined value for some elements

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;
}
}

Why doesn't Chrome allow changing of style tag via JS?

I'm running this code:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=".concat(document.getElementById('name').value).concat(document.getElementById('domain').value), function(data) {
if(data == "true") {
document.getElementById('containerThree').style = "background-color:#20bb47;";
}else{
document.getElementById('containerThree').style = "background-color:#b33535;";
}
document.getElementById('avail').style = "color:#272727;";
document.getElementById('emt').style = "color:#272727;";
});
It works fine in FireFox, but in chrome not at all. I've tried using .style.background = "#mycolorcode" but it still doesn't work in chrome(and in that case, firefox too).
Try this:
if (data === 'true') {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
http://devdocs.io/html/element/style
http://youmightnotneedjquery.com/
NOTE: 'true' is a string. You would most likely would rather use the Boolean true.
Based on the latest edit to your question, does this cleanup of your surrounding code help?
jQuery.get('http://email.hackmailer.com/checkuser.php?email='
.concat(document.getElementById('name').value)
.concat(document.getElementById('domain').value),
function (data) {
if (data === true) {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
document.getElementById('avail').style.color = '#272727';
document.getElementById('emt').style.color = '#272727';
});
You don't need to send a string as 'true' to check a condition. Use it like:
var data = true; //use boolean but not 'true' as string.
Then you can simple use it as follows:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=" + document.getElementById('name').value + document.getElementById('domain').value, function(data) {
var colorValue = "#272727";
document.getElementById('containerThree').style.backgroundColor = data == "true"?"#20bb47":"#b33535";
document.getElementById('avail').style.color = colorValue;
document.getElementById('emt').style.color = colorValue;
});
BTW, I am not sure how .style = "background-color:#20bb47;"; is working for you.

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();

onbeforeunload function not working properly

$(function(){
var a=document.getElementById('text_editor_textarea'),regEx=/^\s*$/,
updateOrig = function() {
var sc = $(a).data('sceditor');
if(sc){
sc.bind('keypress', sc.updateOriginal);
sc.blur(sc.updateOriginal);
}else {
setTimeout(updateOrig , 200);
}
};
updateOrig();
if(a.value !== "" && regEx.test(a.value) ){
window.onbeforeunload = function(){
return "You have a post waiting to be submitted";
};
}
});
This code should check if there is data in a and if there is onbeforeunload the alert should be prompted. It works except that even if there is no data in the textarea it still is prompted. Am I doing something wrong here?
Just do a.value !== "" instead of a.value !== null || a.value !== "" inside of this if block:
if (a.value !== null || a.value !== "") {
window.onbeforeunload = function () {
return "You have a post waiting to be submitted";
};
}
Also, flip the if and the event function assignment to this:
window.onbeforeunload = function () {
if (a.value !== "") {
return "You have a post waiting to be submitted";
}
};
I didn't realize this before, but only on page load would your message get called since otherwise the assignment wouldn't occur since the textarea would be empty when you first opened the page.
jsFiddle

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