jQuery .post Post Elements
Pregunta
Here is my code;
<script type="text/javascript">
function submitform()
{
$.post("handlers/request.php");
}
</script>
<form action="handlers/request.php" method="post" data-ajax="false" id="request">
<a href="javascript: submitform()">
<input type="hidden" name="url" value="http://google.com" />
</a>
</form>
In a separate PHP file (handers/request.php) I have a simple:
$url = $_POST['url'];
It isn't picking this up. Why not?
Solución
You're not actually passing any data through.
$.post("handlers/request.php", { url: $("[name='url']").val() }, function(data){
console.log( data );
});
Note the second parameter, it's an object which will carry our values over to the server-side PHP script. The url
key will become $_POST['url']
on the server-end, and will contain our value from the [name='url']
form input.
Additionally, when binding this functionality to an anchor-click, avoid the following:
<a href="javascript: submitform()">
Instead, go with something more along the lines of:
<a class="submit" href="enablejs.html">Submit</a>
Then, within your JavaScript:
$(function(){
$("form#request").on("click", "a.submit", function(e){
e.preventDefault();
$.post("handlers/request.php", { url: $("[name='url']").val() }, function(data){
console.log( data );
});
});
});
It's always good to keep your JavaScript out of your HTML.
Otros consejos
On a simple level, you need to:
- pass some data to the Ajax page, which your code doesn't.
- decide what to do once your data has been passed.
The syntax for $.post goes like:
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
so it would be:
$.post("test.php", { name: "John", time: "2pm" } );
to pass simple JavaScript variables, or:
$.post("test.php", $("#request").serialize());
to pass a whole form with id "request", like yours.
You need to specify a callback function if your test.php
page returns some code.
Besides, your implementation of the HTML is somewhat messy. There's no sense in putting a hidden input in an A
tag. Try something like:
<form action="handlers/request.php" method="post" data-ajax="false" id="request">
<input type="hidden" name="url" value="http://google.com" />
<input type="button" onclick="submitform();" value="Submit" />
</form>
function submitform() {
$.post("handlers/request.php", $("#request").serialize());
}