0

I spent most of my day yesterday trying to solve this puzzle so today I've decided to reach out for some help. Before I begin, let me state that I am very aware that JavaScript is client-side and PHP is server-side and I use Ajax successfully for various other things. In this case, I can't find any S/O references that are similar to what I'm trying to accomplish. I would've thought this was very basic but I'm missing something here and could use some direction. Thank you.

In essence, I have a Javascript function that produces a JavaScript variable and then calls a PHP function that initiates a mySQL query (all on the same page). If I "hard-code" the argument in my PHP function call (e.g., sc_bdls = <?php echo Candidates::getBDLs(1000033); ?>;), the function runs perfectly and I receive the expected outcome (an array).

However, if I try and use a JavaScript variable in place of the argument, I receive a "Uncaught TypeError: Cannot read property 'id' of undefined" error. I have tried several iterations without success and I suspect I am missing something basic. Here is my code:

    function tab_pos3(row){
            var sc_id = row.toString();
            var sc_bdls = [];
            $.ajax({
                type: "POST",
                url: '/phpscripts/pass.php',   
                data: {row : row},
                success:(function(data){
                console.log("success");
                alert(data);
                })
            });
            sc_bdls = <?php echo Candidates::getBDLs($uid); ?>;
}

Here is the code from the pass.php file:

if(isset($_POST['row']))
{
    $uid = $_POST['row'];
    echo $uid;
}

Please notice that the console.log("success") and the alert(data) both show that the Ajax POST is working. Any thoughts on what might be going wrong? Thank you.

1st EDIT (comment from Swati)

I tried moving the PHP function call as suggested and then used $UID, $data, data, among others, and I still get the exact same error. Here is the edited code:

$.ajax({
            type: "POST",
            url: '/phpscripts/pass.php',  // 
            data: {row : row},
            success:(function(data){
            console.log("success");
            alert(data);
            <?php $row = $_POST['row'];?>; // I tried this based on something I read.
            sc_bdls = <?php echo Candidates::getBDLs(data); ?>;
            })

The fact that the error doesn't change is gnawing at me. Could the argument be passed but in a format that is not being read right? Is the "TypeError" referring to data type?

8
  • What is the output of echo $uid;? Commented Jul 5, 2020 at 14:46
  • 1
    From where did you got $uid isn't that should be data ? Also this sc_bdls = <?php echo Candidates::getBDLs($uid); should be inside success function of ajax if you need to access the data in your function call . Commented Jul 5, 2020 at 14:49
  • You didn't use any 'id' your code then how you got this error????Uncaught TypeError: Cannot read property 'id' of undefined" error. Commented Jul 5, 2020 at 14:51
  • what you get in your alert(data).you have to push that value into your javascript array. Commented Jul 5, 2020 at 14:54
  • 1
    Check this answer might help you . Commented Jul 5, 2020 at 16:21

1 Answer 1

1

Try moving the sc_bdls = <?php echo Candidates::getBDLs($uid); ?>; to pass.php and read the returned data in ajax success function.

Please note php is executed before the browser sees it. And JS code is called client side.

This is how your function will look like

$.ajax({
        type: "POST",
        url: '/phpscripts/pass.php',  // 
        data: {row : row},
        success:(function(response){
              console.log("success");
              sc_bdls=response; // Just to show that response has the value you need.
              alert(sc_bdls);
        })

The pass.php will look like this

// I prefer using !empty here (unless you are expecting 0 as a valid input.
// This ensure $uid isset and is not empty.
// Also if $uid is supposed to be numeric you may want to add a validation here.

if(isset($_POST['row'])) 
{
    $uid = $_POST['row'];
    $response_array = Candidates::getBDLs($uid); //Your question says you are expecting an array
    echo json_encode($response_array);
}
Sign up to request clarification or add additional context in comments.

7 Comments

This is where I think I'm missing something. When you say "Please note php part is executed before the browser sees it" I understand that perfectly. However, I would've thought that a function that initiates a PHP query is a brand-new call that starts a brand-new PHP request? In essence, the PHP function wouldn't be seen on load, it would only be seen once it is executed?
Well, This can be easily understood when you view the source of the page generated in the browser. Please replace the $uid with a valid ID that exists in the DB, you will see that the php function is already executed even before the JS function is called. This line sc_bdls = <?php echo Candidates::getBDLs(1000033); ?>; will look like this in the browser sc_bdls = <value returned by the method Candidates::getBDLs($uid)> It no longer has the php code. PHP code is executed on the server, then sent to the browser. Whereas JS is executed in the browser
Is the "TypeError" referring to data type - while the question does not mention it clearly, but this error is returned by either the DB or the validation functions in the method. Basically $uid is NULL when you are calling the method to query the DB. $uid has a value only when the JS code is executed (ie. when you are calling the function tab_pos3(row)) and the php call to Candidates::getBDLs($uid) is called even before the browser has rendered the html to the browser.
I am going to follow your line of reasoning and get back to you. I must hop on a team huddle for a couple of hours and then I will pursue. Thank you.
Hmm ... I'm getting a POST 500 error. I'm thinking ALL of the function being called will need to be in the pass.php file? This would include the db login info as well as the $mysqli->query info. Thank you for your help.
|

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.