如何调用第二个jquery / ajax请求?

时间:2014-11-11 05:56:42

标签: javascript php jquery

好吧,我用jquery / ajax请求验证我的html表单。它是add_contact_process.php页面的处理过程。在此页面中,如果数据(家庭或给定名称)退出,则我会显示一条消息,其中的按钮值为是和取消

因此
1)如果按按钮,我想调用另一个jquery / ajax请求,将数据保存到db。
2)如果按取消按钮,则我想删除/隐藏消息。

有人可以建议我怎么做?

Html表单代码

<form id="addcontact">
<table width="450" border="0" cellspacing="0" cellpadding="0">  
<tr>
    <td>Family name</td>
    <td><input type="text" name="family_name" maxlength="50" placeholder="Family name"/></td>
</tr>
<tr>
    <td>Given name</td>
    <td><input type="text" name="given_name"  maxlength="30"placeholder="Given name"/></td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="submit" value="Add Contact" class="submit"></td>
</tr>
</table>
</form>    

<script>
$("#addcontact").submit(function(event) {
    event.preventDefault();
    $.ajax({
    type: 'POST',
    url: 'add_contact_process.php',
    data: $(this).serialize(),
    dataType: 'json',      

    success: function (data) {
        $('#success').html('');
        $('#success').show();
        $.each( data, function( key, value ) {          
        if(key !== 'error' && key !== 'last_id')  {
           $('#success').append('<p>'+value+'</p>');            
           }  
        }); 

        if( ! data.error) {     
            $('#hide').hide();              
             setTimeout(function () {
             $('input[type=submit]').attr('disabled', false);        
             var last_id = data.last_id;             
             window.location.href = "../index.php?redcdid="+last_id; 
        },     5000); 
            }

       }
      });
    });
$('#success').delay(3000).fadeOut('slow');      
</script>

add_contact_process.php页面:

<?php
$family_name = inputvalid(ucfirst($_POST['family_name']));
$given_name = inputvalid(ucfirst($_POST['given_name']));

$exitfname = mysqli_query($link, "SELECT family_name FROM contact_details WHERE family_name = '$family_name'");
$numfname = mysqli_num_rows($exitfname);

$exitgname = mysqli_query($link, "SELECT given_name FROM contact_details WHERE given_name = '$given_name'");
$numgname = mysqli_num_rows($exitgname);

$msg =  array();
$msg['error'] = false;

if(empty($family_name)){
    $msg[] = "<div class='error'>Family name required.</div>";  
    $msg['error'] = true;                           
}

if(strlen($given_name) > 30){
    $msg[] = "<div class='error'>Given name is too big.</div>"; 
    $msg['error'] = true;   
}

// If error is not found            
if($msg['error'] === false){
    if(!empty($family_name) && $numfname >= 1 || !empty($given_name) && $numgname >= 1){
        $msg[] = "<div class='error'>A contact with this name exists. Do you wish to continue adding this new contact?                  
        <input type='submit' name='warning' value='yes' id='yes' class='submit' style='margin:0px;'/>&nbsp;
        <input type='submit' name='warning' value='Cancel' id='cancel' class='submit' style='margin:0px;'/>         
        </div>";
        $msg['error'] = true;           
    }else{      
        $query_2 = "INSERT INTO contact_details (family_name, given_name) VALUES('$family_name', '$given_name')";
        $query_2 =  mysqli_query($link, $query_2);
        $last_id =  mysqli_insert_id($link);

        if($query_2){
            $msg[] = "<div class='success'><strong>Successfully added a new contact</strong>. </div>";          
            $msg['last_id'] = "$last_id";
            $another = "close";
        }else{
            $msg[] = "<div class='success'>Sorry we can not add a new contact details. </div>";
            $msg[] .=  mysqli_error();          
            $another = "close";
        }       
    }   
}       
echo  json_encode($msg);        
?>

2 个答案:

答案 0 :(得分:0)

Call Second ajax within success
          <script>
            $("#addcontact").submit(function(event) {
                event.preventDefault();
                $.ajax({
                type: 'POST',
                url: 'add_contact_process.php',
                data: $(this).serialize(),
                dataType: 'json',      

                success: function (data) {
                    $('#success').html('');
                    $('#success').show();
                    $.each( data, function( key, value ) {          
                    if(key !== 'error' && key !== 'last_id')  {
                       $('#success').append('<p>'+value+'</p>');            
                       }
          /*------------------------------------------------------------------*/  
                       if(confirm('Write your message here')){
                       /* Second ajax after clicking ok on confirm box */
                             $.ajax({
                                url : 'Second URL',
                                method :'POST',
                                data : {'data1':data1}, 
                                success:function(response){
                                        // code after success       
                                },
                                error: function(e){
                                    return false;
                                }
                            });                 
                        }else{
                            $('#success').hide();
                            $('#success').hide();
                        }
        /*----------------------------------------------------------*/

                    }); 

                    if( ! data.error) {     
                        $('#hide').hide();              
                         setTimeout(function () {
                         $('input[type=submit]').attr('disabled', false);        
                         var last_id = data.last_id;             
                         window.location.href = "../index.php?redcdid="+last_id; 
                    },     5000); 
                        }

                   }
                  });
                });

答案 1 :(得分:0)

您应该在第一个Ajax调用完成方法中定义第二个Ajax调用。默认情况下,Ajax调用是异步的,它将以成功方法开始执行代码或语句,而不等待服务器的响应。你的代码应该像我这样

$.ajax({
            type: 'POST',
            url: 'add_contact_process.php',
            data: $(this).serialize(),
            dataType: 'json',      

            success: function (data) {
               // some code            
                   },

            complete:function () {
           //you second ajax call
            }