jquery / javascript Load different content depending on session - javascript

hey guys i have this code here:
$('#internet').click(function(e){
e.preventDefault();
$.ajax({
url: "ajax/sessionset.php",
success: function (data){
if (data == 1){
$.ajax({
type: "POST",
//add variables
url: "ajax/loggedin.php",
success: function(data2){
//history.pushState({"internet.php?view=internetlog");
$('#internetlog').html(data2);
}
});
}
else if(data===0){
alert("suka");
}
}
});
});
The sessionset.php returns a value of either 1 or 0, depending if the session is currently going on or not.
Problem here is the link $('#internet')
returns the url loggedin.php when the data value is 1.
However if the data value is 0, nothing happens, since the e.preventDefault(); prevents any events.
Already checked on firebug that it either returns values of 1 or 0, I dont understand why the alert is not firing off when the value returned is 0...
edit: just checked the sessionset.php in a separate window instead of firebug
<?php
session_start();
if (!empty($_SESSION['origuserip'] && $_SESSION['loggedin'])){
$switch = "1";
}
else {
$switch = "0";
}
echo $switch;
the return value of 1 is 1 however if !empty is false it returns
Notice: Undefined index: origuserip in ajax\sessionset.php on line 4
0
SOLUTION:
Guess the simplest way is just the best way -_-
else {
("suka");
}

The scripts return value is probably a string, because you didn't specify the return type of your AJAX call.
You should validate like this: data==="1" and data==="0". Which checks for identity, as long as you definitely return strings.
data==1 is always true, if it's set and not null.
Regarding the other problem:
Make sure your $_SESSION variables are set properly when you check their indexes and separate the empty() checks. For example like this:
if (!empty($_SESSION['origuserip']) && !empty($_SESSION['loggedin'])){
$switch = "1";
}
else {
$switch = "0";
}
echo $switch;

Related

javascript variable seems to be zero but no

I have problem with recognizing variable and defining if statement dont know why. So...
$.ajax({
type: "POST",
url: "check.php",
success: function(response){
alarmvar = response;
if(alarmvar !== 0){
alert(alarmvar+"aaaaag");
}
}
});
and in check.php file:
$rowsw = mysql_num_rows($query);
echo "".$rowsw."";
variable is always defined not like 0 even if mysql_num_rows returns 0
alert is always shown and alarmvar variable causes next line in alert box.
Where is the problem?
The problem is you check if alarmvar is 0 value and number type. The operator !== check value and type. When mysql_num_rows is 0, you are checking "0" !== 0, and return true because the type is different. Alternatives:
if(alarmvar !== "0"){
alert(alarmvar+"aaaaag");
}
Or (Not recomended)
if(alarmvar != 0){
alert(alarmvar+"aaaaag");
}
And I recomended you use var to declare alarmvar, if not, alarmvar is in global scope.
var alarmvar = response;

IF-ELSE statement not working

I'm trying my best to create a website.
I need to create an IF-ELSE in ajax. It basically calls the content of an input called "greeting" and aims at writing "YES" if the user inserts a specific text and "NO" otherwise.
jQuery(document).ready(function () {
var greeting = jQuery("#greeting").val();
jQuery("#push-me").click(function () {
jQuery.ajax({
type: 'POST',
url: 'http://www.boatsandbeats.com/wordpress/wp-admin/admin-ajax.php',
data: {
action: 'myAjax',
greeting: jQuery("#greeting").val(),
},
success: function (data, textStatus, XMLHttpRequest) {
if (data == "XYZ") == 0 {
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
} else {
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
While the rest of the code works just fine, it does not recognize the IF and takes everything as if it were true (therefore, printing "YES").
Can anybody be so kind and explain this to me?
it is not working because your if statement is wrong
if (data == "XYZ") == 0 {
should be
if (data.greeting == "XYZ") {
}
Step 1: check if your ajax actually returns something.
...//add the following line
success: function (data, textStatus, XMLHttpRequest) {
console.log(data);
alert("Data logged." + data);
...
Step 2: what do you want to test?
You want to know if data (the ajax return) is a string and that string is having the value "XYZ"?
//change
if (data == "XYZ") == 0
//to
if (data === "XYZ")
Note the triple === it's not the same as ==. The difference is that === will check if the variables have the same value and the same type.
In addition, in Javascrip can compare string similar to your style like using localeCompare():
if (data.localeCompare("XYZ") === 0)
/* strA.localeCompare(strB); Returns:
0: exact match
-1: strA < strB
1: strB > strA
*/
UPDATE:
Assuming your php function is as the following:
function myAjax()
{
$greeting = $_POST['greeting'];
if (isset($_POST['greeting']))
$greeting = $_POST['greeting'];
$results = "<h2>".$greeting."</h2>";
die($results);
}
This is what's going to happen.
{
//$greeting is being assigned a value from POST greetings, // in post is empty then $greeting will be empty as well.
$greeting = $_POST['greeting'];
//You are validating POST greeting, although you already captured it's value and put it in $greeting, so why not using $greeting here instead?
if (isset($_POST['greeting']))// this if has no {} so ONLY the first line after will be included in this IF condition.
$greeting = $_POST['greeting'];
// this line will be exectue no matter what, so the value of $greeting will be entered into a string enclosed with <h2> tags. if POST greeting is empty, then $greeting will be empty of course.
$results = "<h2>" . $greeting . "</h2>";
//the variable $result now has "<h2></h2>" as it's value if $greeting is empty.
die($results); //echoing $result, or
}
So, since you have confirmed that you are receiving "" as a value for data variable returned from AJAX. Why are you comparing it to XYZ in your condition?
In your JS you are assigning "#greeting").val() to a variable greeting, then you use that variable as an array attribute for your ajax{data{greeting:jQuery("#greeting").val() }}
var greeting = jQuery("#greeting").val();// what is the use of this line?
Enclose your object attribute with "" e.g. "greeting".
data: {
"action": 'myAjax',
"greeting": jQuery("#greeting").val(),// what is the value of "#greeting").val()?
},
first of all you need to check data will exactly print XYZ or print [Object object]
if [Object object] then you need to check data.d=="XYZ"
in success function first parse then compare like this
var response=$.parseJSON(data);
if(response.field=="XYZ")
{
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
}
else
{
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
IF condition system is looks wrong,
if (data == "XYZ") == 0
You should use only, no need == 0
if (data == "XYZ"){
//.... code here
}
OR If ajax response in json
if (data.key == "XYZ"){
//.... code here
}

Why is this variable changing when passing it around functions?

Edit2: Yay, found the problem, there is actually an error in the ajax call, and because of my stupidity, I didn't realise that both the methods - success and error can be ran (I thought it was either one or the other), so formComplete was being set to false every time because there was an error.
Appreciate the time you gave & tip about not using global variable names as function parameters.
Edit: Here's the code where formComplete is set (console.log()'s to check formComplete throughout the process):
validate: function(field) {
if(!field.val()) {
formComplete = false;
// formComplete is false here
console.log(formComplete);
}
else {
if(field.attr('name') === 'queryEmail') {
// Validate the email
if(DMOFFAT.helper.validateEmail(field.val()) === true){
// formComplete is either true or false here, depending on the last validation carried out
console.log(formComplete);
formComplete = true;
// formComplete is true here
console.log(formComplete);
}
else {
formComplete = false;
// formComplete is false here
console.log(formComplete);
}
}
else {
formComplete = true;
// formComplete is true here
console.log(formComplete);
}
}
},
Question: Why is this variable (formComplete) going from true to false?
I've written some basic form validation for a contact form, here's how I've done it:
Defined the fields like so:
var queryTypeField = $('#queryType'),
queryMessageField = $('#queryMessage'),
queryEmailField = $('#queryEmail'),
queryNameField = $('#queryName'),
submitButton = $('#submit');
Adding some event handlers to these like so (FWIW, DMOFFAT variable is just an object which holds different modules of the code e.g. contactForm = contact form javascript etc.):
queryMessageField.on('blur', function() {
DMOFFAT.contactForm.validate(queryMessageField);
});
queryNameField.on('blur', function() {
DMOFFAT.contactForm.validate(queryNameField);
});
queryEmailField.on('blur', function() {
DMOFFAT.contactForm.validate(queryEmailField);
});
submitButton.on('click', function(evt) {
evt.preventDefault();
console.log('Click');
console.log(formComplete);
DMOFFAT.contactForm.send(formComplete);
});
The validate function simply sets 'formComplete' to either true or false, depending on if the field is valid or not.
When my fields are all filled in correctly, formComplete = true.
As you can see from the last line of my code above, I pass formComplete (which is true) over to my send function. My send function simply checks the value of formComplete, and either sends the data off to a php script, or prints an error, here's the code:
send: function(formComplete) {
// This is true when the form is filled in correctly
console.log('In send formComplete is...' + formComplete);
if(formComplete === true) {
// Extract form values
formData['queryMessage'] = queryMessage.value;
formData['queryType'] = queryType.value;
formData['queryName'] = queryName.value;
formData['queryEmail'] = queryEmail.value;
$.ajax({
type: 'POST',
async: true,
url: '....',
dataType: 'json',
data: formData,
success: function(data, status, xhr) {
DMOFFAT.contactForm.writeMessage(formComplete);
},
error: function(xhr, status, err) {
DMOFFAT.contactForm.writeMessage(formComplete);
}
});
}
else {
this.writeMessage(formComplete);
}
Now, I KNOW that formComplete is true when the form is filled in correctly, because my php script creates a .txt file with the data in, if it was false, this file wouldn't be created.
This means that we send the value of formComplete off to writeMessage, which simply writes out some HTML to the page to display whether the submission was successful or not, here's the code:
// Disgusting spaghetti code
writeMessage: function(formComplete) {
// This is false now...
console.log('In writeMessage formComplete is...' + formComplete);
if(formComplete === true) {
contactFormElement.html('<div class="success ui-message cf-message"><p><strong>Thank you</strong> for your query, we\'ll get back to you as soon as we can.</p></div>');
}
else {
// Check if there's already an error, otherwise many will appear
if(errorElement === '') {
errorElement = '<div class="error ui-message cf-message"><p>' + this.config.errorMsg + '</p></div>';
contactFormElement.prepend(errorElement);
}
}
}
formComplete itself is defined like so:
var formComplete;
When I inspect formComplete on the first line of writeMessage, it's now false, I cannot find out why though...even when I explicitly set formComplete to true before it's passed to writeMessage, it's still false.
TLDR: Tell me where I'm being stupid please :)
PS: I know I could use a pre-built contact form validation plugin, but wanted to try build something simple myself.
The problem is, that you are calling writeMessage() from a callback function for your AJAX request, so the interpreter is looking for a global variable on execution time. Anyway, you can simply pass true to writeMessage() in your callback functions, as the calls are only executed if formComplete is true-

jQuery break if the AJAX response is null

I'm trying to break/return false if a $.post() response is null, by doing so:
....
$('#order_list li > div').remove(); // is to remove `no_data` or `search_box` when clicking on the next `li`
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
console.log(data_response); //outputs null if nothing retrieved, or data if otherwise
if(data_response==null) //stop code if the response is null
{
alert('if works');
$(this).append(no_data).show('slow');
return false; // doesn't do the trick
}
}, "json");
//if not null, continue with this
if( ! $('.search_box').exists())
{
$(this).append(search_box).show('slow');
}
....
But as you could read, my code doesn't do the trick. Any ideas?
UPDATE
the if(data_response==null) works, it's the return false that doesn't do its job
The A in AJAX is for Asynchronous.
When you get to the point where you want to check, it has already executed.
First you run this code:
$.post('do.php', { OP: "news_search", category: cat_id }, callback, "json");
This issues an XmlHttpRequest to the server. I intentionally wrote only callback, because the function is just passed as a parameter. It will only run when the server responded. By that time, the other parts of your code have already run.
$.post() - call to the server
the rest of your code
when the server responded, your callback
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
console.log(data_response);
if(data_response)
{
$(this).append(no_data).show('slow');
// return false; NOT NEEDED
} else {
// below condition should remain here, not outside of Ajax
if( ! $('.search_box').exists()){
$(this).append(search_box).show('slow');
}
}
}, "json");
People usually verify doing the following:
if (foo == null) {
foo = "Joe";
}
When what they really mean is
if (!foo) {
foo = "Joe";
}
Its because null is an object and == does type coercion.
More info in this article: JavaScript undefined vs. null

jQuery Dynamic Function and Variable

I am trying to create a function that handles the 'keyup' event for several input fields and passes the input value to a php script. Here's the code I have so far
$(document).ready(function () {
$("#email").keyup(function () {
val = $("input#email").val();
what = 'email';
aFunction(val, what);
});
});
function aFunction(val, what) {
var dataString = what + '=' + val;
var error = "email_check";
$.post("key.php", dataString, function (data) {
//if (data.[error] == 'invalid'){
if (data.email_check == 'invalid') {
$("#ppp").html('error');
} else {
$("#ppp").html('good to go');
}
}, "json");
//return false;
}
When I uncomment
//if (data.[error] == 'invalid'){
and comment out
if (data.email_check == 'invalid'){
My the script doesnt execute and js file doesn't load into the firebug script console - I assume means there's an error because when I undo that and refresh I can view it. I've tried added single and double quotes to the variable. Also, it would be helpful if there was a way to see what the is error is, but I don't know how to do that.
Your primary problem here is that you should use either dot notation ("data.error") or array notation ("data['error']") but not both ("data.['error']").
Javascript does not support braces in identifiers.
If the key is actually just error, you can write if (data.error == 'invalid').
If it is [error], you'll need to write if (data['[error]'] == 'invalid)`.
To see syntax errors, go to Firebug's Console tab.

Categories

Resources