1

I want to validate form field on submit and if ajax returns message to block the form submit. Here is the js code I have:

$('form.p_form').submit(function (){
var description = $.trim($('#f9').val());
var aa = $.post("checkdescription.php",{
     description: description
 },
 function(data, status){
    if(data !== ''){
    return data;
    }
 });

 if(aa){
 alert(aa);
 return false;
 }
});

but the code above always returns [object XMLHttpRequest] - How to read the mesage returned?

basicaly in checkdescription.php I have php code that validates the field and if there is error it puts in:

$return ='error message'; 

//file ends with:

echo json_encode($return);

how can I read the exact message received from response?

thank you in advance !

I also tried this:

    $('form.p_form').submit(function (){
var description = $.trim($('#f9').val());
var aa = $.post("checkdescription.php",{
     description: description
 },
 function(data, status){
    if(data !== ''){
    return false;
    }
 });

but it doesnt prevent form submit..

Europeuser
  • 934
  • 1
  • 9
  • 32

1 Answers1

0

It's required that you also set PHP header to application/json because, this output can be easily read by JQuery's ajax or $.post function, more a structured JSON output is also needed, here's how you should do it...

for PHP

<?php
$output = array('status'=>'true','message'=>'your error message');
//Setting up the output MIME type
header('Content-Type:application/json;');
//Providing Structured Output
echo json_encode($output);

this will be easily read by ajax...

For Javascript

$('form.p_form').submit(function (){
var description = $.trim($('#f9').val());
var aa = $.post("checkdescription.php",{
description: description
},
 function(data, status){
   return data['status'];
   }
});
Marmik Bhatt
  • 607
  • 4
  • 16