ali3shah ali3shah - 1 month ago 10
Ajax Question

Pass Java Script var to PHP $var

I'm creating a simple chat room that starts with a log in page in

index.php
.

There is a form that sends password variable to
PHP_SELF
and PHP gets the variable and if password was correct , user successfully enters the chat room.

There is a message input that works like a form.

But I cannot use form anymore because if form sends message input,page reloads and User goes at the first (log in page).

So I want to send my
variable
without reloading page.

I have tried using
$var = "document.getElementById('input).innerHTML"
,But this wont return any value!

I have tried using AJAX. Chatroom is
index.php
and my assistant page is
post.php
.

index.php
AJAX works something like this:

var message = 'document.getElementById('input).innerHTML';
$.ajax({
type: "POST",
url: 'post.php',
data: message,
success: function(data)
{
alert("200");

}
});
});


post.php
receives the variable and it sends variable to
index.php
again.
post.php
php:

if(isset($_POST['message'])) $mymsg= $_POST['message'];


And
post.php
AJAX:

var message = '<?php echo $mymsg ?>';
$.ajax({
type: "POST",
url: 'index.php',
data: message,
success: function(data)
{
alert("200");

}
});
});


I mean I want that when user loged in successfully and wrote his message and clicked submit, these will happen.
index.php
receives variable and insert into database table.
But this dont work for me.
Please Say whats wrong, or how can I do that?

Answer

Without reloading your browser you can use javascript

put this before the <body> tag

<script>
$(document).ready(function(){
    $("#varbtn").click(function(){
        var var1 = $("#var").val();

            $.ajax({
                method: "POST",
                url: "post.php",
                data: {
                    var:var1
                    },
                success: function(data){
                //#success will be the id of the div you want to put the response of the php file
                    $("#success").html(data);
                }
            });
    });
}); 
</script>

in the form, you dont need to create <form> tag

<input type="text id="var" />
<button id="varbtn"> Submit</button>

<!--this div will be the result of the post.php file-->
<div id="success"></div>

in the post.php

//will check if the person will direct visit that post.php, this is not secured enough but hes doing his job actually 
<?php 
if(isset($_SERVER['HTTP_REFERER'])){
    if(!isset($_POST['var'])){
        //your codes here
    }
}
?>
Comments