javascript - I want to load php with a message to hide a form after submit but event.preventDefault(); ruins an "already exists" check on my .php file -


after submitting there must exist 3 possible states:

  1. data saved , php message loaded onto form was.
  2. data exists , load different php informing user.
  3. an error occurred, show alert asking user please try again.

this submit .php looks like:

$test="select * launchpage email_launchpage ='$email'"; $testing=$link->query($test); $alreadyexists=$testing->num_rows;  if($alreadyexists ==1){     echo "<script>alert('already exists');window.history.go(-1);</script>"; } else{     $sqlinsertlistingtype="insert launchpage(email_launchpage,language_launchpage) values('".$email."','".$language."')";     $link->query($sqlinsertlistingtype);     echo "<script>alert('saved');window.history.go(-1);</script>"; } 

it works fine on it's own , try @ ajax request submit:

$(document).on("submit","#form",function(event){     event.preventdefault();     var formurl = $(this).attr("action");     var formtype = $(this).attr("method");     var formdata = $(this).serialize();     $.ajax({         url: formurl,         type: formtype,         data: formdata,         success:function(data, textstatus, jqxhr){             console.log('went through ajax');         },         error: function(jqxhr, textstatus, errorthrown){             console.log("i've ruined something");         }     }); }); 

which works, because of .preventdefault(); "don't" know if data saved or not.

i have no idea should try bring these 2 together, or if there's better way this...

i'm guessing must rather easy solve, i'm missing haven't learned yet.

don't return js or other html. return json:

<?php  ... process form data if (processing succeeds) {    $msg = array(        'code' = 1,        'message' = 'success'    ); } else {    $msg = array(        'code' => 0,        'message' => 'failed, dun blowned up'    ); } echo json_encode($msg); 

then in success handler:

success: function(data) {         if (data.code == 1) {              do_success_stuff();         } else {             alert('requested failed error #' + data.code + " , message '" + data.message + "'");         }  } 

Comments