1

I'm trying to post a JS variable to a PHP script but I'm not able to do it. Here are the scripts,

The following JS is embedded in a script named "check.php",

<script type="text/javascript">
$(document).ready(function() {
$('#content-area').mouseup(function() {
 var selection = getSelected();
  if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
     alert('Sending the following text to the server via AJAX: ' + selection);
            $.ajax({
             type: 'post',
             url : 'calculate.php',
             data: 'selection=' + encodeURI(selection)  
            });
     }
   });
   });  
</script>  

I'm posting the "selection" variable using ajax to The PHP script(calculate.php) where I'm receiving the value as follows.

<?php
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
      strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' &&  
      $selection = trim($_POST['selection'])) {
        $selText = $selection;
       }
?>

I'm getting a null value at the server-side i.e "calculate.php". Please tell me what is going wrong here?

2 Answers 2

1

Try this once.

in ajax call

$.ajax({
            type: 'post',
            url : 'calculate.php',
            data: { selection : selection},
          });

In calculate.php get your data using $_POST['selection'];

Sign up to request clarification or add additional context in comments.

2 Comments

I checked it using if(isset($_POST['selection']) in calculate.php, and the data is not received at the server side. But it shows the alert msg on selecting the text. Pl help
Why post an answer with same content/proposal as other already posted answer? If it didn't worked for that answer, why it should works for yours?
1

Change you data attribute to:

data: { selection: encodeURI(selection) }

Then it will be available on your PHP script as:

$_POST['selection']

Further, look at your if condition in your PHP script:

$selection = trim($_POST['selection'])

If you're want to compare those values, I think you should use ==. If not, just move it outside the condition.

3 Comments

Still no success. Still getting null value. Do you have any other fix?
Even the updated thing is not working. Also I checked it using if(isset($_POST['selection']) in calculate.php, and the data is not received at the server side. But it shows the alert msg on selecting the text. I'm disheartened, Pl help
@mario23 is hard to help you with that lack of information. Post the result of print_r($_POST); at the beggining of your PHP script and your request from developers tools(Chrome) - it can be a screenshot or even request header text...

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.