1

I'm sending a JSON with the POST AJAX method to a PHP file and I would like to know how can I check if the JSON is correctly sent before using the json_decode function ?

The isset($_POST['myJSON']) and !empty($_POST['myJSON']) functions are they correct for this case or I cannot use them because my variable is a JSON?

mzavarez
  • 61
  • 8
Lodec
  • 87
  • 1
  • 8
  • 1
    Its correct. With **isset($_POST['myJSON']) ** you check if myJSON key is set regardless of data type. – Rafael Gadotti Bachovas Jul 06 '17 at 17:27
  • why you want to check if your json is ok before? the json_decode return null if your json failed.. `if(isset($_POST['myJSON'])){ $var = json_decode($_POST['myJSON']); if($var == null){ // something wrong? }}` ? – Jean-philippe Emond Jul 06 '17 at 17:38
  • Because when I learned the base of PHP, for the case of a form, I learned to first check if a variable exists and if it's not empty to use it after. So I was thinking, in the case of a JSON that I should make some tests – Lodec Jul 06 '17 at 19:03

1 Answers1

1

You can check by using JavaScript function JSON.parse($val) before sending to php file

If it shows error then your json is not correct

Mahesh Singh Chouhan
  • 2,558
  • 1
  • 16
  • 26
Pritamkumar
  • 682
  • 1
  • 11
  • 30