1

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!!!

Claudio
  • 3,814
  • 7
  • 28
  • 34
  • Unless you're using AJAX, when you submit the first form, you will leave the first page and go to the second page. It seems you're expecting you will remain on the first page – Ayush Jan 20 '12 at 06:15
  • I am using ajax for the first form! What i am thinking about is to generate a variable with a random string and use that as the name of the file being uploaded. Later, when I save the rest of the form inputs I can move and rename the file named randomly. Or even use the session userid generated when he logged in the first time. (remember that I don't really need the $user_id, it is just to show the problem) – Claudio Jan 20 '12 at 06:58

2 Answers2

2

Here's how I would do it.

The html:

<form id="form1" action="foo.php" method="post">
    <!-- form elements -->
</form>

<form id="form2" action="bar.php" method = "post">
    <input type="hidden" name="filename" value="" />
    <!-- other form elements -->
</form>

The javascript

$('#form1').submit(function(){
    var formdata = ''; //add the form data here
    $.ajax({
      url: "foo.php",
      type: "POST",
      data: formdata,
      success : function(filename){
            //php script returns filename
            //we apply this filename as the value for the hidden field in form2
            $('#form2 #filename').val(filename);
      }
    });
});

$('#form2').submit(function(){
    //another ajax request to submit the second form
   //when you are preparing the data, make sure you include the value of the field 'filename' as well  
   //the field 'filename' will have the actual filename returned by foo.php by this point
});

The PHP

foo.php

//receive file in foo.php

$filename = uniqid(); //i generally use uniqid() to generate unique filenames 
//do whatever with you file
//move it to a directory, store file info in a DB etc.

//return the filename to the AJAX request
echo $filename;

bar.php

//this script is called when the second form is submitted.
//here you can access the filename generated by the first form

$filename = $_POST['filename'];

//do your stuff here

use the Jquery Form plugin to upload the file via Ajax

$(document).ready(function(){
    $('yourform').submit(function(){        //the user has clicked on submit

        //do your error checking and form validation here

        if (!errors)
        {
            $('yourform').ajaxSubmit(function(data){        //submit the form using the form plugin
                alert(data);    //here data will be the filename returned by the first PHP script
            });
        }
    });
});

As you'll notice, you haven't specified either the POST data or the URL of the PHP script. ajaxSubmit picks up the POST data from the form automatically and submits it to the URL specified in the action of the form

Ayush
  • 41,754
  • 51
  • 164
  • 239
  • question: I'm not being able to add the file to the formdata variable. This' the code: 'formdata = false; formdata = new FormData(); if (formdata) {formdata.append("images", file);} ... ajax call ...' The foo.php looks like this: '$fileTmpLoc = $_FILES["images"]["tmp_name"]; if (!$fileTmpLoc) { echo "ERROR: Please browse for a file!"; exit(); }'. For some reason I am always getting the echoed error. If I 'print_r($fileTmpLoc);' I get nothing. Finally the html: '' – Claudio Jan 22 '12 at 16:15
  • here more lines from the javascript: input.addEventListener("change", function (evt) {var len = this.files.length, img, reader, file; file = this.files;} – Claudio Jan 22 '12 at 16:19
  • @cbarg: you won't be able to add a file manually to the formdata. In fact, its generally considered 'not possible' to upload a file via ajax. A lot of people use iframes etc to achieve the same effect. However, I've used the jquery forms plugin (http://jquery.malsup.com/form/) and it works great. It'll be about 3-5 lines of code. I'll edit my answer to attach the code – Ayush Jan 22 '12 at 18:34
  • Thanks xbonez, just let me work with it a little bit more and reformulate the whole post/question. Thanks again. – Claudio Jan 22 '12 at 18:51
  • Hello! I've been working with it and so far it's coming up pretty good. But how do I set the variable formdata? check http://stackoverflow.com/questions/8991731/jquery-ajax-sending-files-array-from-form so I can vote up! – Claudio Jan 25 '12 at 00:43
1

I can think of two ways off the top of my head. 1.

session_start();
$_SESSION['user'] = $row['user_id']

Then, you can refer to $_SESSION['user'] whenever until the session is destroyed.

Another way would be to include the file that defines $user_id (foo.php) into file1.php with:

include("file1.php");

It is probably easier to achieve this with sessions.

Actually, ONE MORE THING you could use is to pass the variable value through the URL if it isn't something that needs to be kept private.

echo "<a href='file1.php?userid=" .$userid. "' > LINK </a>";

or

<?php
echo "
<html>
<head>
<meta HTTP-EQUIV='REFRESH' content='0; url=file1.php?userid=" .$userid. "'>
</head>
</html>";

Then, on file1.php you would access that variable like this.

$userid = $_GET['userid'];

and you can use $userid as you please.

Pablo Canseco
  • 554
  • 1
  • 10
  • 24
  • Basically, I am assigning the session user id to the uploaded file since each user can only upload one file at any time. so when I need to call that file I just know the file name. Thanks! – Claudio Jan 21 '12 at 01:10