Filipe Fonseca
Filipe Fonseca

Reputation: 62

Sending PHP variables through AJAX

I'm currently designing a system working with steps (like an airline booking, where you pass on various steps to buy a ticket) and these steps are being done via AJAX. So, the index.php file is the sole file loaded and the pages' are being loaded via AJAX on the main div.

The system is working as it should be, but I need to ensure the variables' passing on the subsequent loaded pages, based on the data entered before. E. g.:

I have a form on page 1 where the user enter some data, like his name and country. When clicking submit, the button triggers an AJAX request where the result is the content of page 2, being loaded on the div. But I need that the page 2 have the variables filled with the values on page 1. Page 2 have another form with new data and another submit button. When clicked, it requests via AJAX the page 3 which have to contain the variables at pages 1 and 2. And so on.

Which is the smartest way to do that? Using PHP session? Passing via $.get or $.post?

I request an opinion of you.

Thank you very much.

Upvotes: 2

Views: 4686

Answers (2)

Christian-G
Christian-G

Reputation: 2361

If you are using a library like jQuery - the most easy option is to pass the variables as POST or GET parameters, see: http://api.jquery.com/jQuery.ajax/

For example:

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
  }).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

You can change the type to be GET or POST depending on your needs and the data key should hold the data you wish to send. (in JSON format)

On how to pass the php data as JSON to the js, see passing php variable

Upvotes: 8

Borniet
Borniet

Reputation: 3546

I would go for the

$.post

option of jQuery. http://api.jquery.com/jQuery.post/ Pass all the variables to your PHP script, and let that PHP script generate the new content of the div (next step) with all the variables (new ones + the ones from the post) filled in. If there are variables that should be transferred but not shown to the visitor, use hidden fields to transfer them. BTW: to get the contents of all the inputs in your form via jQuery, use

serialize()

http://api.jquery.com/serialize/ They work together like a charm!

Upvotes: 1

Related Questions