Getting selected text

Asked by At

I need to get a text that the user has select with pointer and put it to some variable in PHP. So, the user should select some text in one div, then click submit button (in another div), and then I need to store that part of the text to some variable. Can anybody help me?

1 Answers

Matthew Vanlandingham On

You would have to set an onclick listener (I prefer to use JQuery for this) so that when the user clicks the submit button, you grab the selected text from the div. You could probably do that in a way found here:

Get the Highlighted/Selected text

Since javascript and HTML are front-end and PHP is back-end, you cannot simply place the selected value into a PHP variable. Instead, you can use an ajax request to send the data to a PHP function. I'm not sure what you are doing with it after that, but sending an ajax request and including the selected text in the data section of the request, and then retrieving it in your PHP file/function and storing it in a variable there. This question should help in that regard: Passing Javascript variable to PHP using Ajax