I am currently working with a JS/AJAX functions that works without a page refresh or button click. I have run into some issue when echoing the value. For example if I change this line $email = $_POST['name']; it works perfect but if i use the actual value of email like $email = $_POST['email']; it doesn’t work. I am new learner with both JS & php.
Can someone tell me why is giving such results? EXAMPLE
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "test1.php",
data: dataString,
success: function(result){
$('#special').html($('#resultval', result).html());
}
});
return false;
}
$('#email').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 0050);
var name = $("#email").val();
dataString = 'name='+ name;
});
});
</script>
PHP
<?
if($_POST) {
$email = $_POST['email'];
if (preg_match('|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $email)) {
echo ('<div id="special"><span id="resultval">'.$email.'</span></div>');
}
else {
echo ('<div id="special"><span id="resultval">Include a valid email address.</span></div>');
}
}
?>
Well, you explicitly specify a parameter ‘name’ to hold the email address. There is no parameter ’email’ you speficy. Loot at this line in your JS code:
So there is no sense trying to read the email address in php like you do:
You have to change the JS code to name the parameter the same as you are trying to read it inside the php code.
So most likely all you have to do is change you current JS code from
to