A
A
Alexander Babiy2019-02-26 23:10:33
JavaScript
Alexander Babiy, 2019-02-26 23:10:33

How to get the value of the post parameter when sending mail via ajax request?

I send mail from the landing form.
On submit, it executes an ajax request with sending data to the php mail send file.
Everything works fine. Now I want to add identification by the POST request parameter, for example, by name.
I found a recommendation on how to do this.

<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["name"]);
</script>

I place this code in the php file after closing ?> But when submitting the form data, I get the error
SyntaxError: Unexpected token < in JSON at position 3
How to correctly pass the POST parameter to JS?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Marat Garifullin, 2019-02-26
@magarif

Apparently, you have to return json from the script to browsers.
Write before ?>
echo json_encode(['name' => $_POST['name']]);
And after ?> delete everything

A
Alexander Babiy, 2019-02-26
@ABabiy

As soon as it appears either before <?php or after ?> code of even empty opening and closing tags

?>
<script type="text/javascript">
  
</script>

Immediately I
get SyntaxError: Unexpected token < in JSON at position 11

D
Dmitry, 2019-02-28
@dmitrytyt

Have you tried adding quotes?

<script type="text/javascript">
    var $_POST = '<?php echo json_encode($_POST); ?>';
    document.write('$_POST["name"]');
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question