1

What I am trying to accomplish is to pass the correct value from php to a jquery function. What is the proper way to get that value to my jquery function so that I can use it. Here is an example of how I tried to pass the php variable to the javascript function. Of course that does not give the desired effect.

index.php User starts typing in username and live search displays matching usernames in dropdown

<input type="text" class="form-control" id="keywords" placeholder="Search..." autocomplete="off">

getUsername.php Username gathered from database and displayed to user in dropdown. (when user clicks on a username it will send the username value to jquery function, then queries database and displays the specified info to user). Obviously sending a php variable directly through a jquery function is not going to work, but what other workaround is there in jquery to grab that $row['Username'] value to pass to the jquery function (searchFilterUsername). EDIT: Actually, sending the value through the jquery function is exactly what was needed. The Selected answer is the correct way to send the values through the jquery function

foreach($results as $row){
    <td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername();">
}

functions.js Need to be able to get that specific username to this jquery function, so that it can be sent to the database function to display proper selection back to user

function searchFilterUsername(page_num, userName) { //Username needs to be sent to this function somehow, so that I can store the proper value inside the variable $keywords
    page_num = page_num?page_num:0;

    var keywords = $('.searchTerm').data("username-id"); //Adding this will only allow the first item in the dropdown to be grabbed for the query

    var keywords = userName;

    alert(keywords);

    $.ajax({
        type: 'POST',
        url: 'getData.php',
        data:'page='+page_num+'&keywords='+keywords,
        beforeSend: function () {   
            $('.screenLoader').show();
        },
        success: function (html) {
            $('#displayPage').html(html);
        }
    });
}

Now if I remove the value from the onclick="searchFilterUsername()" then I am able to grab the first value, but of course that will not work since the data is dynamic. It is a live search, (user types username into input box and dropdown appears with queried usernames) and when the user clicks on the username, it displays values in display div based off of that username selection. The live search ties into the pagination class which allows user to search through returned values. Thanks.

getData.php getData.php grabs those $_POST values and sends them to the database query and then the searchFilter function is sent to the pagination class

 if(isset($_POST['keywords']) && !empty($_POST['keywords']) && $_POST['keywords'] !== 'null'){  
    $keywords = $filter->filter($_POST['keywords']);
    $usersSQL .= "AND users.userName LIKE :keywords "; 
  }else{
    $keywords = '';
    $usersSQL .= "AND users.userName LIKE :keywords ";
  }
$query= "SELECT * FROM users WHERE stuff = :stuff $usersSQL";

class.pagination.php $_POST Values sent to this pagination class to create pagination links

$paginationConfig = array('link_func' => 'searchFilterUsername');  
4
  • When you click the link, does the system show the username when it executes alert(keywords) ? Commented Jun 13, 2021 at 1:08
  • If I remove the $row['username'] from the onclick function then the alert will display 'undefined' due to no value being passed Commented Jun 13, 2021 at 1:40
  • 1
    what happens if you do NOT remove the $row['username'] from the onclick function and then you click the link ? does it execute alert(keywords) ? Commented Jun 13, 2021 at 1:44
  • 1
    Probably not... Since the are some quotes missing and anyway, there is only one argument passed in where two are expected. Commented Jun 13, 2021 at 1:47

3 Answers 3

3

I would suggest you to pass the values via some data-* attribute of each td.

foreach($results as $row){
  echo '<td class="searchTerm" data-pagenum="'.$row['something'].'" data-username="'.$row['userName'].'">blah blah blah</td>';
}

And use delegation for those dynamic elements.

$(document).on("click", ".searchTerm", function(){
  
  // Get the values via the data-* attributes
  var pagenum = $(this).data("pagenum");
  var keywords = $(this).data("username");
  alert(keywords);

  $.ajax({
    type: 'POST',
    url: 'getData.php',
    data:'page='+pagenum+'&keywords='+keywords,
    beforeSend: function () {   
      $('.screenLoader').show();
    },
    success: function (html) {
      $('#displayPage').html(html);
    }
  });
});
Sign up to request clarification or add additional context in comments.

6 Comments

I have tried it that way but it only returns the first value. I will edit my question for a little more clarity, I send the values from the jquery function searchFilter() to a pagination file. $paginationConfig = array( 'link_function' => 'searchFilter'); which adds them to the onclick() for the pagination.
I don't understand about your pagination... What I suggest is to pass the values via some data attributes in the HTML markup and then jQuery can retreive it.
Nice answer but you should be wrapping those attribute values in htmlspecialchars()
Thanks for the comment, Phil. But I don't understand why those values should be translated into HTML entities... It is supposed to be a username and a number.
@Louys Patrice Bessette I'm thinking it will be a lot more work to adjust the code for this one function. Since this is only one item in the multiple value search. Users can search by location, age and alot of other values.
|
2

Pass userName with onclick event called in td.

foreach($results as $row){
    <td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername(null,\''.$row['userName'].'\')">
}

As searchFilterUsername has first parameter is page_num and second is userName.

Hope this will be useful

1 Comment

Watch out for quotes! Should be (null,\''.$row['userName'].'\' )
1

All Code is good but you need to echo this line in getUsername.php like this

foreach($results as $row){
    echo '<td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername();">';
}

2 Comments

thanks for the reply Musab, I store all the return values in a variable and then echo them all together later. $output .= '<td class="searchTerm">'; echo $output; I figured i'd leave that out just for more clarity with less clutter
Ok, No problem.

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.