Reputation: 41
I know this is a repetitive question, but please help me. I have this code which send form data to php using ajax, but the code doesn't work and I don't know why. Any help please ?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
function chk(){
var name = document.getElementById('name').value;
var datastring = 'name = ' + name;
$.ajax({
type:"post",
url:"hi.php",
data: datastring,
cache:false,
success: function(html){
$('msg').html(html);
}
});
return false;
}
</script>
</head>
<body>
<form>
<input type="text" name="id" >
<input type="submit" value="submit" onclick="return chk()">
</form>
<p id="msg"></p>
</body>
</html>
PHP
<?php
if($_POST)
{
$name=$_POST['name'];
echo $name."<br>";
}
?>
Upvotes: 0
Views: 156
Reputation: 12132
Problem: your code is looking for an element with id
of name
when you use this line: var name = document.getElementById('name').value;
. However there are no elements with that Id in your HTML. Also, you're triggering the element with id of msg
but you are not telling it its an ID, since no hash #
is present.
Solution: since you are already using jQuery, I would stick with its functions, specifically submit()
and serialize()
. Redo your code like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="text" name="name">
<input type="submit" value="submit">
</form>
<p id="msg"></p>
<script>
$('form').submit(function () {
$.ajax({
type: "post",
url: "hi.php",
data: $(this).serialize,
cache: false,
success: function (html) {
$('#msg').html(html);
}
});
return false;
});
</script>
</body>
</html>
Upvotes: 1
Reputation: 339
In your code you are setting the html response to: $('msg').html(html);
I think you mean $('#msg').html(html);
Notice the '#' to reference an element by id.
Upvotes: 0
Reputation: 218808
This won't do anything:
$('msg').html(html);
Because there are no <msg>
tags in your markup. Perhaps you meant to reference the element with the id
of "msg"
?:
$('#msg').html(html);
Upvotes: 0