Jarla Jarla - 6 months ago 11
Ajax Question

How can I send a form via Ajax and php?

I want to submit some data via Ajax:

index.php:

<form>
<input name="name" value="Frank"><br>
<input name="submit" type="submit" value="Submit">
</form>

<div id="result"></div>

<script>
$(document).on('submit','form',function(e){
e.preventDefault();
$form = $(this);
submit($form);
});

function submit($form){
var formdata = new FormData($form[0]);
var request = new XMLHttpRequest();
request.open("post", "action.php");
request.send(formdata);
$.ajax({url: "action.php", success: function(result){
$("#result").html(result);
}});
}
</script>


action.php:

echo "hello ";
echo $_POST["name"];


My result:

hello


My expected result:

hello Frank

Answer

Using jQuery:

function submit($form){
    $.ajax('action.php', {
        method: 'POST',
        data: $form.serialize(),
        success: function(result) {
            $('#result').html(result);
        }
    });
}
Comments