I am trying to learn jQuery ajax the function seems to be working properly so says browser web developer tools but the values aren't pulled through to the php file(url) that I have here's my simple code.
This is the HTML anf jQuery File
<!Doctype HTML>
<html>
<head>
<title>Working with PHP and jQuery</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/jquery-1.11.3.min.js"></script>
</head>
<body>
<form id="#myForm">
<p>
<label>Enter your name</label>
<input type="text" name="Name">
</p>
<p>
<label>Are you male
<input type="checkbox" name="IsMale">
</label>
</p>
<p>
<label>Enter your email address</label>
<input type="email" name="Email">
</p>
<p>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</p>
</form>
<div id="loadResult"></div>
<script>
$(function() {
$('#submitButton').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'php/form1.php',
type: 'POST',
data: $('#myForm').serialize(),
success: function(result) {
console.log(result); $('#loadResult').html(result);
},
error: function(badresult){ alert("ajax error function hit"); console.log(badresult); }
});
});
});
</script>
</body>
</html>
And here's the php file
<?php
$name = $_POST['Name'];
$isMale = $_POST['IsMale'];
$email = $_POST['Email'];
echo "Name is $name, are you a male? $isMale. Your email address is $email";
?>
I am using the jquery serialize function but don't know where I am going wrong
Most likely what you're getting is this line blowing up
$isMale = $_POST['IsMale'];
And in your HTML we see
<input type="checkbox" name="IsMale">
Checkboxes, when they are not checked, are not successful, meaning they won't show up in $_POST
. From the jQuery serialize manual
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button.
snip
Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked
So you need to check that it was submitted
$isMale = (isset($_POST['IsMale'])) ? 'Yes' : 'No';