Skip to content Skip to sidebar Skip to footer

How To Send Variables From Javascript To Php

I want to know how to send variables from javascript to php so i can create a variable that contains dynamic sum of rows. More specific: When I search in my search box, i want to g

Solution 1:

You probably have never learned the difference between javascript and php

Javascript is clientsided, which means everything is processed by your local system. PHP is server sided which means everything is processed by the server and parsed into html.

You can't send a value from javascript into plain php like you did. You can however send a post or get to the same script and let that reload a part of your script

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

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

Solution 2:

You're not the first to want this, and not the first to be told it is impossible the way you imagine. When you browse to a PHP page things go basically like this:

  1. Browser sends HTTP request to server
  2. Server determines what page to send to the browser
  3. Server discovers you want a PHP page
  4. Server executes PHP
  5. Server sends what is returned by PHP to the browser
  6. Browser doesn't know about the PHP and displays HTML
  7. Browser executes Javascript.

Now the important part is that the browser doesn't know what PHP is, but can execute JavaScript, while the server doesn't know what JavaScript is (for simplicity's sake) but can execute PHP. Bottomline: it is hard to communicate between the two because they are executed in different places. You'll most probably want to use AJAX, so here is a supersimple sample:

The PHP page we're going to fetch:

<?// We're on the server// We're going to output something:echo"Yay! You can see me!"; // So the browser sees only "Yay! You can see me!" (without quotes).?>

JavaScript (with jQuery) to fetch the PHP page:

$("#anElementID").load("thePHPPageWeWantToFetch.php"); // It's that simple! The element with the ID #anElementID now contains "Yay! You can see me!" (without quotes).

Solution 3:

I suggest too, use AJAX or something to pass your javascript values to PHP. You can create a AJAX call, add the data from your javascript, and catch the data in your PHP file.

var value = "Jan";
$.ajax({
        url: "/form.php",
        type: "post",
        data: "name=" + value
    });

in your PHP file you can do:

<?php$catchedName = $_POST["name"];
?>

Post a Comment for "How To Send Variables From Javascript To Php"