user1251698 user1251698 - 6 months ago 21
Javascript Question

jQuery Post and Get Form data

When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.

I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.

Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:

HTML:

<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>

<input type="submit" name="submit" value="Submit"/>
</form>


jQuery:

jQuery('form#basicform').submit(function() {
//code
var hasError = false;

if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){

//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;


});


PHP:

if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];

//no any error
return true;
}

Answer

To be very specific to the question:

How can I get the server response back in the jQuery (to check if there was any server error or not). Here's what I'm trying:

Sound like you're talking about Server-Side validation via jQuery-Ajax.

Well, then you need:

  • Send JavaScript values of the variables to PHP
  • Check if there any error occurred
  • Send result back to JavaScript

So you're saying,

However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if there's no any blank field.

JavaScript/jQuery code:

Take a look at this example:

<script>
$(function()) {
    $("#submit").click(function() {
        $.post('your_php_script.php', {
             //JS Var   //These are is going to be pushed into $_POST
             "name"   : $("#your_name_field").val(),
             "email"  : $("#your_email_f").val()
        }, function(respond) {
           try {
               //If this falls, then respond isn't JSON 
               var result = JSON.parse(respond);

               if ( result.success ) { alert('No errors. OK')  }
           } catch(e) {
               //So we got simple plain text (or even HTML) from server
               //This will be your error "message" 
               $("#some_div").html(respond);
           }
       });
   });
}
</script>

Well, not it's time to look at php one:

<?php

/**
 * Since you're talking about error handling
 * we would keep error messages in some array
 */

$errors = array();

function add_error($msg){
  //@another readers 
  //s, please don't tell me that "global" keyword makes code hard to maintain
  global $errors;
  array_push($errors, $msg);
}

/**
 * Show errors if we have any
 * 
 */
function show_errs(){
   global $errors;
   if ( !empty($errors) ){

     foreach($errors as $error){
        print "<p><li>{$error}</li></p>";
     }
     //indicate that we do have some errors:
     return false;
   }
  //indicate somehow that we don't have errors
  return true;
}



function validate_name($name){
  if ( empty($name) ){
     add_error('Name is empty');   
  }

  //And so on... you can also check the length, regex and so on
  return true;
}


//Now we are going to send back to JavaScript via JSON 

if ( show_errs() ){
   //means no error occured

   $respond = array();
   $respond['success'] = true;
   //Now it's going to evaluate as valid JSON object in javaScript
   die( json_encode($respond) );

} //otherwise some errors will be displayed (as html)
Comments