简体   繁体   中英

jQuery ajax fails on form submit with link

In the sequence of this question , the content I've got in a form is now updating the DB. However, when I click this link

<a onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>

The jQuery .ajax function fires the error callback AND updates the DB with the information as well.

Here's the code

function doUpdate()
{
              e.preventDefault();
              $.ajax({
                type: "POST",
                data: $("#validation").serialize(),
                cache: false,
                url:"modules/user/updateuser.php",
                success : function(data){
                    $("#response-update").html(data);
                },
                error:  function(data){
                    $("#response-update").html("Erro na submissão");
                }                
           });
          }

I'd like to get the success callback, in order to display a nice message to the user when it saves the data.

However if I simply do this

 <a href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>
 <script>
 $(function(){
 $('#commit-changes').click(function(e){
              e.preventDefault();
              $.ajax({
                type: "POST",
                data: $("#validation").serialize(),
                cache: false,
                url:"modules/user/updateuser.php",
                success : function(data){
                    $("#response-update").html(data);
                },
                error:  function(data){
                    $("#response-update").html("Erro na submissão");
                }                
           });
          });
 });
 </script>

The "submition" doesn't work at all.

How can I solve this problem? Been stuck with this part for days! :(

EDIT - HTML for the form (This is also a response loaded in the begging of the page)

  $response.='<form id="validation" method="post"> 
                                <fieldset >
                                <input type="hidden" name="user_id" value="'.$_POST['user_id'].'"/>
                                <legend>Actualizar Dados Utilizador</legend>
                                      <div class="section ">
                                      <label>Nome<small>Insira o seu nome</small></label>   
                                      <div> 
                                      <input type="text" class="validate[required,custom[onlyLetterSp]] large" name="nome" id="f_required" value="'.utf8_encode($rcs_user->nome).'">
                                      </div>                                      
                                      </div>';
 $response.='<div class="section ">
                                      <label> Email<small>Insira o seu email</small></label>   
                                      <div> 
                                      <input type="text" class="validate[required,custom[email]] large" name="email" id="e_required" value="'.  utf8_encode($rcs_user->email).'">
                                      </div>
                                      </div>';

 $response.= '<div class="section">
                                        <label>Permissões<small>Seleccione o tipo de utilizador </small></label>   
                                        <div>
                                            <select class="medium" name="role">

                                                       '.$role.'                                                 

                                            </select>       
                                      </div>
                                      </div>                                      
                                     <div class="section">
                                            <label>Activo<small>Activar utilizador</small></label>


                                         <div>
                                            '.$activo.'
                                            <span class="f_help">ON / OFF  </span> 
                                        </div>
                                  </div>

                                  <div class="section last">
                                  <div>
                                     <a onclick="return doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a><a class="uibutton special"   onClick="ResetForm()" title="Limpar Formulário"   >Limpar Formulário</a>
                                 </div>
                                 </div>

                                </fieldset></form>

Have you put your jQuery code inside a document.ready handler?

jQuery(function ($) {
    // put jQuery here
});

The first example will work without document.ready (but doesn't make much sense because you're using jQuery anyway). The second won't.

In order to behave doUpdate() function as expected, Try this

modify the anchor tag onclick attribute to

<a onclick="return doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>

and also change the doUpdate function to

function doUpdate()
{
  $.ajax({
     type: "POST",
     data: $("#validation").serialize(),
     cache: false,
     url:"modules/user/updateuser.php",
     success : function(data){
         $("#response-update").html(data);
     },
     error:  function(data){
         $("#response-update").html("Erro na submissão");
     }                
  });

  return false;
}

The jquery ajax success/error callbacks will fire based upon whether the POST request was received or not, it has nothing to do with what actually happens within the file you have posted to. It's strange you would get the error callback and have the database updated, but you can try and have the php file you are posting to give a response and then run success/error based upon that response.

In your php file you could have something like this:

$testQuery = "QUERY STRING HERE";
if(!mysql_query($testQuery))
{
    echo "error";
    exit;
}
else
{
    echo "sucess";
    exit;
}

And then in your doUpdate function you can run the success callback and output based upon the html

    function doUpdate()
{
              e.preventDefault();
              $.ajax({
                type: "POST",
                data: $("#validation").serialize(),
                cache: false,
                url:"modules/user/updateuser.php",
                success : function(data){
                   if(data == "success")
                   {
                       $("#response-update").html(data);
                   }
                   else
                   {
                       $("#response-update").html("Erro na submissão");
                   }                    
                }            
           });
          }

You can also use the "complete" callback which will fire even if the POST was not received, that wont tell you anything other than the function has been ran though

I've got a solution. Not the prettiest, as I wanted a pure jQuery solution, but, it works well.

Just needed to change the

<a onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>

To

<input onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form" value="Gravar" />

And now it works with the sucess callback firing.

Thanks for all the help on this.

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