简体   繁体   中英

How to retrieve an error message in the php using json?

I have the following php code:

if (($name == "") || ($email == "") || ($telephone == "") || ($username == "") ||       ($password == "")) {       

$ret = Array();
$ret["msg"] = "some input is missing";

echo json_encode($ret);
} elseif (!preg_match($pattern_email, $email)) {

$ret = Array();
$ret["msg"] = "email format is incorrect";

echo json_encode($ret);
} elseif (!preg_match($pattern_phone, $telephone)){

$ret = Array();
$ret["msg"] = "telephone should be all digits";

echo json_encode($ret);
}

and the following javascript:

    $(document).ready(function(){


$("#save").click(function(){

     var name = $('#name').val();
     var email = $('#email').val();
     var telephone = $('#telephone').val();
     var username = $('#username').val();
     var password = $('#password').val(); 

  $.ajax({
   type:'POST',
   url: 'contactData.php',

  dataType: "json",
   data:{"name":name,"telephone":telephone,"email":email, "username":username, "password":password},
   success: function(data) {
       //alert(data);
       var result = JSON.parse(data);
       $("#validate").html(data.msg);    


   }        
});

});
});

the aim of the program is to output an error message using json whenever one of the conditions is true. but I'm not retrieving any data and the program shows an error at the statement
var result = JSON.parse(data);
Can anyone help plz???

First in your PHP instead of

$errorMsg = '{"msg":"some input is missing"}';

Use

$ret = Array();
$ret["msg"] = "some input is missing";

echo json_encode($ret);

In your javascript

add in your ajax request

dataType: "json",

Your Parse will work now

You need create one array. After all validation in the end of code.

$data['respone'] = $errormsg;
echo json_encode($data);
exit();

In javascript you need to parse json object. And check if oject.element == '' then file else something wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM