PHP: Passing variables from Javascript to PHP

This entry is part 54 of 54 in the series PHP Tutorial

Javascript is a client side programming language and it can’t interact with server side database such as MySQL.

If you are developing HTML 5 apps for Andoid or IOS, you will have to save some inputs into the database.  To store data, you can always pass them into php and store them using PHP.

A common technique is to use AJAX is illustrated by the example below.

        function submitForm(form)
            var text_input = form.inputbox.value;

            var xmlhttp=new XMLHttpRequest();

                if (xmlhttp.readyState==4 && xmlhttp.status==200)

<form>Enter something in the box: <br><br>
    <input type="text" name="inputbox" value=""><P>
        <input type="button" name="button" value="Click" onClick="submitForm(this.form)">
<p id="text_id">Input your name to get a response from server</p>


$name = $_GET['str'];
echo 'Hello ' . $name . '!';

Put the above 2 files, ajax.html and get.php in the same directory and run ajax.html.

You can try it here.

In the line


We put the browser in a ready state to receive a response from the server.

We then send a request to the server using:"GET","get.php?str="+text_input,true);

The syntax for the method is open(method,url,async)

Method is either in post or get method, we are using get method which is faster and simpler.

async needs to be set to true to enable asynchronous rather than synchronous.

The variable will be passed into the get.php script and store as $name variable.  We can then input the $name variable into MySQL if needed.

Series Navigation<< PHP: URL validation