how can i send and get messages from database using AJAX JQUERY - php

I'm building a website using PHP and AJAX JQUERY. And inside this website, there is texting system, like whatsapp, telegram ...etc.
and I'm wanna get all the messages from the database after the user send a message, using jQuery AJAX. so far I have been able to send the text to the database successfully but I fail when I try to get the messages.
I Have this following code when first the page is loaded:
<div class="messaging-frame">
<div class="Title-in-message">
<h4 class="title-message"><?php echo $index['Title'] ?></h4>
</div>
<div class="messaging-box" id="messages">
<?php
// THE MESSAGE FROM MESSAGE TABLE
foreach ($messages as $key => $value) {
if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='sent'>
<p id='send-bubble'> <?php
echo $value['Message'] ?> </p>
</div>
</div>
</div>
<?php
} else { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='recived' id="recieved-bubble">
<p id='recived-bubble'><?php echo $value['Message'] ?></p>
</div>
</div>
</div><?php
}
}
?>
</div>\
Than this code in AJAX jQuery get executed when ever the user send a new message in messaging box:
$(document).ready(function() {
$('#sending_text').click(function() {
var report = $('#report_num').val()
var reportInt = parseInt(report);
var text = $('#text_sent').val();
var encodeText = encodeURIComponent(text);
$.ajax({
url: "<?php echo base_url() . 'DisplayTicket/sendNewText' ?> ",
type: "POST",
data: {
text: text,
reportNum: reportInt
},
success: function() {
$('#messages').load("<?php echo base_url() . 'DisplayTicket/getNewMessages' ?>", {reportNum: reportInt}, function() {
var texts = " <?php foreach ($messages as $k => $val) { if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='sent'>";
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>";
texts += "<?php } else { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='recived' id='recieved-bubble'>"
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>"
texts += "<?php }
} ?>";
texts += "</div>";
$('#messages').html(texts);
})
},
});
});
})
Keep in mind that the $('#messages').html(texts);
is actually get executed but the newest messages in not added

I see you are using .load() method to fill the #messages .
Normally the first argument to this method is the response you wanna insert,and the this is just a callback after success, and you are using a php variable $messages instead of using the response from the request.
I see already 2 ways of doing this:
1 - remove the callback from load() and make sure the response is well written in html as youy want
2 - get rid of load() function, and call another ajax inside success of the first ajax to accomplish so.
The second method is just to make you understand what is wrong. So the best way to do it is to fix load() method accordingly

Related

assign value to php variable using jquery [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i am working on website with buttons each button fire up a bootstrap modal contain data from mysql database i pass a variable from the jquery that fire up the model into a mysql query inside the modal the problam is the php variable cannot get the data send it from the jquery any hints please ?!
i am passing data through jquery post to ajax.php file
the modal code
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<span id="codeElem"></span>
<?php
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode ");// WHERE Code IN ('".$codeArrayStr."')
?>
<?php
$i=0;
$row3 = mysqli_fetch_array($resultHead);
?>
<h4 class="modal-title"><?=$row3['CoopName'];?></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php
$result = mysqli_query($con,"SELECT DISTINCT * FROM reports WHERE host = $getCode GROUP BY host DESC");
?>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<div class="card card-figure has-hoverable">
<figure class="figure">
<img class="img-fluid" src="http://www.iroof.tv/screenshots/<?=$row['screenshot'];?>" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"><?=$row['host'];?></h6>
<p class="text-muted mb-0"> <?=$row['timestamp'];?> </p>
<?php
// Assign JSON encoded string to a PHP variable
$statusJson = $row['status'];
// Decode JSON data into PHP associative array format
$arr = json_decode($statusJson, true);
// Call the function and print all the values
// $result2 = printValues($arr);
echo "<hr>";
echo "<h3> Player </h3>";
// Print a single value
echo "Status: ".$arr["player"]["status"] . "<br>";
echo $arr["player"]["filename"] . "<br>";
echo "<hr>";
echo "<h3> Graphics </h3>";
echo "Display: ".$arr["video"]["display"] . "<br>";
echo "Resolution: ".$arr["video"]["resolution"] . "<br>";
echo "Colors: ".$arr["video"]["colors"] . "<br>";
echo "<hr>";
echo "<h3> System </h3>";
echo "CPU: ".$arr["cpu"] . "<br>";
echo "Ram: ".$arr["ram"] . "<br>";
//echo "Temprature: ".$arr["temperature"] . "<br>";
echo "Fan: ".$arr["fan"] . "<br>";
?>
</figcaption>
</figure>
</div>
<?php $i++;
}
?>
</div>
<!-- Modal footer
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>-->
</div>
the jquery script
<script>
$(document).ready(
function() {
setInterval(function() {
$('.card');
}, 5000); //Delay here = 5 seconds
var gen;
$(".btn").click(function(){
gen = $(this).attr("data-code");
//$.post("ajax.php", {"code": gen},function(data){console.log(data);});
});
$('#myModal').on('shown.bs.modal', function () {
$.post("ajax.php", {"code": gen},function(data){console.log(data);});
//var phpCode = "<? $getCode = $_POST["code"]; ?>";
//$('#codeElem').html(phpCode);
})
});
</script>
ajax.php file
<?php
if(isset($_POST['code']) && isset($_POST['code'])){
//$_SESSION["code"] = $_POST["code"];
$_SESSION['header'] = $_POST['code'];
$getCode = $_POST["code"];
echo $_SESSION['header'];
}
?>
i expect the variable $getCode to get the code from jquery to complete the mysql query inside the modal :
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode");
I dont think its possible to post variables to a modal, I didnt see example like that when I was searching for popup modal login.
guess you need an action page to forvard infos to modal.
This is the solution to post variables:
Change variables to your needs..
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var post_id =$("#mail-id").val();
var name =$("#mail-name").val();
var email =$("#mail-email").val();
var message =$("#mail-message").val();
var type =$("#mail-type").val();
var captcha_code =$("#captcha_code").val();
var submit =$("#mail-submit").val();
$(".form-message").load("heads/comment.php",{
post_id: post_id,
name: name,
email: email,
message: message,
type: type,
captcha_code: captcha_code,
submit: submit
});
});
});
you probably need some thing like this to show variables in popup
<p class="form-message"></p>
Or you can check Bootstrap modal table :
Here

accordion not working after load

I just encountered a problem with jquery accordion. What I am doing is loading new content from a php page "jobsload.php". After updating the page with new content, accordion doesnot work. I have tried the destroy property too but in vain.
here is the code
$('#postjob').click(function () {
//Get the data from all the fields
var title = $('#jobtitle');
var date = $('#jobdate');
var status = $('#status');
var desc = $('#jobdesc');
//Simple validation to make sure user entered something
//If error found, add error-highlight class to the text field
if (title.val()=='') {
title.addClass('error-highlight');
return false;
} else title.removeClass('error-highlight');
if (date.val()=='') {
date.addClass('error-highlight');
return false;
}
else date.removeClass('error-highlight');
if (desc.val()=='') {
desc.addClass('error-highlight');
return false;
}
else desc.removeClass('error-highlight');
var data;
if($("#jobid").val()=="")
{
data = 'title=' + title.val() + '&date=' + date.val() + '&status=' + status.val() + '&desc=' + desc.val();
}
else
data = 'id=' + $("#jobid").val() + '&title=' + title.val() + '&date=' + date.val() + '&status=' + status.val() + '&desc=' + desc.val();
//organize the data properly
// Disable fields
//$('.text-label, .textarea-label').attr('disabled','true');
//show the loading sign
$('.loading-contact').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "postjob.php",
//GET method is used
type: "POST",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
//show the success message
$('.loading-contact').fadeOut('slow');
//show the success message
$('.success-message').slideDown('slow');
$('.success-message').delay(1000).slideUp('slow');
$('#jobsload').load("jobsload.php");
// Disable send button
//$('#send').attr('disabled',true);
//if process.php returned 0/false (send mail failed)
} else
{
$('.loading-contact').fadeOut('slow')
alert('Sorry, unexpected error. Please try again later.');
}
}
});
//cancel the submit button default behaviours
$('#accordion').accordion('destroy').accordion({ heightstyle: "content" });
return false;
});
HTML CODE
<div id="jobsload" style="clear:both">
<div class="panel">
<div class="panel-heading"><center>Available Positions</center></div>
<div class="row">
<?php
$sql = "SELECT * FROM jobs where valid='YES'";
$res = mysql_query($sql) or die(mysql_error());
?>
<div class="personalInfo" id="accordion">
<?php while ($row = mysql_fetch_array($res))
{ ?>
<h6 class="media-heading historyHeading">
<span style="width:80%;"><?php echo $row['title'];?></span>
<span style="width:20%;">(<?php echo $row['date'];?>)</span>
</h6>
<div>
<p><?php echo $row['description'];?></p>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="panel">
<div class="panel-heading"><center>Positions Filled</center></div>
<div class="row">
<?php
$sql = "SELECT * FROM jobs where valid='NO'";
$res = mysql_query($sql) or die(mysql_error());
?>
<ul class="personalInfo">
<?php $mycount=1; while ($row = mysql_fetch_array($res))
{ ?>
<li>
<span>
<div style="width:100%; border:thin #666666">
<div style="float:left; width:5%">
<p style="margin-left:10px; margin-top:5px" >
<?php echo $mycount; $mycount++; ?>
</p>
</div>
<div style="float:left; width:85%">
<h6 class="media-heading historyHeading">
<?php echo $row['title'];?>
</h6>
</div>
<div style="float:right; width:10%">
<h6 class="media-heading historyHeading">
<?php echo $row['date'];?>
</h6>
</div>
</div>
</span>
<div class="clearfix"></div>
</li>
<?php } ?>
</ul>
<!-- add this line to add small portfolio -->
</div>
thank you for your help.
If i'm correct the following code loads your new content:
$('#jobsload').load("jobsload.php");
and not the post call.
You need to re-initialize ajaxloaded content, because it's not in the dom, when jquery is initialized.
In the answer Kuma, the accordion is triggered at the same time as the load is being called. Not after the success of the code.
See code beneath to use the success function of the jobsload
$('#jobsload').load("jobsload.php", function( response, status, xhr ) {
if (status == "success") {
// Place reload the accordion code here
}
if ( status == "error" ) {
// optional: place error code here.
// if you don't place this, user will not receive notification of failure.
}
});
You should apply the accordion inside your success function.
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
//show the success message
$('.loading-contact').fadeOut('slow');
//show the success message
$('.success-message').slideDown('slow');
$('.success-message').delay(1000).slideUp('slow');
$('#jobsload').load("jobsload.php");
// Disable send button
//$('#send').attr('disabled',true);
//if process.php returned 0/false (send mail failed)
//cancel the submit button default behaviours
$('#accordion').accordion('destroy').accordion({ heightstyle: "content" });
return false;
} else
{
$('.loading-contact').fadeOut('slow')
alert('Sorry, unexpected error. Please try again later.');
}
}

php mysql + ajax + jquery + delete action

i am creating a comment system using the php and mysql to store data and ajax with jquery all the system work well but when it comes to the delete action nothing it happen like this button do not have any action or relation with the system can anyone help me ???
comment_box.php
<li class="comment-holder" id="_<?php echo $comment->comment_id; ?>">
<div class="user-img">
<img src="<?php echo $user->profile_img; ?>" class="user-img-pic" />
</div>
<div class="comment-body">
<h3 class="username-field">
<?php echo $user->userName; ?>
</h3>
<div class="comment-text">
<?php echo $comment->comment; ?>
</div>
</div>
<div class="comment-buttons-holder">
<ul>
<li id="<?php echo $comment->comment_id; ?>"class="delete-btn">X</li>
</ul>
</div>
</li>
comment_delete.js(i am testing the delete button with firebug)
$(document).ready(function() {
$('.delete-btn').each(function() {
var btn = this;
$(btn).click(function(){
console.log("the id " + btn.id);
})
});
});
Try this
$(document).ready(function() {
$('.delete-btn').each(function(i,el) {
$(el).click(function(){
console.log("the id " + $(this).attr('id'));
})
});
});
<li id="<?php echo $comment->comment_id; ?>"class="delete-btn">X</li>
Since you are missing whitespace here between the id value and the class attribute, I think the browser just does not assign that class to the element.
Edit (for people who don’t know what “missing” means):
Your PHP code will generate HTML output of the form
<li id="123"class="delete-btn">X</li>
whereas it should of course be
<li id="123" class="delete-btn">X</li>
Please always validate your HTML code before asking questions.
Try
$(document).ready(function() {
$('.delete-btn').click(function() {
var comment_id = $(this).attr('id');
alert(comment_id);
});
});

Cant get the value in div class="rateit" readonly mode after ajax call

I am using Jquery RateIt plugin with the view more button.
so In my project i am showing restaurant rating with these plugin by default i am displaying first 5 rating.Then after 5 records i am displaying other content through ajax so in the content loded through ajax rating is not being showd i am using readonly mode..If anyone can help thanks in advance
foreach($list_review as $row): ?>
<div class="user_reviews_data">
<div class="width-20 float-left">
<span class="padleft-10"><?php echo $row->User; ?> </span>
<br/>
<span class="padleft-10">
**<div class="rateit" data-rateit-value="<?php echo $row->Rating;?>" data-rateit-ispreset="true" data-rateit-readonly="true"></div>**
</span>
<div class="muted padleft-10 float-left"><small><?php echo date('dS M Y' ,strtotime($row->CreatedDate)); ?></small></div>
</div>
<div class="width-80 float-left"><?php echo $row->Feedback;?></div>
<span class="report_span">Report this Feedback <img src="<?php echo base_url();?>themes/images/FLAG_GREY.png"></span>
</div>
<?php
$msg_id=$row->Id;
endforeach;?>
</div>
<div id="more<?php echo $msg_id; ?>" class="btn-container center_text morebox">
View More
</div>
Now code of jquery
/*view More Button*/
$('.more').live("click",function()
{
var this_tag = $(this);
var ID = $(this).attr("id");
if(ID)
{
$.post(siteUrl+"ajax/ajax_more",{lastmsg:ID,restid:$(this_tag).data("restid")},function(html){
$("ol#updates").append(html);
$("#more"+ID).remove();// removing old more button
});
}
else
{
$(".morebox").html('The End');// no results
}
return false;
});
I am adding content on view more button click through ajax ajax code is same as above code
I am Using this plugin http://www.radioactivethinking.com/rateit/example/example.htm
In the $.post success handler you should invoke rateit again via JavaScript after you append the HTML like so:
$("ol#updates").append(html);
$(".rateit").rateit();
Replace $(this_tag) with either this_tag or $(this) in your ajax call.
You should use var this_tag = this; instead of using var this_tag = $(this);
OR try var $(this_tag) = $(this);

append data to webpage by iterating json object returned (echo) by php

I am using cakephp to develop a webpage that dynamically append data retrieved from server. The appended data can be turned in jquery accordions (not shown).
I've tried some suggestions as seen in other topics, but still nothing shows up on the webpage.
The javascript is as such:
<script type="text/javascript">
$.getJSON('viewmjcatjson.ctp', function(data){
var content = '<div id="majorcat">\n';
$.each(data, function(index,cat){
content += '<h2>' + cat.category + '</h2><div>\n';
content += cat.description + '</div>\n';
});
$("#majorcat").append(content);
});
</script>
The 'viewmjcatjson.ctp' is as such:
<?php
Configure::write('debug', 0);
echo json_encode($majorCategories);
?>
The json object returned is valid (checked with jsonlint)
[{
"MajorCategories":{
"category":"Corporate Governance",
"description":"description on Corporate Governance"
}
},
{
"MajorCategories":{
"category":"Earnings Report",
"description":"description on Earnings Report"
}
},
{
"MajorCategories":{
"category":"Equity",
"description":"Relating to stock"
}
},
{
"MajorCategories":{
"category":"Financial Issue",
"description":"The area of finance dealing with monetary decisions that business enterprises make and the tools and analysis used to make these decisions"
}
}
]
I am suspecting something is wrong in the each loop, but I am not sure.
EDIT
The entire php file containing the javascript.
<?php echo $html->script('jquery-1.5.1.min.js'); ?>
<?php echo $html->script('jquery-ui-1.8.13.custom.min.js'); ?>
<?php echo $html->css('ui-lightness/jquery-ui-1.8.13.custom.css'); ?>
<script type="text/javascript" src="development-bundle/jquery-1.3.2.js"></script>
<script type="text/javascript" src="development-bundle/ui/ui.core.js"></script>
<script type="text/javascript" src="development-bundle/ui/ui.accordion.js"></script>
<div class="users form">
<h1><?php echo $article['Article']['title']?></h1>
<p><small>Author: <?php echo $article['Article']['author_all']?></small></p>
<p><?php echo $article['Article']['full_text']?></p>
<br>
<hr>
<br>
<table>
<tr>
<td width="60%">
<div id="majorcat">
</div>
</td>
<td width="40%">
<div id="minorcat">
</div>
</td>
</tr>
</table>
</div>
<div class="actions">
<h3><?php __('Menu'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Logout', true),
array('controller' => 'users', 'action' => 'logout'));?></li>
</ul>
</div>
<script type="text/javascript">
$(function(){
$.getJSON('viewmjcatjson.ctp', function(data){
var content = '<div id="majorcat">\n';
$.each(data, function(index,cat){
content += '<h2>' + cat.category + '</h2><div>\n';
content += cat.description + '</div>\n';
});
$("#majorcat").append(content);
});
})
</script>
<script type="text/javascript">
$(function(){
$.getJSON('viewmjcatjson.ctp', function(data){
var content = '<div>';
$.each(data, function(index,cat){
content += '<h2>' + cat.MajorCategories.category + '</h2> <div>';
content += cat.MajorCategories.description + '</div>';
});
$("#majorcat").append(content);
});
})
</script>
You're missing the document.ready
I noticed Firebug console showing that 'viewmjcatjson' is responding not with json-encoded data but with a HTML file. The contents is actually exactly the same as the PHP file.
So I deduced it could be a routing problem.
Changing to...
$.getJSON('../viewmjcatjson', function(data){
...solves the problem.
Thanks Interstellar_Coder for the fixed code though.

Categories