Search code examples
javascriptjsonajaxconfirmation

Check any data after confirmation message using JSON


I want to make the data alert successfully saved or fail after the user selects on the confirmation message. In this case data checking occurs after the user confirms the message I made.

This is my Javascript Code :

$('#add-btn').on('click', function(event){
  var confirmation = confirm("Do you want to save ?");
  if (confirmation == true) {
    var code = $('#code').val();
    var name = $('#name').val();
    var unit = $('#unit').val();
    var price_code = $('#price_code').val();
    var type = $('#type').val();
    var final = $('#final').val();
    var dataString = 'code=' +code+ '&unit=' +unit+ '&price_code=' +price_code+ '&type=' +type;
    if (code != '' && name != '' && unit != '' && price_code != '' && type != '' && final != ''){
      event.preventDefault();
      $.ajax({
        type: "POST",
        url: "../public/process/add_data.php",
        data: dataString,
        dataType: "json",
        cache: false,
        success: function(data){
          if(data.status == 'success'){
            alert("Success !");
          }
          else if(data.status == 'error'){
            alert("Data already used !");
          }
        }
      });
    }
    else{
      alert('Please fill all fields !');
    }
  }
});

All input success to save but the alert cannot show.


Solution

  • finally I find my solution. I'm sorry for my carelessness. That happened because my variable dataString did not complete. It should be :

    var dataString = 'code=' +code+ '&name=' +name+ '&unit=' +unit+
    '&price_code=' +price_code+ '&type=' +type+ '&final=' +final;
    

    Thank you all for your kindness :-)