Reputation: 23
I have this code for example
<?php
if(isset($_POST['goose'])){
echo '<div>goose</div>';
}
?>
<form action="goose.php" method="POST">
<input type="submit" name="goose" />
</form>
How can I write something like this but in AJAX? I don't know this language.
Upvotes: 0
Views: 53
Reputation: 2975
I recommend using jQuery.
$.ajax({ // begins our async AJAX request
type: "POST", // defining as POST
url: "goose.php", // page to request data from
data: ["goose":$("input[name=goose]").val()], // define POST values
success: function(output){
alert(output);
},
error: //do something else
});
Because we have set the type to POST
our data will need to be in the form of an associative array with "goose"
being equivalent to $_POST["goose"]
.
data: ["goose":$("input[name=goose]").val()],
The success
is what will happen if the data is able to be sent correctly with output
being what is returned. In our case output
= <div>goose</div>
.
success: function(output){
alert(output);
}
error
can also have a function but here you will want to tell the script what do do if say goose.php
is un-reachable.
Upvotes: 1
Reputation: 10117
No need for extra frameworks. Just use fetch api.
<form action="goose.php" method="POST" onsubmit="submit(event, this)">
<input type="submit" name="goose" />
</form>
Javascript:
function submit(event, form) {
event.preventDefault();
fetch(form.action,{
method: 'post',
body: new FormData(form)
}).then((data) => {
console.log(data);
});
}
Upvotes: 1