1

I read everywhere about ajax and in all of them the form is in an index.html not an index.php. I can do ajax like them but I want to do it when my form is in a php page without need to action attribute or another php page for sending data. is it possible? how should I do it?

home.php :

        <form method="POST" id="form1">
        <input type="text" name="username" placeholder="username"><hr>  
        <input type="submit" name="submit" value="enter" class="submit"><br><br>
        <div id="al"></div>
        </form>

home.php again :

<?php if(isset($_POST['submit'])) 
{if(isset($_POST['username']){
if(preg_match("/^[a-zA-Z0-9]*$/",$_POST['username'])){
 code...  
    echo "yes";

}else{echo "error!";}
}} ?>  

js.js :

$(document).ready(function(){

$('#form1').submit(function(e){
    e.preventDefault();

    $.ajax({
        type: 'post',
        url: 'home.php',
        data:$('#form1').serialize(),
        success:function(response){
            $('#al').html(response);
        }
    })
})
})

when i use code above my home.php page loads into div with id="al"!!! with the error.

mary
  • 19
  • 5
  • $_POST['username'] is empty probably – ThomasP1988 Sep 22 '21 at 07:28
  • @ThomasP1988 more likely `$_POST['submit']`. Submit buttons don't get picked up by `.serialize()` – Phil Sep 22 '21 at 07:29
  • What **exactly** is not working? What have you tried to resolve the problem? – Nico Haase Sep 22 '21 at 07:30
  • no I fill it tanx @ThomasP1988 – mary Sep 22 '21 at 07:31
  • @nico haase i remove url of my ajax code but again the entire page loads into the box not just the error this is my problem. – mary Sep 22 '21 at 07:33
  • And what have you tried to resolve the problem? – Nico Haase Sep 22 '21 at 07:34
  • i realy don't know what should I do so I asked you to help tanx. @NicoHaase – mary Sep 22 '21 at 07:35
  • I've linked a solution to your `.serialize()` problem at the top of your question. If you don't want your entire page being included in the response, you'll need to handle the response conditionally, eg `if (isset($_POST['submit'])) { /* ajax response... */ ; exit; } /* full page response */` – Phil Sep 22 '21 at 07:35

0 Answers0