Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 313
Filipe Fonseca Avatar asked Jun 18 '26 15:06

Filipe Fonseca


1 Answers

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

like image 58
Christian-G Avatar answered Jun 21 '26 04:06

Christian-G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!