简体   繁体   中英

How can i update a field / post a form without redirecting or reloading a page?

I have the following code to update just one field in my database which a field called Flag which is a Boolean field. How can I update flag field without reloading the page and redirecting. I tired ajax/Jquery but it works for the first time then stopped when updating the next item in the <li> list, on the next list click it shows ID and Flag value in address bar but not updating record only works when updating the first item in the list.

 <form id="updateflag">
         @if (item.Flag == "Off")
           {
            <input name="ID" type="hidden" value="@item.ID" />  //value changes based on the selected list item
            <input name="Flag" type="hidden" value="true" />//value changes based on the selected list item
            <button type="submit" class="btn btn-primary">&nbsp; @(Localizer["Turn Flag On"]) // value changes based on the selected list item</button>
            }
           @if (item.Flag == "On")
             {
              <input name="ID" type="hidden" value="@item.ID" />//value changes based on the selected list item
              <input name="Flag" type="hidden" value="false" />//value changes based on the selected list item
              <button type="submit" class="btn btn-primary">&nbsp; @(Localizer["Turn Flag Off"])</button>//value changes based on the selected list item
             }
  </form>

//the above form ID field changes

I used the following Ajax/Jquery which works once then on the next try it shown me the posted data in the url but not updating the field

$('#updateflag').submit(function (e) {
    e.preventDefault();
    let Data = $(this).serialize();

    $.post({
        type: 'POST',
        url: "/Customer/updateFlag",
        data: Data,
        success: window.location.reload()
    })
})

what is the best way to update a field value on button click without redirecting and show the updated result instantly?

According to your jquery codes, I found you just bind the click event for the updateflag.

If you have multiple form that the Jquery click binding will just work for the first one.

You could try to set a class for all the forms and use class selector in the jquery like this: <form id="updateflag" class="update"> , jquery: $('.update').submit .

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