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.
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' ];
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With