简体   繁体   中英

How can I call second jquery/ajax request?

Well, I'm validating my html form with jquery/ajax request. It's process by add_contact_process.php page. In this page if data (family or given name) is exit then I'm showing a message with a button which value is Yes and Cancel .

So
1) If Yes button is press I want to call a another jquery/ajax request which save the data to db.
2) If Cancel button is press then I want to remove/hide the message.

Can someone suggest me how can I do this ?

Html form code :

<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 page :

<?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);        
?>
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); 
                        }

                   }
                  });
                });

You should define the second Ajax call in first Ajax call complete method. By default Ajax call is asynchronous, it will start executing the code or statements in success method with out waiting for response from the server. you code should me like this

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

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

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

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