I am trying to send post data from from with empty action and send the info with javascript to the file that must handle the post information.
Here is my code:
<HTML>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<script>
function post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form._submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_();
}
post_to_url("./postinfo.php", { submit: "submit" } );
</script>
<form method="post" onsubmit="return post_to_url()">
<input type="text" name="ime">
<input type="submit" id="submit" name="submit" value="Send">
</form>
So how i can send the post data to postinfo.php
with javascript with empty action in my html form?
Thanks in advance!
You're quite lucky because there's a JQuery function called "Ajax" which handles this for you!
All you need to do is call JQuery, and use code like this:
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
function post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
_submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_();
}
post_to_url("./postinfo.php", { submit: "submit" } );
change to
post_to_url("/postinfo.php", { submit: "submit" } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With