1

Possible Duplicate:
How to pass a variable / data from javascript to php and vice versa?

I have 3 javascript variables which gives me an id, a name and a surname as such:

    if (!response.error) {

    document.getElementById("meName").innerHTML = response.id 
                                                 + " " + response.name
                                                 + " " + response.surname ;
                        }

Now I want to pass those variables (response.id, response.name and response.surname) into my database.

Something like this:

<?php

    $query = mysql_query("INSERT INTO users (id, name, surname) VALUES 
 ('response.id', 'response.name', 'response.surname')") or die(mysql_error());

$result = mysql_fetch_array($query);
return $result;

?>

How can I do this?

Community
  • 1
  • 1
jQuerybeast
  • 14,130
  • 38
  • 118
  • 196

5 Answers5

2

This is what you need:

        if (!response.error) {
                    var uid = response.id;
                var firstname = response.name;  
                    var surname = response.surname  

                    if (window.XMLHttpRequest) {
                        xmlhttp = new XMLHttpRequest();
                    }

                    xmlhttp.open("GET", "ajax.php?uid=" + uid + "&firstname=" + firstname + "&surname=" +  surname , true);
                    xmlhttp.send();

                    return false;

        }

and in your ajax file:

<?php include("YOUR_CONNECTION_FILE.php");


$uid = mysql_real_escape_string($_GET['uid']);
$firstname = mysql_real_escape_string($_GET['firstname']);
$username = mysql_real_escape_string($_GET['surname']);


$query = mysql_query(" YOUR MYSQL QUERY ") or die(mysql_error());  
?>
jQuerybeast
  • 14,130
  • 38
  • 118
  • 196
1

Well, ajax would be the best choice in your case.

Check my answer here How to send a form without refreshing the page?

Check out some documentation also:

jQuery Documentation

Tutorials

Community
  • 1
  • 1
Alex
  • 7,538
  • 23
  • 84
  • 152
1

I'm guessing you're trying to pass the javascript variables to php.

In order to do this you need to use a POST or GET method.

This question's answer will help.

Community
  • 1
  • 1
rks
  • 11
  • 1
0

You'd need to make an AJAX call to a separate PHP script which stores the variables.

Javascript runs browser-side, whereas PHP runs on the server - by the time the browser is running the Javascript code in the page, it has already finished running on the server and thus all of the PHP code has already executed.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • That is why I came here and asked this question otherwise I would just go do it, dont you think? You are answering my question. – jQuerybeast Mar 11 '12 at 00:42
-1

I believe that response is your return via ajax, if so, you should check two things

First, set the ajax dataType to 'json'.

Second, replace

return $result

to

return json_encode($result);

By.