0

I have written a script i JQuery and PHP, After the success return from PHP, AJAX function should catch a success response but I am not getting that. Below is the code:

$.ajax({

                    url     :"script_admin-add-category.php",
                    method  :"POST",
                    data    :{lExpensesId:lcl_ExpensesId},

                    success:function(data){
                        //if(data=="ok"){
                            if(data=="YES"){
                                alert("EMAIL");
                            }else{
                                alert(data);
                            }
                        //}
                        //if(data=="ok"){
                            //alert("Expenses Id already exists!");
                        //}else{
                            //alert(data);
                        //}
                    }

        });

and here is the php code

//Check connection
    if(!$conn){
        die("Connection Failed: " .mysqli_connect_error());
    }else{
//echo "helloooo";
            if(isset($_POST["lExpensesId"])){
                $lExpensesId    = $_POST["lExpensesId"];
                    $Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
                    if($query_result = mysqli_query($conn, $Lquery)){

                            if(mysqli_num_rows($query_result )){
                                echo 'YES';
                            }else{
                                //echo "Proceed";
                            }
                    }else{
                        echo "Not Okay";
                    }
            }else{

            }
    }       

I can see the echo value on browser and alert value also. But if condition is not working for success function???

15
  • What response code are you getting in your network console? That should always be your first stop debugging ajax to verify that the request happened and what response it got. Commented May 26, 2017 at 17:03
  • I am getting "YES" only. Actually, it should display YES and EMAIL Commented May 26, 2017 at 17:04
  • I am betting it is more that just yes. Commented May 26, 2017 at 17:04
  • console.log( escape(data) ) Commented May 26, 2017 at 17:05
  • Yaar, echo will return the value to AJAX? And why not? Commented May 26, 2017 at 17:09

4 Answers 4

0

Try set correct data type for returned data.

$.ajax({
  url: 'script_admin-add-category.php',
  method: 'POST',
  data: {lExpensesId: lcl_ExpensesId},
  dataType: 'text',
  success: function (data) {
    if (data === 'YES') {
      alert('EMAIL')
    } else {
      alert(data)
    }
  }
})
Sign up to request clarification or add additional context in comments.

2 Comments

hi, it does not matter
Please add some explanation to your answer such that others can learn from it
0

@J Salaria as i understood your question you are having problem with jquery AJAX and PHP code as you are not getting you desired result. There are different ways to send the data through jquery ajax which i will be explain in detail.

$_POST["lExpensesId"] are you getting this ID from a HTML <form> ?.Because here i'll be showing you 3 different practiced ways to send data through ajax..

NOTE: YOUR CODE IS VULNERABLE TO SQL INJECION. I'LL BE ALSO SHOWING YOU THE METHODS TO OVERCOME.IF YOU WANT TO LEARN MORE ABOUT SQL INJECTION CLICK ON THIS LINK SQL INJECTION LINK

HTML FORM CODE :

<form action="" id="send_lExpensesId_form" method="post">
    <input type="text" name="lExpensesId" id="lExpensesId" >
    <input type="submit" name="submit" >
</form>

FIRST WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>

 <script>
    $(document).ready(function(){
        $("#send_lExpensesId_form").submit(function(e){
            e.preventDefault();

            var form_serialize = $(this).serialize();

            $.ajax({
                type:'POST',
                url:'script_admin-add-category.php',
                data:form_serialize,
                success:function(data){
                    if(data == "YES"){
                        alert("EMAIL");
                    }else{
                        alert(data);
                    }
                }
            });
        });
    });
</script>

SECOND WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>

    <script>
    $(document).ready(function(){
        $("#send_lExpensesId_form").submit(function(e){
            e.preventDefault();

            var form_serialize = new FormData($(this)[0]);


            $.ajax({
                type:'POST',
                url:'script_admin-add-category.php',
                data:form_serialize,
                contentType: false,
                processData: false,
                success:function(data){
                    if(data == "YES"){
                        alert("EMAIL");
                    }else{
                        alert(data);
                    }
                }
            }); 
        });
    });
</script>

THIRD WAY FOR SENDING DATA THIS IS USED WHEN A LINK CLICKED OR TO DELETED THROUGH ID OR CLASS

 <script>
    $(document).ready(function(){
        $("#send_lExpensesId_form").submit(function(e){
            e.preventDefault();

            var lcl_ExpensesId = $("#lExpensesId").val();

            $.ajax({
                type:'POST',
                url:'script_admin-add-category.php',
                data:{lExpensesId:lcl_ExpensesId},
                success:function(data){
                    if(data == "YES"){
                        alert("EMAIL");
                    }else{
                        alert(data);
                    }
                }
            });
        });
    });
</script>

HERE IT THE PHP CODE WITH mysqli_real_escape_string(); AGAINST SQL INJECTION

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "admin";
    $dbname = "demo";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    if(isset($_POST["lExpensesId"])){
        $lExpensesId = mysqli_real_escape_string($conn, $_POST["lExpensesId"]);

        $Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
        if($query_result = mysqli_query($conn, $Lquery)){

            if(mysqli_num_rows($query_result )){
                echo 'YES';
            }else{
                echo "Proceed";
            }
        }else{
            echo "Error".mysqli_connect_error();
        }
    }
?>

HERE IT THE OTHER PHP CODE WITH MYSQLI->PREPARED WHICH IS BETTER AGAINST SQL INJECTION

<?php
    // WITH MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION
    $sql = $conn->stmt_init();
        $Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId =?";
        if($sql->prepare($Lquery)){
            $sql->bind_param('i',$lExpensesId);
            $sql->execute();
            $sql->store_result();

            if($sql->num_rows > 0){
                echo 'YES';
            }else{
                echo "Proceed";
            }
        }
        else
        {
            echo "Error".mysqli_connect_error();
        }
?>

I HOPE YOU GOT ANSWERE FOR YOU QUESTION IF YOU HAVE OTHER DOUBTS FEEL FREE AND COMMENT BELOW

Comments

0

All methods are known and many thanks for assistance. My question is that Why I am not able to get proper return from PHP. Below is my code:

var lcl_ExpensesId = $("#IExpensesId").val();
            //alert(lcl_ExpensesId);
        $.ajax({

                    url     :"script_admin-add-category.php",
                    method  :"POST",
                    data    :{lExpensesId:lcl_ExpensesId},
                    success:function(data){
                        if(data=="ok"){
                            alert("Inserted");
                        }else{
                            alert(data);
                        }
                    }
        });
ob_start();

/------------------FUNCTION TO READ ACCOUNTS DROPDOWN EXPENSES LIST -----------------------/

require_once 'db_config.php';
$newlist    = fxn_CONFIGURATION();
$HOST       = $newlist[0];
$DBNAME     = $newlist[1];
$UNAME      = $newlist[2];
$PSWD       = $newlist[3];
$conn   =   mysqli_connect($HOST, $UNAME, $PSWD, $DBNAME);


    //Check connection
    if(!$conn){
        die("Connection Failed: " .mysqli_connect_error());
    }else{
            if(isset($_POST["lExpensesId"])){

                $lExpensesId    = $_POST["lExpensesId"];

                    $Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
                    $query_result = mysqli_query($conn, $Lquery);

                            if(mysqli_num_rows($query_result) > 0){
                                echo "ok";
                            }else{
                                echo "Proceed";
                            }

            }
    }       
mysqli_close($conn);


ob_flush();

As, i am using this AJAX in my one of input keyup method so whatever I will type, each and everytime, it will execute PHP script. I am having a item as FOOD in databse. When i type "F", I got Proceed, "O" - Proceed, "O" - Proceed, "D" - ok.... When I type D, i should get "Inserted" instead of Ok.... This is my doubt that why i m getting this????

4 Comments

@J Salaria if you are using words to search then you should be using SQL LIKE OR WILDCARD QUERY using ExpensesId = '$lExpensesId' will not give you right answere.. $Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId LIKE '%$lExpensesId%'";
I am wondering that you guys are not able to understand the question. I am posting something and you guys are keeping posting something else..... Many thanks for telling me about wildcards. Please, have a look on the question and all post posted by me....
Here, I have got something new in sources breakpoint on if(data=="ok"), I can see the output of data is "Proceed-----" - means enter key simple
HI, As I am getting as ocal Return value : undefined response : "Proceed ↵ ↵ ↵ ↵ ↵" this : Object Instead of "Proceed"... Any one tell me the reason for this
0

The above problem is resolved by using exit() statement in PHP as I am getting five ↵↵↵↵↵ after my values and it means I am having 5 lines of html without closing ?>. So the best way to resolve the issue is to use exit() in PHP as per need

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.