10

I want to pass some values from JavaScript to PHP using jQuery/AJAX. 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.

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:

$("#text-id").click(function() {
$.ajax({
type: 'post',
url: 'text.php',
data: {source1: "some text", source2: "some text 2"}
});
});

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.

4

2 に答える 2

10

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 );
        }
    });
});

コンソールに次の情報が表示されます。

some textsome text 2

test.phpと HTML ソース ファイルの両方が同じディレクトリにあることを確認してください。

于 2013-10-19T05:24:10.207 に答える
1
$("#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
     });
});

参照ajax

于 2013-10-19T05:20:13.987 に答える