How to assign value to a PHP variable using Javascript?

Asked

Viewed 778 times

0

Guys, I have the following problem:

I have a table with several records and, as soon as a certain link related to the record is clicked, a modal window would be opened with more information related to it.

Link:

<a class="navbar-brand" href="#my_modal" data-toggle="modal" data-book-id="' . $res->codigoLO . '"><i class="fa fa-times"></i></a>

The following script takes a value that is sent by parameter when clicking on the link and the arrow in an input present in the modal window. In fact, I would like instead of this value being put into input, to be assigned directly to a PHP variable also present in the modal window.

     <script type="text/javascript">
        $('#my_modal').on('show.bs.modal', function (e) {
            var bookId = $(e.relatedTarget).data('book-id');
            $(e.currentTarget).find('input[name="bookId"]').val(bookId);
              });
    </script>

Any idea how I can do that?

  • 2

    You cannot set variables in PHP by Javascript. PHP runs on the server side, while javascript runs on the browser (client side)

  • 1

    Complementing what @Callebe said: when Javascript runs, PHP has long since finished its service, there are no more PHP variables in this context.

1 answer

0


Search for Ajax (Asynchronous Javascript and XML). There are several ways we can use it, and one of these ways allows you to pass values to another file (PHP, in your case) and call it into the current page without having to reload the page and is widely used when we need to manipulate modals. Here is an example of a code taken from jQuery’s documentation regarding the use of Ajax but using the jQuery library:

$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }})
.done(function( msg ) { 
alert( "Data Saved: " + msg ); 
});

And the return of the other information (attributes) from the record to the client side could be done using JSON (Javascript Object Notation), a code that I use to convert an object, array or variable to JSON in PHP is:

echo json_encode($lista_json)

And this would return one or several elements to Javascript to handle on the page according to our requirements.

Some interesting links on these subjects:

jQuery: http://api.jquery.com/jquery.ajax/

W3schools AJAX: http://www.w3schools.com/ajax/

W3schools JSON: http://www.w3schools.com/json/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.