With ajax only reload div when submit Form

21,366

Solution 1

give ur div an id... add onsubmit="return false" so that form does not reload or it those nothig on submit

HTML

<div id="divID"> <!-- THE DATA FROM THE FORM VIA PHP --> </div>
<form id='foo' onsubmit="return false">
 <input type='text' name="yourname">
 <input type='submit'>
</form>

display the response in the html to which u gave an id.

JQUERY

$('#foo').submit(function(event){
  $.ajax({
    url: 'index.php',
    type: 'post',
    dataType:'html',   //expect return data as html from server
   data: $('#foo').serialize(),
   success: function(response, textStatus, jqXHR){
      $('#divID').html(response);   //select the id and put the response in the html
    },
   error: function(jqXHR, textStatus, errorThrown){
      console.log('error(s):'+textStatus, errorThrown);
   }
 });
 });

write ur html here... i am just printing the post variable here... u can use <table> (html) as required

index.php

echo $_POST['yourname'].

Solution 2

success:

function(response, textStatus, jqXHR){
      do stuff here
    },

such as: $("#mydiv").html(response);

Share:
21,366
souichiro
Author by

souichiro

Updated on January 24, 2020

Comments

  • souichiro
    souichiro over 4 years


    I have a simple FORM, one INPUT and one SUBMIT Button. The data from there will be sent to a PHP script, which sends this to a db and then puts it inside of an DIV. (with smarty)
    Without the Ajax, it works just fine, the data goes to the db, it will be displayed and so on. But with Ajax, it would be faster and more lightweighted.

    Normally, the submit reloads the Page or redirects to the page I defined.

    But is there a way to just reload the DIV after doing the Submit?

    The html:

    <div> <!-- THE DATA FROM THE FORM VIA PHP --> </div>
    
    <form id='foo'>
    <input type='text'>
    <input type='submit'>
    </form>
    

    The JQuery so far:

    $('#foo').submit(function(event){
      $.ajax({
        url: 'index.html',
        type: 'post,
        data: $('#foo').serialize(),
        success: function(response, textStatus, jqXHR){
          console.log('worked fine');
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log('error(s):'+textStatus, errorThrown);
        }
      });
    });
    
    • 11684
      11684 over 11 years
      You are sending a AJAX request to an HTML page. There can't be a PHP script! But there is a way to only get a div from the returned page, something like: $("div").load("index.html #divYouWantToGet");