简体   繁体   中英

jQuery post from ajax loaded div

Can't seem to figure this one out. I have a page where contents of one div is loaded via ajax. That same div has forms in it and after submit it should refresh to show new content. But without reloading the whole page. How is that possible? I am so lost right now.

Also I don't think it's the best style to loop new form for every row but can't think of anything else now. If someone could help me would be awesome.

display.php

<script>
$(document).ready(function() {    
$("#list").load("list.php");
});
</script>
 .................
 other stuff
 .................

  <div id="list"></div>

list.php

<script>
$(document).ready(function() {
$( ".add" ).click(function(event){
 event.preventDefault();
 $.ajax({type:"POST", url:"ajax_post.php",
 data:$("#"+id).serialize(), cache:false, timeout:10000 });

  location.reload();

   }); });
  </script>

 .................
 other stuff
 .................
  <?php
   foreach($list as $l): ?>
  <form id="<?php echo $l->id;?>">
  <input type="text" value="<?php echo $l->pd;?>" name="pd">
  <input type="text" value="<?php echo $l->sf;?>" name="sf">
  <input type="submit" value="<?php echo $l->status;?>" class="add">
   </form>
   <?php
   endforeach; ?>

ajax_post.php is just insert query.

I am not sure to understand your requirements. But way don't you try changing your script code with something like:

<script>
$(document).ready(function() {
  $( ".add" ).click(function(event) {
    event.preventDefault();
    $.ajax( {type:"POST", url:"ajax_post.php",
      data: $("#"+id).serialize(), cache:false, timeout:10000 
      success: function() {
        $("#list").empty()
        $("#list").load("list.php");
      }});
});});
</script>

The intention is to clean the #list element and refill it once the ajax call succeeded.

First, put your form in a separate php file so that we can call it using AJAX, eg forms.php.

When the page loads, you call list.php using $.load()

$('#list').load('list.php')

From my understanding, the list will contain forms, and when the form is submitted, you want the form to reload again without having page refresh. So this is my approach.

$('#list').on('submit', '#formIDfromPHP', function(){
    var data = $(this).serializeArray()
    $.post('ajax_post.php', data, function(result,status){
        console.log(result)
    })
    // Dynamically load it again without refresh.
    $('#list').load('list.php')

    // Or maybe you want to load the form only, hence the external forms.php
    // $('#list').load('form.php')

    // Prevents default form submission behaviour.
    return false;
})

Hope this helps. Cheers!

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