Let’s say that I have a file (file1.php) with a simple form with the action attribute:
echo'
<form action="foo.php" method="post">
Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>';
$another_var = $user_id+5;
Let’s say the foo.php looks something like this:
$sql ... SELECT user_id, username... WHERE username = $_POST['username']; //or so
echo 'We got the user ID. it is in a variable!';
$user_id = $row['user_id'];
As you see, I need the variable $user_id made in foo.php actually to be used in the main file file1.php.
Is there any way to do this? I though that return $user_id would work but I was wrong :-/
Some notes to have into account:
-
in file1.php there are two forms: one to upload a file (example above) and another to save all the data into a database (that’s the reason I need the variable name).
-
the example is just that, an example. I’m not really adding 5 to the variable requested, but I don’t want to copy and paste 100 lines of code to overwhelm everybody.
-
the variable is also refreshed with javascript, So I see it there but I don’t really know how to assign a javascript variable to a php variable (if possible).
THANKS!!!
Here’s how I would do it.
The html:
The javascript
The PHP
foo.php
bar.php
use the Jquery Form plugin to upload the file via Ajax
As you’ll notice, you haven’t specified either the POST data or the URL of the PHP script.
ajaxSubmitpicks up the POST data from the form automatically and submits it to the URL specified in theactionof the form