[英]Trying to pass variable values from JavaScript to PHP using AJAX
I want to pass some values from JavaScript to PHP using jQuery/AJAX. 我想使用jQuery / AJAX将一些值从JavaScript传递给PHP。 I have the following "simplified" code, not sure what is that I am doing wrong.
我有以下“简化”代码,不知道我做错了什么。 There seems to be quite a few similar questions/answers in StackOverflow, but none of the them are really helping.
StackOverflow中似乎有很多类似的问题/答案,但它们都没有真正帮助。
HTML: HTML:
<div>
<a href="#" id="text-id">Send text</a>
<textarea id="source1" name="source1" rows="5" cols="20"></textarea>
<textarea id="source2" name="source2" rows="5" cols="20"></textarea>
</div>
JAVASCRIPT: JAVASCRIPT:
$("#text-id").click(function() {
$.ajax({
type: 'post',
url: 'text.php',
data: {source1: "some text", source2: "some text 2"}
});
});
PHP (text.php): PHP(text.php):
<?php
$src1= $_POST['source1'];
$src2= $_POST['source2'];
echo $src1;
echo $src2;
?>
The problem: Nothing is happening...no errors..nothing. 问题:什么都没发生......没有错误......没什么。 I don't see the values of 'source1' and 'source2' showing up in the PHP echo statements.
我没有看到'echo1'和'source2'的值出现在PHP echo语句中。
You need to include a success handler in your AJAX call: 您需要在AJAX调用中包含成功处理程序 :
$("#text-id").on( 'click', function () {
$.ajax({
type: 'post',
url: 'text.php',
data: {
source1: "some text",
source2: "some text 2"
},
success: function( data ) {
console.log( data );
}
});
});
and in your console, you'll receive: 在您的控制台中,您将收到:
some textsome text 2
Do make sure that both the test.php
and your html source files are in same directory. 确保
test.php
和html源文件都在同一目录中。
$("#text-id").click(function(e) {// because #text-id is an anchor tag so stop its default behaivour
e.preventDefault();
$.ajax({
type: "POST",// see also here
url: 'text.php',// and this path will be proper
data: {
source1: "some text",
source2: "some text 2"}
}).done(function( msg )
{
alert( "Data Saved: " + msg );// see alert is come or not
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.