0

test.php

<script src="https://code.jquery.com/jquery-1.11.1.js"></script>  
<script>
function testing(){
 $.ajax({
                        url: 'test.php',
                        type: 'GET',
                         data: { va: "answer" },
                         success: function(data) {
                             // do something;
alert("answer")  ;                       }
                     });



}
</script>

<textarea><?php 
$compare= $_GET['va'];
echo $compare; ?>
</textarea>  

<button onclick="testing();">click</button>     

Am getting an alert message when I click the button but am getting nothing into the textarea.unable to get the javascript variable into php code. What's wrong here?

2
  • It's working but you are not refreshing the page. Textarea it's rendendered at time 0. Then you have Ajax call at time 1. Textarea it's already rendered so it's not refreshed. Commented Nov 28, 2014 at 13:15
  • stackoverflow.com/questions/9150977/… Commented Nov 28, 2014 at 13:17

2 Answers 2

2

AJAX and PHP are different.

PHP is server based and AJAX is browser based.

You are getting data in:

You need to update this data with javascript itself.

As page is not refreshing PHP, will not update here.

success: function(data) {
  $("textarea").val(data); // You need update the value with Javacript.
}
Sign up to request clarification or add additional context in comments.

3 Comments

When updating textarea using $("textarea").val(data); , am getting the whole code into the textarea instead of getting value.
The backend file test.php might contain some HTML output. Please take care of that.
Then what's the solution to avoid that html output
1

You never update the textarea after doing the ajax call. You need to add id attribute to the textarea so it's clear which textarea you're referring to, let's say the id is answer

<textarea id="answer"><?php 
$compare= $_GET['va'];
echo $compare; ?>
</textarea> 

then set the value of the textarea in the success function using $('#answer').val(data)

function testing(){
    $.ajax({
            url: 'test.php',
            type: 'GET',
            data: { va: "answer" },
            success: function(data) {
                         // do something;
                         alert("answer");
                         $('#answer').val(data);
                      }
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.