вернуть переменную из файла, выполненного из действия формы - PullRequest
1 голос
/ 20 января 2012

Допустим, у меня есть файл (file1.php) с простой формой с атрибутом действия:

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; 

Скажем, foo.php выглядит примерно так:

$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'];

Как видите, мне нужна переменная $ user_id, созданная в foo.php, чтобы она использовалась в основном файле file1.php. Есть какой-либо способ сделать это? Я думал, что возвращение $ user_id будет работать, но я ошибся: - / Некоторые примечания, которые необходимо учитывать:

  • в file1.php есть две формы: одна для загрузки файла (пример выше) и другая для сохранения всех данных в базе данных (вот почему мне нужно имя переменной).

  • пример только это, пример. На самом деле я не добавляю 5 к запрошенной переменной, но я не хочу копировать и вставлять 100 строк кода, чтобы сокрушить всех.

  • переменная также обновляется с помощью javascript, поэтому я вижу это там, но я не знаю, как назначить переменную javascript переменной php (если это возможно).

СПАСИБО !!! * * 1023

Ответы [ 2 ]

1 голос
/ 20 января 2012

Вот как бы я это сделал.

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>

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
});

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

используйте плагин Jquery Form для загрузки файла через 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
            });
        }
    });
});

Как вы заметили, вы не указали ни данные POST, ни URL-адрес сценария PHP. ajaxSubmit автоматически выбирает данные POST из формы и отправляет их на URL-адрес, указанный в action формы

1 голос
/ 20 января 2012

Я могу придумать два пути от макушки головы.1.

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

Затем вы можете ссылаться на $ _SESSION ['user'] всякий раз, пока сеанс не будет уничтожен.

Другим способом будет включение файла, который определяет $ user_id (foo.php) в file1.php с:

include("file1.php");

Вероятно, это проще сделать с помощью сессий.

На самом деле, ОДНОМ БОЛЬШЕ, что вы можете использовать, - передать значение переменнойURL-адрес, если это не то, что нужно сохранить в тайне.

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

или

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

Затем на file1.php вы получите доступ к этой переменной следующим образом.

$userid = $_GET['userid'];

и вы можете использовать $ userid как свойпожалуйста.

...