tabia
tabia

Reputation: 635

if else statement in AJAX success

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);

       }



    }

Upvotes: 2

Views: 23988

Answers (2)

Dariusz Majchrzak
Dariusz Majchrzak

Reputation: 1237

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 complex 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.')
    }
}   

Upvotes: 0

Surreal
Surreal

Reputation: 1047

Add the error command in your ajax call to execute if the command 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>");
    }
});

Upvotes: 1

Related Questions