最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - if else statement in AJAX success - Stack Overflow

programmeradmin4浏览0评论

This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?

AJAX

$( "#frm_add" ).on('submit',(function(e) {

                e.preventDefault();
                var  img= new FormData(this);
                datas = $("#frm_add").serializeArray();
                $.each(datas,function(key,input){
                    img.append(input.name,input.value);
                });
                $.ajax({
                    url: "response_categories.php", // Url to which the request is send
                    type: "POST",             // Type of request to be send, called as method
                    //data:new FormData(this),
                    data:img,
                    // data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                    contentType: false,       // The content type used when sending data to the server.
                    cache: false,             // To unable request pages to be cached
                    processData: false,        // To send DOMDocument or non processed data file it is set to false
                    success: function (data)   // A function to be called if request succeeds
                    {

                        if(data == true)
                        {
                            $('#add_model').modal('hide');
                            $("#categories_grid").bootgrid('reload');
                        }
                        else
                        {
                            $("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
                        }

                    }

                });
            }));

php

  function insertCategories($params)
    {

        $fileName = $_FILES['cat_image']['name'];
        $name = $params['cat_name'];
        $type = $params['cat_type'];
        $switch = $params['cat_switch'];
        $chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
       if(mysqli_num_rows($chk)==0)
       {
           $sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch');  ";
           echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");


           if ($result) {
               if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
                   echo  $fileName . " <span id='invalid'><b>already exists.</b></span> ";
               } else {
                   $sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
                   $targetPath = "images/" .$fileName; // Target path where file is to be stored
                   move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
               }

           }
           echo json_encode($result);

       }



    }

This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?

AJAX

$( "#frm_add" ).on('submit',(function(e) {

                e.preventDefault();
                var  img= new FormData(this);
                datas = $("#frm_add").serializeArray();
                $.each(datas,function(key,input){
                    img.append(input.name,input.value);
                });
                $.ajax({
                    url: "response_categories.php", // Url to which the request is send
                    type: "POST",             // Type of request to be send, called as method
                    //data:new FormData(this),
                    data:img,
                    // data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                    contentType: false,       // The content type used when sending data to the server.
                    cache: false,             // To unable request pages to be cached
                    processData: false,        // To send DOMDocument or non processed data file it is set to false
                    success: function (data)   // A function to be called if request succeeds
                    {

                        if(data == true)
                        {
                            $('#add_model').modal('hide');
                            $("#categories_grid").bootgrid('reload');
                        }
                        else
                        {
                            $("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
                        }

                    }

                });
            }));

php

  function insertCategories($params)
    {

        $fileName = $_FILES['cat_image']['name'];
        $name = $params['cat_name'];
        $type = $params['cat_type'];
        $switch = $params['cat_switch'];
        $chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
       if(mysqli_num_rows($chk)==0)
       {
           $sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch');  ";
           echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");


           if ($result) {
               if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
                   echo  $fileName . " <span id='invalid'><b>already exists.</b></span> ";
               } else {
                   $sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
                   $targetPath = "images/" .$fileName; // Target path where file is to be stored
                   move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
               }

           }
           echo json_encode($result);

       }



    }
Share Improve this question asked Jun 30, 2017 at 16:24 tabiatabia 6352 gold badges12 silver badges34 bronze badges 7
  • Is that your full PHP code? insertCategories is never called if that is the case.. – chris85 Commented Jun 30, 2017 at 16:26
  • 1 you have 2 echo . If sending json need to expect json in ajax and only send one echo. Will never be true either – charlietfl Commented Jun 30, 2017 at 16:31
  • 1 do a console.log(data) before your if statement to check what value you are getting back – Karthik Ganesan Commented Jun 30, 2017 at 16:32
  • 1 You need to check the difference between loose equality (==) and strict equality (===). Your logic right now is "if anything es back from the server trigger the truth condition." – cwallenpoole Commented Jun 30, 2017 at 16:40
  • 1 if you do console.log(data) what is ing back? – Joe Lissner Commented Jun 30, 2017 at 16:54
 |  Show 2 more ments

2 Answers 2

Reset to default 1

Add the error mand in your ajax call to execute if the mand fails or returns no data in general

$.ajax({
  url: "response_categories.php", // Url to which the request is send
  type: "POST",             // Type of request to be send, called as method
  data:img,
  contentType: false,       // The content type used when sending data to the server.
  cache: false,             // To unable request pages to be cached
  processData: false,        // To send DOMDocument or non processed data file it is set to false
  success: function (data),   // A function to be called if request succeeds
    {
      if(data)
        {
          $('#add_model').modal('hide');
          $("#categories_grid").bootgrid('reload');
        }
        else
          {
            $("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
          }

    }
  error: function (data)
    {
      $("#namerr".html("<p id='error' style='color:red'>"+data+"</p>");
    }
});

I think You have problem with response convention: Sometimes You call die() method (PHP: 12 line), sometimes You call json_endcode() (PHP: 25 line), sometimes echo with plain string.

In this type of actions You should:

  1. Always output JSON from backend script. Mixing response types is really pain in the ass, it's hard to parse and test.
  2. Use response object with uniform structure - that might help with building plex applications and easy to modify

Example pseudocode: PHP

if($success) {
    die(json_encode([
            'error' => false, 
            'message' => 'Thank You', 
            'data' => $some_extra_data
        ]));
} else {
    die(json_encode([
            'error' => true, 
            'message' => 'Sorry', 
            'data' => $some_extra_data
        ]));    
}

Then in ajax.success() method, its really easy to handle:

success: function (data) {

    try {

        var response = JSON.parse(data)

        if(response.error == true) {
            $('#nameerr').text(response.message)
        } else {
            $('#add_model').modal('hide');
            $("#categories_grid").bootgrid('reload');
        }

    } catch (err) {
        alert('Sorry. Server response is malformed.')
    }
}   
发布评论

评论列表(0)

  1. 暂无评论