IF-ELSE statement not working - javascript

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
}

Related

If condition not working if (str == "1") while data is returning 1

If condition not working while data is returning 1 and 0 but it always execute the else code, i am unable to find error, code is working fine on localhot but not on server
$('#by_head_name').on('blur', function() {
var headsubt = document.getElementById('by_head_name').value;
if (headsubt !== "") {
//alert('hi');
$.post('verify-head-or-subhead-name.php', {
headsub: headsubt
},
function(data, status) {
var str = data;
if (str == "1") {
var headd = "ok";
alert('ok');
} else if (str == "0") {
alert("No Head Exist, Please choose valid Head or create one before selecting it");
} else {
alert(data);
this.value == '';
}
});
}
Please check what "data" of the success function returns in your alert message.
If it returns string directly, then your condition should work.
If it shows object in the alert screen, please verify your object and accordingly choose a variable which satisfy your condition like data.value.

jquery / javascript Load different content depending on session

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;

Javascript validation. What am I not passing after the .val using values

how is my values not passing for ajax using trim and val. The issue is that when I check it using trim and val the values get check if there was anything typed if there is nothing then it sends to validation false if there is something it will hide the validate. All works bu the values do not make it and I get a new row without values. What am I missing from my function to pass my values. Here is the code:
var validation = "";
var values = {};
if ($.trim($("#name").val()) === "") {
$("#validateName").show();
validation = "false";
} else {
$("#validateName").hide();
}
if ($.trim($("#news").val()) === "") {
$("#validateNews").show();
validation = "false";
} else {
$("#validateNews").hide();
}
if(validation == "false"){
return false;
}
values['addnews'] = '';
$.ajax({
// Rest of the code //
This is how it was previously passed. Here is the code:
$.each($('#add-news-form').serializeArray(), function(i, field) {
if((field.value == 0)){
validation = "false";
}
values[field.name] = field.value;
});
What am I missing from my ajax function to pass the values?
If you want to assign the name input text to the values object, you can do it like so:
values['name'] = $.trim($("#name").val());
Ideally you shouldn't have this trim statement twice, you should store the trimmed value in a variable and use that variable in both your validation and assignment sections.
Then make sure you're passing 'values' in the data param of your ajax call:
$.ajax({
data: values
// rest of your ajax code
});

How to carry "getjson" functionality from one func to another?

Basically I have a getjson call to call for a bunch load of data. Now I am getting sick of the amount of if data is null else checks.
For Example:
if (data.Height == "") {
$('#DataHeight').html('No Data is Available');
}
else {
$('#DataHeight').html(data.Height);
}
Reason being is the user has to be alerted asap that data is not available.
So I went off and am trying to write a DataCheck.js to include and handle all this outside of my pretty little page :D.
Function:
function DataNullCheck(ObjectName) {
if (data.ObjectName == "") {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}
and to call it inside my function
function getdata() {
$.ajaxSetup({
cache: false
});
$.getJSON(urldefault, function (data) {
DataNullCheck('Height');
.......
And Data is undefined. Because it is not within the JSON call?
Any help or hints towards the right direction would be appreciated especially an explanation of why it works one way or another. Thanks in advance.
How would I carry through the getJson call functionality to my little function?
Pass data as a parameter to your function:
function DataNullCheck(data, ObjectName) { // you can check for null any property of data
// e.g. DataNullcheck(data, "Width"), or
// DataNullCheck(data, "Height") etc.
if (!data[ObjectName]) {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}

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