0

Friends I dont know is it possible or not, But want to do like mentioned as below, if possible give me the best solution..

index.php

<?php
mysql_connect('localhost', 'root', '') or die (mysql_error());
mysql_select_db('mydb') or die (mysql_error());
?>
<html>
  <head>
    <script type="text/javascript" src="jquery-1.8.2.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $('input[type="button"]').click(function(){
          $.ajax({
            url : 'ajax.php',
            success : function(data){
              alert(data);
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <input type="button" name="button" value="Submit">
    <?php print_r($_REQUEST['data'])?>
  </body>
</html>

ajax.php

<?php
mysql_connect('localhost', 'root', '') or die (mysql_error());
mysql_select_db('mydb') or die (mysql_error());

$query = mysql_query('select * from user');
$count = count($query);
while($row = mysql_fetch_array($query)) {
  $data['name'][] = $row['name'];
}
print json_encode($data);
?>

When I click on submit ajax will call and will get response from in json encoded string as below

{"name":["Nakul Kabra","Bridget Louise","Jayesh Joshi","Jignesh Chaudhary","Jitendra Vihol","Spec Develop","Harshad Sadclown","Andy Estep","Rohan"]}

Now i want to store this ajax response in PHP variable and display it. How to solve this problem, can anybody help me please..??

Thanks, In advance !! Your regards.

4

2 回答 2

1

It sounds like to are trying to persist data across page requests. Remember each page request, be it a page refresh or an ajax request, creates a new php runtime. Variables are not stored across these, but there are of course multiple techniques used to allow this behaviour to occur. The most common way to persist data across page requests is to use PHP sessions and cookies.

This is a useful article which explains in a nice amount of detail how to implement sessions and cookies.

于 2012-12-25T19:03:26.250 回答
1

The short answer is no, it's not possible. You already had the data in a PHP array before you sent it to the client side. Once the json array arrives, it's not possible to store it in as a PHP array. That would of course require sending it back to the server.

In your AJAX success function, you can parse the json and insert it into a form (or any other HTML element). Here's an example:

var obj = jQuery.parseJSON(data);
$.each(obj.name, function(index, value) {
    $('<input>').attr({
        type: 'input',
        name: 'name[]',
        value: value
    }).appendTo('#name_box');
});

Here's a sample form:

<form action="edit_names.php" method="post">
    <div id="name_box"></div>
    <input type="submit" value="Submit" />
</form>
于 2012-12-25T19:06:25.573 回答