简体   繁体   中英

update db by ajax without refreshing the page codeigniter

I'm trying to update a row in a table by query and ajax.

I succeeded, but I have one problem.

The page that I have is a form that has one input; the input is the id for the row in the DB. After I submit the form I update the row, but if I insert another id in the input then it's not working until refreshing the page again. Meaning: I must refresh the page again to update another row in the table. I'm using codeigniter.

This is my code:

<form method="POST" action="" >
    <fieldset data-role="controlgroup">
        <input type="text" name="id" id="id" value=""
        <input type="submit" name="submit-choice-a1" id="submit-choice-b1" value="submit"  />
    </fieldset>
</form>

and the JS is:

<script type="text/javascript">
$(function() {

    $("#submit-choice-b1").click(function(e) {

        var id = $('#id').val();
        var result = confirm("are you sure ?");
        if (result==true) {

            $.ajax({
                url: "the url that have the page with the update function",
                success: function(xhr){
                    alert('updated');
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(xhr.responseText);
                }
            });
        }
    });
});
</script>

I see 2 ways:

1) Dont use <form> tag, just get the information and send it with jQuery ajax in data parameter.

$.ajax({
url: "the url",
type: "post",
data: {
    id: 68,//Your field id/class, got it with $(selector).attr("id") or $(selector).attr("class");
    anotherKey: anotherValue
    etc...
}
});

2) modify the form using onsubmit attribute

<form method="post" onsubmit="return sent();">

the end of the sent() function, you need to add "return false" to tell to the form (dont reload the page)

function sent() {
    ..your ajax implementation here..
    return false;
}

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