Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to pass variable values from JavaScript to PHP using AJAX

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.

like image 539
Gandalf Avatar asked Oct 19 '13 05:10

Gandalf


People also ask

How do I pass variables and data from JavaScript to PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];

Can we assign JavaScript variable to PHP variable?

Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER . Feasible Solution : You can submit the Javascript value via ajax or through form submit.

How use JavaScript variable on same page in PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.


1 Answers

You need to include a success handler in your AJAX call:

$("#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.

like image 67
hjpotter92 Avatar answered Oct 06 '22 00:10

hjpotter92