M
M
ma4t2019-01-20 13:51:17
PHP
ma4t, 2019-01-20 13:51:17

Ajax output from a form to a file, how?

I don't know php at all and I don't know how to work with Ajax.
I'm trying to send the text entered by the guest from the form to a separate file, but I can't figure out how to correctly format this data in JS and how to correctly accept it in php.
Tried to first set it like this
var getMail = $('.form-back__window').children('form').children().first().val();
var getName = $('.form-back__window').children('form').children().first().next().next().val();
var getNumber = $('.form-back__window').children('form').children().last().prev().prev().val();
var send = "mail: " + getMail + ", Name: " + getName + ", Number: " + getNumber;

and send the send variable, but I didn’t figure out whether it’s possible to extract in php what what she keeps.
Then did this

var send = {
"mail": getMail,
"name": getName,
"number": getNumber
}
console.log(send);

$.ajax({
type: 'POST',
url: "../php/main.php",
dataType:'json',
data:"send2"+JSON.stringify(send),
success: function(){
$ ('.form-back__window').children('form').hide();
$('.form-back__window').val('Reply received, thanks!');
}
});

tried to google how to process it, it turned out

if($_POST['send2']) {
$send2 = json_decode($_POST['send2']);
$row2 = get_text($send2->name);
$row3 = get_text($send2->number);

$file = fopen("GuestData.txt", "a");
fwrite($file, json_encode($row1));
fwrite($file, json_encode($row2));
fwrite($file, json_encode($row3));
fclose($file);
}

The idea is simple, but how it is sawn, xs.

Here is the hmtl form














Please suggest

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
NonameMeTrue, 2019-01-20
@ma4t

For the client side:

$.post('/youURL', $('form').serialize(), function (response) {
    //Code 200.
})

It is better to specify a more precise selector for the desired form, for example: On the server, check whether the parameters have arrived (key = name attribute in each input tag). If yes, write down:
if(!empty($_POST['name']) && !empty($_POST['other'])) {
  $filename = 'GuestData.txt';
  $somecontent = $_POST['name']."\r\n";
  if (is_writable($filename)) {
    if (!$handle = fopen($filename, 'a')) {
      //die();
    }
    if (fwrite($handle, $somecontent) === false) {
      //die();
    }
    fclose($handle);
    //return some
  }
}

This is just an example. On the server side, specify the parameters you need for full performance.

M
ma4t, 2019-01-20
@ma4t

Something html form didn't submit

J
Johny, 2019-01-20
Marx

The most convenient way is to use FormData, which creates sets of key-value pairs, then sends it using the POST method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question