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?
|
2 answers
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 } }); }); |
$_POST['input_name'], but if it is justvar- 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