简体   繁体   中英

Jquery and ajax call being fired multiple times

Hi I'm making an ajax call to my php side to add or edit in the database. I return three options depending on what was completed. After debugging with firebug I see that after each submit of with add/edit/delete there is more than one call to the php side (doubles each time) I've done a lot reading of trying to unbind and bind which only allows the event handler to execute once but once I do that the submit buttons don't work until the page is reloaded which isn't what I want. Please help!

Javascript page:

    //$('#addAgeGroupForm').trigger("reset");

    //$(document).ready(function()  {
    $(function() {
    $("#dialog").dialog({
    autoOpen:false,
    maxWidth:600,
    maxHeight: 500,
    width: 500,
    height: 350,
    async: false,
    close: function(){ 
    $('#addAgeGroupForm').trigger("reset");
        $.ajax({
            type: "GET",
            url: "/Ajax/ajax_reset_id.php",
            async: false,
            success: function(html){
                $("#responce_event").html(html);
        }
    });
    }

    });
    $("#addAgeGroup").on("click", function() 
    {

    $("#dialog").dialog("open");
    });



    $("#addAgeGroupForm").submit(function(e)
    { 
    e.preventDefault();
    var postData = jQuery(this).serialize();
    var data = "";
    $("#dialog").dialog("close")
    $.ajax({
    type: "POST",
    url: "/Add/AddAgeGroups.php",
    dataType: 'json',
    async: false,
    data: postData,
    success: function(result){
    data = result;
    $('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
    if (data==1)
    {
        alert("Error: Please fill in all fields");
    }

    else if(data==2)
    {
        alert("Error: Duplicate Age Group entry for this Meet");
    }
    else
    {
     alert(data); 
     //alert("success");
     $('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
     }
    },
    error: function(jqXHR, exception) {
    if (jqXHR.status === 0) {
    alert('Not connect.\n Verify Network.');
    } else if (jqXHR.status == 404) {
    alert('Requested page not found. [404]');
    } else if (jqXHR.status == 500) {
    alert('Internal Server Error [500].');
    } else if (exception === 'parsererror') {
    alert('Requested JSON parse failed.');
    } else if (exception === 'timeout') {
    alert('Time out error.');
    } else if (exception === 'abort') {
    alert('Ajax request aborted.');
    } else {
    alert('Uncaught Error.\n' + jqXHR.responseText);
    }

    }



    });

    }); 


    $('[id^="editAgeGroup"]').submit(function(e)
    { 
    e.preventDefault();
    var editData = jQuery(this).serialize();
    $.ajax({
    type: "POST",
    url: "/Get/GetAgeGroup.php",
    async: false,
    dataType: 'json',
    data: editData,
    success: function(data){

    var form = document.forms['addAgeGroupForm'];
    form.id.value=data.id;
    form.agegroup.value=data.agegroup;
    form.abbrev.value=data.abbrev;
    form.sort.value=data.sort;


    }


    });

    $("#dialog").dialog("open");

    });

    $("#dialog2").dialog({
    autoOpen:false,
    maxWidth:600,
    maxHeight: 500,
    width: 500,
    height: 300,
    async: false,
    close: function(){ 
    $('#deleteAgeGroupForm').trigger("reset");

            $.ajax({
            type: "GET",
            url: "/Ajax/Delete/ajax_delete_ageGroup.php",
            async: false,
            success: function(html){
                $("#responce_delete").html(html);
        }
    });

    }

    });



    $('[id^="deleteAgeGroup"]').submit(function(e)
    { 
    e.preventDefault();
    var deleteData = jQuery(this).serialize();
    $.ajax({
    type: "POST",
    url: "/Get/GetAgeGroup.php",
    dataType: 'json',
    data: deleteData,
    success: function(data){

    var form = document.forms['deleteAgeGroupForm'];
    var id = data.id;
    var name = data.agegroup;
    form.age_group_id.value = data.id;
    $.ajax({
            type: "GET",
            url: "/Ajax/Delete/ajax_delete_ageGroup.php?id="+id+"&name="+name,
            async: false,
            success: function(html){
                $("#responce_delete").html(html);

    }


    });

    }


    });

    $("#dialog2").dialog("open");

    });

    $("#deleteAgeGroupForm").submit(function(e)
    { 
    e.preventDefault();
    var postData = jQuery(this).serialize();
    var editData = jQuery(this).serialize();
    $("#dialog2").dialog("close")
    $.ajax({
        type: "POST",
        url: "/Get/GetAgeGroup.php",
        dataType: 'json',
        async: false,
        data: editData,
        success: function(data){
            var id = data.id;
            //alert(data.id);
            //alert(data.schoolname);
            $.ajax({
                type: "Get",
                url: "Delete/DeleteAgeGroup.php?id="+id,
                dataType: 'json',
                async: false,
                data: postData,
                success: function(data){
                 //alert(data); 
                //alert("success");
                $('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
                },
                error: function(jqXHR, exception) {
                if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
                } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
                } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
                } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                alert('Time out error.');
                } else if (exception === 'abort') {
                alert('Ajax request aborted.');
                } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
                }
                }
            }); 
        }}); 
    });
/******************/
    })
function updateTable()
{
    $('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
}

PHP side:

        session_start();
    if($_SESSION["logged_in"] == 0)
        header("Location: ****");
    else if($_SESSION["type"] == "general")
        header("Location: ****");
    else
    {

    $agegroup = addslashes($_POST['agegroup']);
    $abbrev = addslashes($_POST['abbrev']);
    $sort = addslashes($_POST['sort']);
    $id = $_POST['id'];
    $managerID = $_SESSION["manager_id"];
    $meetID = $_SESSION["meet_id"];

        $db = mysqli_connect("****", "****", "****","****");
    if(!$db){
      exit("Error in database connection");
    }

    else

    {

    $exists =  mysqli_query($db,"SELECT * FROM `AgeGroup` WHERE `AgeGroupLong` = '$agegroup' AND `AgeGroupShort` = '$abbrev' AND `ManagerID` = $managerID AND `MeetID` = $meetID ");
    $row = mysqli_fetch_array($exists);


    if($_POST['agegroup']=="" || $_POST['abbrev']=="" || $meetID=="")
    {
    //exit(json_encode(1));
    echo json_encode(1);

    }

    else if($id == "" && $row > 0)
    {
        echo json_encode(2);
    }

    else
    {


    $result = mysqli_query($db, "SELECT * FROM `AgeGroup` WHERE `AgeGroupLong`='$agegroup' AND `AgeGroupShort` = '$abbrev'");
        //$row = mysqli_fetch_array($result);

    if($id == "")
        {

        mysqli_query($db, "INSERT INTO `AgeGroup` (`AgeGroupLong`,`AgeGroupShort`,`Sort`, `ManagerID`, `MeetID`) VALUES ('$agegroup', '$abbrev', $sort, $managerID, $meetID)");


        }

        else
        {

        $AgeGroup_id = $row['AgeGroupID'];


        mysqli_query($db, "UPDATE `AgeGroup` SET `AgeGroupLong`='$agegroup',`AgeGroupShort` = '$abbrev', `Sort`=$sort WHERE `AgeGroupID`=$id");

        }

    $ageGroup = array
    (
       'agegroup' => stripslashes($agegroup),
      'abbrev' => stripslashes($abbrev),
      'sort' => stripslashes($sort)

    );

    echo json_encode($ageGroup);

    }
    }
    }

    mysql_close($db);

declare global variable and make ajax request one time:-

var is_request_sent = false;
function like_post(wall_post,obj)
{
    if(is_request_sent == false)
    {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: base_url+"ajax_timeline/like_post",
            data: "action=like_post&wall_post_id="+wall_post,
            success: function(result){//alert(result);alert('here');
                is_request_sent = false;

           },
            error: function(a,b,c)
            {
                is_request_sent = false;
                //fbalert('Error', 'Error occured. Please try again.');
            },
            beforeSend: function(jqXHR, plain_jqXHR){
                is_request_sent = jqXHR;
                 // Handle the beforeSend event          
            },
            complete: function(){
                is_request_sent = false;
             // Handle the complete event
            }
        });
    }
}

i hope this will help you

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