I am practicing doing simple AJAX calls to localhost but experiencing trouble. What I'm trying to do is send two textbox form values to PHP and then have it return a message to an empty div in my form upon successful reception via AJAX. My test.php is like this:
<?php
$num = htmlentities(substr($_POST["num"], 0, 7), ENT_QUOTES);
$name = htmlentities(substr($_POST["name"], 0, 50), ENT_QUOTES);
$result = "'$num ' + 'and' + ' $name' + ' values have been successfully AJAXd'";
echo json_encode($result);
jQuery:
$("#form").submit(function() {
event.preventDefault();
$("#msgcontainer").html("");
$.ajax({
url: "test.php",
data: ("#num").serialize(), ("#name").serialize(),
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
success: function(response) {
$("#msgcontainer").html(response);
}
});
}
When I try to submit, the page simply reloads and adds form values to the URL. I've been trying to solve this for about a day now, so any help would be greatly appreciated.
EDIT:
I figured it out by trying things from every response. Not sure why it works without serialization... If someone knows, please explain. Working jQuery code:
$("#form").submit(function(event) {
event.preventDefault();
$("#msgcontainer").html("");
$.ajax({
url: "test.php",
data: {
num: $("#num").val(),
name: $("#name").val()
},
type: "POST",
dataType: "json",
success: function(response) {
$("#msgcontainer").html(response);
}
});
});
Thank you for the help!
$result = "{$num} and {$name} values have been successfully AJAXd";would be the correct format