Reputation: 27
I have a form with 2 button send_btn
& receive_btn
and a text input. What i want to do is if send_btn
is clicked then the messages will show from right side(i.e float right) and when receive_btn
is clicked then the messages will show from left side(i.e float left).I used ajax jquery to call the php file but if i set a if condition to check button click there is no output no error. Here is my code
HTML--
<div class="msgpostsec">
<form id="msgform" action="upload.php" method="POST">
<label for="date">Date:</label>
<input type="date" id="date" name="date" style="border-radius:5px;border:1px solid #5B5151;margin-bottom:12px;"/> <br />
<label for="time">Time:</label>
<input type="time" id="time" style="border-radius:5px;border:1px solid #5B5151;" name="time"/><br /><br />
<label for="message">Message</label>
<input type="text" id="message" name="msg_txt"/>
<input type="submit" id="send_btn" name="send_btn" value="Send" class="btn btn-success" style="border-radius:5px;" />
<input type="submit" id="receive_btn" name="receive_btn" value="Receive" class="btn btn-warning" style="border-radius:5px;" />
</form>
</div>
PHP--
<?php
session_start();
// session_destroy();
$msg_array = array(
'msgtosend' => $_POST['msg_txt'],
'msgtoreceive' => $_POST['msg_txt'],
'date' => $_POST['date'],
'time' => $_POST['time']
);
$_SESSION['send_msg'][] = $msg_array;
if (!empty($_SESSION['send_msg']) && isset($_SESSION['send_msg'])) {
foreach ($_SESSION['send_msg'] as $keys => $values)
{
$output='<p>'.$values["msgtosend"].'</p>';
$output2='<p>'.$values["msgtoreceive"].'</p>';
}
}
if (isset($_POST['send_btn'])) {
echo $output;
} else if (isset($_POST['send_btn'])){
echo $output2;
}
?>
AJAX JQUERY--
$(document).ready(function () {
$('#msgform').on('submit',(function(e) {
e.preventDefault();
var post_url = $(this).attr("action");
var request_method = $(this).attr("method");
var form_data = $(this).serialize();
$.ajax
({
url: post_url,
type: request_method,
data:form_data,
success: function(response)
{
$("#out_msg").html(response);
console.log(response);
},
error: function()
{
},
});
});
});
Upvotes: 1
Views: 981
Reputation: 4825
The button value won't be sent along via AJAX because on submit()
via serialize()
, jquery won't know the button that was clicked. What you can do is add a hidden field and check in PHP
<input type="hidden" name="hidden_field" id="hidden_field" value="form_check">
<?php
if (isset($_POST['hidden_field']) && $_POST['hidden_field'] === 'form_check') {
#proceed
}
Upvotes: 1