S
S
Sergey Suntsev2015-11-25 12:44:07
PHP
Sergey Suntsev, 2015-11-25 12:44:07

How to pass variable values ​​from JS to PHP via AJAX in one file?

There is a file 1.php in it there is a js code, there is a need to translate it into php.
I know that it can be done through ajax. I can pass values ​​from js file to php.

$.ajax({
                type: "POST",
                url: "gen.php",
                data: {"text" : new, "user_id" : user_id, "text" : text},
                success: function(data){
                    title = data;
                }
            });

But is it possible to do it in the same file? Without referring to gen.php?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anton Perevoshchikov, 2015-11-25
@GreyCrew

Alexander Wolf wrote to you, everything works

<?php if(isset($_POST['messag'])) {
  exit($_POST['messag']);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
  var messag = 'answer';
  $.ajax({
    type: "POST",
    data: {
      "messag" : messag
    },
    success: function(data){
      console.log(data)
    }
  });
</script>

A
Alexander Wolf, 2015-11-25
@mannaro

<?php
if(isset($_POST['user_id'])) {
  // обрабатываем
}
?>
<script>
$.ajax({
                type: "POST",
                url: ".",
                data: {"text" : new, "user_id" : user_id, "text" : text},
                success: function(data){
                    title = data;
                }
            });
</script>

E
Evgeny_Popov, 2015-11-25
@Evgeny_Popov

So you can generate the js code itself from php

Y
Yuri, 2015-11-25
@kapitan7830

You can, if you write in the file something like

if ( $_SERVER["REQUEST_METHOD"] == "POST" ) {
  //код обработки формы
} else {
  //а здесь html и скрипт
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question