[英]Send data from javascript to PHP using ajax
I just tried sending data from javascript to php using ajax. 我只是尝试使用ajax将数据从javascript发送到php。 Here is my code in
show.html
: 这是我在
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代码:
<?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?
如何使用javascript从该文本字段获取数据?
Use serialize function: 使用序列化功能:
function showValues() {
var str = $( "form" ).serialize();
$( "#results" ).text( str );
}
You shouldn't wrap document.ready() event in a function as it most likely won't ever fire and nothing will happen. 您不应该将document.ready()事件包装在一个函数中,因为它很可能不会触发并且什么也不会发生。 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>
html html
<input type="text" name="name" id="somename"/>
<button name="post" onclick=post();>Test Post</button>
<div id="someid"></div>
javascript: 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);
}
});
}
In your get_test.php file 在您的get_test.php文件中
<?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. 请尝试使用此代码,这可能会对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.