1

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?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

5 Answers5

2

it is not working because your if statement is wrong

 if (data == "XYZ") == 0 {

should be

 if (data.greeting == "XYZ") {

}
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
1

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()?
            },
Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38
  • Thank you very much for your help! Step 1: what is "alert" supposed to do? nothing really happens, except the div text changes to "NOPE" as usual. Step 2 and 3: tried both, no success :( – user3381904 Mar 05 '14 at 05:44
  • nothing happens? or it alerts but no message in the alert? I assume the 'data' variable is empty – Mohammed Joraid Mar 05 '14 at 05:45
  • oh yeah it actually works, sorry about that. An alert comes out with "data logged.

    "
    – user3381904 Mar 05 '14 at 05:48
  • Then, the content of your data variable returned from the ajax is

    and not XYZ. Check your php file and see what does it echo
    – Mohammed Joraid Mar 05 '14 at 05:48
  • Just for your future reference. I assume you are already debugging with the console. If not, hit F12 to open the console. If you are using Firefox try to install Firebug. If you are using Google Chrome F12 will be enough. Once you open the console you actually can see all the ajax request and what is being returned from the server. That way your debugging process will be much easier. – Mohammed Joraid Mar 05 '14 at 05:50
  • This is function.php function myAjax(){ $greeting = $_POST['greeting']; if(isset($_POST['greeting'])) $greeting = $_POST['greeting']; $results = "

    ".$greeting"

    "; die($results); }
    – user3381904 Mar 05 '14 at 05:56
  • Check my update. One more thing, I'm really confused. What are you trying to achieve here? what is your objective? you are u sending the AJAX request? – Mohammed Joraid Mar 05 '14 at 06:31
  • Thank you so much for your help. I tell you what I'm trying to do even if I have scarce competence with ajax. I want simply to check what's inside the "greeting" input box and see if it's equal to a specific string (say "XYZ") and if so, to print a specific message on the page. However this code seems buggy and overcomplicated as you pointed out. What is the best way to approach the problem? – user3381904 Mar 05 '14 at 08:24
  • Ok then, do you need any information from the database? Why would you need to use AJAX and pass greeting to the serer, while you can compare the directly from the input? cuz so far you are passing the greetings to the server and then return it back as it is (enclosed with

    tags). And then you are comparing it with XYZ. So far the fastest solution is to remove

    form the echo. And see how it goes.
    – Mohammed Joraid Mar 05 '14 at 08:45
  • No I don't need database – user3381904 Mar 05 '14 at 08:48
  • Simplest and more efficeint solution would be to compare just using client side javascript. Your whole code will be summed into => $("#push-me").click(function () { if($("#greeting").val() === "XYZ"){alert("you have entered XYZ")} }); – Mohammed Joraid Mar 05 '14 at 08:48
  • This is JQuery. It's what the dollar sign $ represents. Actually $ equals the keyword JQuery the one u r using. It's a library that runs on using Javascript. AJAX on the other hand, is a technique to send data to the server without the need to refresh the page. You can use plain javascript AJAX (will take several lines) or use AJAX with JQuery which makes it easier to read and understand. The way you are using it is AJAX with JQuery since you opened the tag JQuery.ajax. Keep in mind that PHP is a server side programming and Javascript is client side. Client side runs over the user's browser. – Mohammed Joraid Mar 05 '14 at 09:01
  • search for the following keywords individually [client side vs server side, what is ajax, what is javascript, what is jquery, what is php, javascript vs php] – Mohammed Joraid Mar 05 '14 at 09:01
  • you have been incredibly helpful, keep it up :) – user3381904 Mar 05 '14 at 09:11
0

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 
}
Girish
  • 11,907
  • 3
  • 34
  • 51
  • Thanks for your help! However, this does not work either as now it's always false even if I input "XYZ". I have a hard time understanding why – user3381904 Mar 05 '14 at 05:02
  • @user3381904 check your ajax response in firebug console first `console.log(data);` or alert(data); in ajax `success function` – Girish Mar 05 '14 at 05:04
  • @user3381904, console.log help(http://stackoverflow.com/questions/4743730/what-is-console-log-and-how-do-i-use-it) – Girish Mar 05 '14 at 05:07
  • @user3381904, will let me know if you need any help – Girish Mar 05 '14 at 05:47
  • ok I checked the console log and it basically says it's posting what's in the function.php myAjax(){ $greeting = $_POST['greeting']; if(isset($_POST['greeting'])) $greeting = $_POST['greeting']; $results = "

    ".$greeting"

    "; die($results); } but it actually displays "NOPE". How can it be??
    – user3381904 Mar 05 '14 at 06:15
  • `$_POST['greeting']` may be empty, please check post data `print_r($_PSOT)` in php code – Girish Mar 05 '14 at 06:32
0

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"

JegsVala
  • 1,789
  • 1
  • 19
  • 26
0

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");
}
Love-Kesh
  • 777
  • 7
  • 17