Brian Ona
Brian Ona

Reputation: 23

Passing variables from javascript via ajax to php

I am new to jquery and ajax. I have a script here where i need to pass variables to a php file. That php will be then encoded to div#chat-body. I am trying to pass the receiver variable to the load-messages.php via POST but I am getting the following error: "Undefined index: receiver in xxxx/scripts/load_messages.php on line 8". I think there is something wrong with my syntax or im doing this totally wrong.

script.js

$('input#send-message').on('click', function(){
alert("test");
var message = $('input#input-message').val();
var sender= $('input#sender').val();
var receiver= $('input#receiver').val();

    if($.trim(message)!=''){
        $.post('scripts/messaging.php', {message: message, sender: sender, receiver:receiver}, function(data){
        //output after sending message  

        });     
        //load message to  chat-body div

        $.ajax({
        url: 'scripts/load_messages.php',
        type: "POST",
        data: {receiver: receiver},
        success: function(data){
            $('#chat-body').html(data);
            //$('#chat-body').scrollTop($('#chat-body')[0].scrollHeight); 
        }
    });
    }});

load-messages.php

 <?php 
    session_start();
    require('config.php');
    require('chat_functions.php');


$messages = get_msg($_SESSION['user_id'], $_POST['receiver']);

foreach($messages as $message){
    if($message['sender'] == $_SESSION['user_id'])  {
        ?><div id = "you_message">

        <?php echo '<strong> You: </strong><br />';
        echo $message['message'].'<br /><br />';?>
        </div><!--you_message-->
        <?php   
    }

    else{
        ?><div id="recipient_message">
        <?php echo '<strong>'.get_name($_POST['receiver']).'</strong><br />';
        echo $message['message'].'<br /><br />';?>
        </div> <!--recipient_message -->
        <?php
        }
    }

    ?>

Upvotes: 2

Views: 8451

Answers (3)

Sasi Rekha
Sasi Rekha

Reputation: 223

It's just simple to pass the values to php file through AJAX call. Change your AJAX call as shown in below

var message = $('#input-message').val();
var sender= $('#sender').val();
var receiver= $('#receiver').val(); 
$.ajax({
    url: "scripts/load_messages.php", 
    method: "post", 
    //data: { "message":$('#input-message').val(),"sender":$('#sender').val(),"receiver":$('#receiver').val()},you can pass the values directly like this or else you can store it in variables and can pass
    data: { "message":message,"sender":sender,"receiver":receiver},
    success: function(data){
    $('#chat-body').html(data);
    },
     error: function() {
    alert('Not OKay');
    } 
   });

and your load-messages.php could be like this`

$receiver = $_POST['receiver'];
echo $receiver;

Upvotes: 2

OldPadawan
OldPadawan

Reputation: 1251

you can try this then adapt it to your needs, as I just made it a little bit more 'basic' :

your form :

<form action="#" id="form" method="post">
<input type="text" id="sender" name="sender" />
<input type="text" id="receiver" name="receiver" />
<input type="text" id="input-message" name="input-message" />
<input type="submit" id="send-message" value="Post" />
</form>

<div id="chat-body" class="regular"></div>

the jQuery part :

$(document).ready(function(){

$("#send-message").click(function(e){
e.preventDefault(); /* to prevent form default action */

var message = $('#input-message').val();
var sender = $('#sender').val();
var receiver = $('#receiver').val();

    $.ajax({
    url: "load_messages.php",
    method: "POST",
    data: { message: message, sender: sender, receiver:receiver },
    success: function(html){
        alert(html); /* checking response */
        $('#chat-body').html(html); /* add to div chat */
    }
  });
 });
});

then, load_message.php

<?php

error_reporting(E_ALL); ini_set('display_errors', 1);

$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$message = $_POST['message'];

echo"[ $sender / $receiver / $message ]"; /* here, you can only echo $message for instance, 
then use response to append message to chat window */

?>

Upvotes: 0

tiepnv
tiepnv

Reputation: 336

You're passing an object, not a JSON string :

$.ajax({
  type: 'POST',
  url: 'scripts/messaging.php',
  data: JSON.stringify ({receiver: receiver}),
  success: function(data) { alert('data: ' + data); },
  contentType: "application/json",
  dataType: 'json'
});

Upvotes: 0

Related Questions