0

I am trying to pass a JS variable to PHP and have PHP echo the JS variable back. I keep getting an empty null string. What am I doing wrong?

function(u){

            if(u){
                var dt = {'ud':u};
                console.log(dt);

                $.post('xrege.php', dt, function(r){
                    console.log(r.responseText);
                    console.log(typeof(r.responseText));
                });
            }
        });


<?php

$ud = $_POST['ud'];
echo json_encode($ud);
?>
4
  • Check what r is. Commented Nov 13, 2016 at 2:00
  • Thought r would be the response I received from the server Commented Nov 13, 2016 at 2:05
  • 1) u is a boolean in this case. 2) You're trying to asign u to nothing. The correct syntax would be {ud: u} without the quotes. Quote from the jQuery api: $.post( "test.php", { name: "John", time: "2pm" } ); 3) Don't mix Javascript with jQuery. It should be console.log(r); Commented Nov 13, 2016 at 3:14
  • u is a variable that should have a value, I just want to check if indeed it does have a value before passing it to the server. I spent two hours scratching my head and overlooked the syntax error though, thank you. Commented Nov 13, 2016 at 12:06

1 Answer 1

1

you should separate php code into a different file and it should be working.

if(u){
    var dt = {'ud':u};
    console.log(dt);

    $.post('xrege.php', dt, function(r){
        console.log(r);
        console.log(typeof r);
    },"json");
}    

name the above code like 123.html and keep the below code in xrege.php

<?php
$ud = $_POST['ud'];
echo json_encode($ud);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

The code is already segregated. I am using two other PHP files that work perfectly well. But for the life of me, I cannot even get the most basic response from this one.

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.