javascript - Manage json data outside ajaxform

296

I am using the well known ajaxForm Jquery Form Plugin (http://jquery.malsup.com/form/). I 'll present to you my code:

HTML code:

<script type="text/javascript">
$(document).ready(function() { 
$('#users_form1').ajaxForm({ 
    dataType:  'json', 
    success:   processJson           
  });
}); 

function processJson(data) { 
  $("#first").val(data[1].elem1);    
  $("#second").val(data[1].elem2);
}
</script>

PHP code:

  ... 
  $result=$db->query($query);        
    if ($result->num_rows>=1) 
    {     
      $counter=0;   
      while ($row = $result->fetch_assoc()) { 
         $counter++; 
         $data1=$row["req_created"];            
         $data2=$row["subject"];
         $temp[$counter] = array(
            'elem1' => $data1,
            'elem2' => $data2,
         );
      }
       echo json_encode($temp); 
    }     

As you may see from the above code, $temp is passed to var data inside function processJson. I'd like to know if array $temp is accessible outside processJson? For example, I want to choose $temp[3]["elem2"] upon a button click, however is it possible to get this data without searching again the database? If yes, how?

Thank you very much

76

Answer

Solution:

You can have the data in variable, this will be like temporary storage.

<script type="text/javascript">
$(document).ready(function() { 
$('#users_form1').ajaxForm({ 
    dataType:  'json', 
    success:   processJson           
  });
}); 
var tem_data;
function processJson(data) { 
  $("#first").val(data[1].elem1);    
  $("#second").val(data[1].elem2);
   tem_data = data;
}

// Use tem_data anywhere; 
</script>

But only last requested data will be thetem_data.

If you want all data then do it in array with array push method

People are also looking for solutions to the problem: php - Ajax load contents and append related urls

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.