Barry White
Barry White

Reputation: 29

Submitting form on same loaded page if the page is loaded via ajax

So i have a PHP page that is loaded via AJAX using the .load method.

This is then displayed on my page, however i need to be able to submit the form that is located on my second page that im loading using .load, submit this form and process the data on the same page without it reloading.

I'm very new to javascript and AJAX so i've no idea if i'm evening doing this correct using .load()

Any help would be appreciated.

page 1 is the following:

        
 <button onclick="Test()" type="button">Load Content</button>
 
 
 <div class="box" id="box" name="box">
        </div>
    
    
    
        <script>
function Test(id) {     
$( "#box" ).load( "test.php?id=" + id );
}
</script>

The second page which is test.php houses the following


     <form id="enrolemployee" action="" method="post">
     
     
         <div class="form-group">
    <label>Test</label>
    <input type="text" class="form-control" id="Test" name="Test" placeholder="Test">
  </div>
  
  
    
         <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
          <button  type="submit" class="btn btn-outline-custom">Submit</button>
        
        
     </form>


Now to submit the form on test.php i use a custom token class to generate a random hash per form submit so i can validate the data on the same page and process it through my database.

is this possible to do? or do i need to have my form then post the data through a different page?

Basically i need the entire thing to stay on PAGE 1, process the form like it normally should whilst the persons page does not reload and is always static on page 1, this should never redirect to test.php

Thankyou.

Upvotes: 0

Views: 40

Answers (1)

Hakan Kose
Hakan Kose

Reputation: 1656

You can do it like

index.php

<button onclick="Test('10')" type="button">Load Content</button>
<div class="box" id="box" name="box">
</div>
<script src="//code.jquery.com/jquery-latest.js"></script>
<script>
    function Test(id) {
        $("#box").load("test.php?id=" + id);
    }

</script>

test.php

<form id="enrolemployee" action="" method="post">
    <div class="form-group">
        <label>Test</label>
        <input type="text" class="form-control" id="Test" name="Test" placeholder="Test">
    </div>
    <input type="hidden" name="token" value="">
    <button type="submit" class="btn btn-outline-custom">Submit</button>
</form>
<script>
    $("#enrolemployee").on('click', e => {
        // Avoid reloading page
        e.preventDefault();
        console.log(<?php echo $_GET['id']; ?>);
    })

</script>

Upvotes: 1

Related Questions