I have a form on my site from which to collect data. The fact is that: 1) this data is not only in <input> , but also in different <div> , <span> and attributes. So, I need to collect this data using jQuery. Question: how can I parse this data on php? 2) on the PHP side, I need to validate this data (which I know how to do) and if everything is in order, then I need to redirect the user to another page, from which, with the help of ajax, request this same data. Question: is this done with the help of sessions and how can this be implemented in general?

  • one
    Collect in object, serialize in JSON and send in PHP - a script. The script must respond with validation results. How to transfer data between scripts is up to you. Can and sessions. - ilyaplot
  • 1) Send the form or ajax to your php processing page. 2) At the end of the validation, the php page can immediately redirect the user to another page and insert the data extracted from the 1st page (after all, this is all one action - reception + validation + redirection + forwarding of data). Not? Or am I confusing something ? Alexoander
  • @alexoander yes, this is all exactly the case, but I would like examples of how to get data on the PHP side, if they are not from the form (if you get data from the form, it will be $_POST['input_name'] , but if it is just var - variable in js code, how then?). Well, an example of how to remember the data sent to the php-file, so that after the reader it can be taken. - JamesJGoodwin

2 answers 2

Suppose you have a block with data:

 <div> <span id="data1">1</span> <div id="data2">2</div> <textarea id="comment">comment</textarea> </div> 

You collect data either $ ('form'). SerializeArray () is if the form, if in this example, you can simply by id or by class.

 var data = { data1: $('#data1').text().trim(), data2: $('#data2').text().trim(), comment: $('#comment').text().trim(), } 

Therefore, this data is sent to the server. The jQuery function is called Ajax

We send data

  $.ajax({ url: 'test.php', dataType: 'json', method: "post", data: { data:data }, success: function (response) { alert('Всё прошло гладко'); }, error: function (xhr) { alert('Ошибка'); } }); 

In the test.php file you can already work with the data.

 $data = $_POST['data']; 

    You can, for example, create new inputs on the fly when sending a form by clicking on a button with id = pay-invoices . Example with ajax request

     $(document).on('submit', '#pay-invoices', function (e) { e.preventDefault(); var input = $('input[name=invoices]').val(JSON.stringify(selectedInvoices)); var $form = $(this); $form.append($(input)); $.ajax({ url: $form.attr('action'), type: $form.attr('method'), data: new FormData($form[0]), processData: false, contentType: false, success: function (response) { // do something }, error: function (response) { // do something } }); });