I have a form with an onkeyup
event. I try to send a variable to my php script and show result in a div.
Thanks to this forum I got my test function to half work:
jQuery.post(the_ajax_script.ajaxurl,
If I continue with: 1) jQuery("#theForm").serialize(),
I get response text which is "Hello World" If I try to pass a variable: 2) { name: "p" },
I get: -1
JavaScript
function submit_me(){
jQuery.post(
the_ajax_script.ajaxurl,
{ name: "p" },
function(response_from_the_action_function){
jQuery("#txtHint").html(response_from_the_action_function);
}
);
}
PHP
<?php
function the_action_function(){
$name = $_POST['name'];
echo "Hello World, " . $name;
die();
}
?>
FORM
<form id="theForm">
<input type="text" name="user">
<input name="action" type="hidden" value="the_ajax_hook">
<input id="submit_button" value = "Click This" type="button" onkeyup="submit_me()">
<form>
I actually want onkeyup="submit_me(this.value, 0)"
I am doing this on a WordPress through their admin-ajax.php file.
Where is the problem in this?
EDIT
Apparently I had to add action to data
{ action:'the_ajax_hook', name:"p" }
I guess its WP requirement, rather than jQuery, because I saw examples as this:
$.post("test.php", { name: "John", time: "2pm" }
everywhere.
Something like this should work:
<html>
<head>
<script>
$(document).ready(function() {
$("#my_form").submit(function(event) {
event.preventDefault() // to prevent natural form submit action
$.post(
"processing.php",
{ name: "p" },
function(data) {
var response = jQuery.parseJSON(data);
$("#txtHint").html(response.hello_world);
}
);
});
});
</script>
</head>
<body>
<form id="my_form" action="/" method="post">
<input type="text" name="user" />
<input name="action" type="hidden" value="the_ajax_hook" />
<input type="button" name="submit" value = "Click This" />
</form>
<div id="txtHint"></div>
</body>
</html>
And then in processing.php:
<?php
$name = $_POST['name'];
$response['hello_world'] = "Hello World, " . $name;
echo json_encode($response);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.