M.F
M.F

Reputation: 143

Jquery problems with getting my Form to display successully sent or error messages correctly

I have this code in a .js file that adjusts my form display when submitted by closing the form then displaying 'Message Successfully Sent' text or showing error messages like 'Error: message needs to be more than 200 characters or please insert a valid email address' etc.

The Form closing when the message is successfully sent works well and leaves just the message 'Message Successfully Sent', but the Form closing when there is an error does not work well because there is no way to return to the message to correct it.

Can anybody help me adapt the code so that the form only slidesup if the message is successfully sent, otherwise if there is an error the form stays visible but has the error message below, this way you can see the error and make the change in the form above, then press the send button again for a second attempt.

Here is code that I think needs changing, I am assuming it might be another state different than success: for the error stage?:

submitHandler: function(form) {
   $("#send").attr("value", "Sending...");
   $(form).ajaxSubmit({
      success: function(responseText, statusText, xhr, $form) {
         $(form).slideUp("fast");
          $("#response").html(responseText + "<br/>").hide().slideDown("fast");
      }
   });
   return false;
}

#send is the send button and #response is the div that displays the response text.

I hope somebody can help. thanks.

Upvotes: 0

Views: 172

Answers (1)

Barmar
Barmar

Reputation: 781626

In the PHP script, return the result in JSON:

$result = array('error' => $error, 'message' => $response);
echo json_encode($result);

In jQuery, do:

$(form).ajaxSubmit({
    dataType: 'json',
    success: function(response, statusText, xhr, $form) {
        if (!response.error) {
            $(form).slideUp("fast");
        }
        $("#response").html(response.message + "<br/>").hide().slideDown("fast");
    }
 });

Upvotes: 1

Related Questions