I just tried sending data from javascript to php using ajax. Here is my code in show.html:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#post-button").on("click", function(){
$.ajax({
type: "POST",
url: "get_test.php",
data: {name: "John"}
});
})
});
</script>
<body>
<input type="text" name="name"/>
<button name="post" id="post_button">Test Post</button>
</body>
</html>
And the php code:
<?php
if(isset($_POST['post_button'])){
$name = $_POST['name'];
print($name);
}
?>
I've tried to run it, but there is no changing and also no error. Nothing is happening. Could you tell me the problem? And also I want to get data from a form in which there is a text field inside. I will put before the button. How to get the data from that text field using javascript?
4 Answers 4
Use serialize function:
function showValues() {
var str = $( "form" ).serialize();
$( "#results" ).text( str );
}
1 Comment
You shouldn't wrap document.ready() event in a function as it most likely won't ever fire and nothing will happen. All you need to do is this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#post-button").on("click",function(){
$.ajax({
type: "POST",
url: "get_test.php",
data: {name: "John"}
});
});
});
</script>
<body>
<button name="post" id="post-button">Test Post</button>
</body>
6 Comments
html
<input type="text" name="name" id="somename"/>
<button name="post" onclick=post();>Test Post</button>
<div id="someid"></div>
javascript:
function post(){
$.ajax({
type: "POST",
url: "get_test.php",
data: {name: $("#somename").val()},
success:function(data){
$("#someid").html(data);//this will be the data returned from php
//console.log(data);
}
});
}
8 Comments
success?In your get_test.php file
<?php
parse_str($_POST['data'], $data);
if(isset($data['name'])){
$name = $data['name'];
print($name);
}
exit;
?>
Please try with this code, this may helps you.
$(document).ready(function(){wrapper... it's already inside a function.id="post"and can trigger the$("#post").click(function(){ }and to get the value you can usevar val= $("#text_box_id").val();