send Images in chats using PHP + jQuery + MYSQL - php

I have a chat application which works absolutely fine for sending and receiving texts only but I want to send images/videos/ files through it.
This is the main home page which display the chats.
<script>
$ = jQuery;
var currentID = null;
var chatTimer = null;
var oldhtml="";
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#chatbox").show();
$('#messages').html(data);
$("div.area").show();
if(oldhtml!==data) {
$('#messages').scrollTop($('#messages')[0].scrollHeight);
}
oldhtml=data;
}
});
}
$(document).ready(function() {
fetch_data();
setInterval(function() {
fetch_chat();
}, 500);
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
fetch_chat();
});
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
});
});
</script>
and below is the fetch_chat.php which fetches the chat from databases.
<?php
require("config.php");
$user_to = $_POST['id'];
$res1=$db->query("select * from chats where user_from='$_SESSION[id]' AND
user_to='$user_to' OR user_to='$_SESSION[id]' AND user_from='$user_to' order
by id");
if($res1->num_rows){
while($row=$res1->fetch_object()){
if($row->user_from === $_SESSION["id"] ) {
echo "<div class='chat self'>
<div class='user-photo'><img src='img/user1.jpg'></div>
<p class='chat-message'> $row->msg</p>
</div>";
} else {
echo "<div class='chat friend'>
<div class='user-photo'><img src='img/user2.jpg'></div>
<p class='chat-message'>$row->msg</p>
</div>";
}
}
} else
echo "No msgs <br />";
?>
Now I want to save the info of the uploaded file in the database and the files into a folder/directory. The sender and receiver should be able to send and view the files respectively.

Related

jquery passing variable to php

when i try get and echo the variable on php, sending by ajax, i receive always var_dump null
the alert is ok, he shows the current slide id number when <a>(role=button) prev or next is clicked: 1 on slide 1, 2 on 2, 3 on 3;
<script>
$("#myCarousel").on('slide.bs.carousel', function(e) {
var value1 = $(this).find('.carousel-item.active').attr('id');
alert(value1);
var value = {
idCarrosselAtivo: $(this).find('.carousel-item.active').attr('id')
}
$.ajax({
type: "POST",
url: "teste.php",
data: value,
success: function(data) {
console.log(data);
}
});
})
</script>
<?php
if(isset($_POST['idCarrosselAtivo'])&& $_POST['idCarrosselAtivo'] === 'c1') {
echo $idCarrossel;
} else {
var_dump($idCarrossel);
}
?>
Consider this example.
jQuery
$("#myCarousel").on('slide.bs.carousel', function(e) {
console.log("Sending ", $(this).find('.carousel-item.active').attr('id'));
$.ajax({
type: "POST",
url: "teste.php",
data: {
idCarrosselAtivo: $(this).find('.carousel-item.active').attr('id')
},
success: function(data) {
console.log(data);
}
});
});
PHP
<?php
if(isset($_POST['idCarrosselAtivo'])){
$idCarrossel = $_POST['idCarrosselAtivo'];
if($idCarrossel === 'c1') {
echo $idCarrossel;
} else {
var_dump($_POST['idCarrosselAtivo']);
}
}
?>
It's not clear why you are sending back the ID when you just sent it to the script. This will send the ID and get some PHP back.

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

Ajax sends data , but returns nothing

I have got this html
<div class="Likes" data-i=<?php echo $row[8];?>>
<img src="../img/like.png">
<p class="L_c"><?php echo $row[4];?></p>
</div>
And this jquery/ajax
$(".Likes").click(function() {
var i = $(this).attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
$(this).children(".L_c").html(data);
}
});
});
Connect.php
if (isset($_GET["I"]) && !isset($_GET["C"])) {
$RandS=$_GET["I"];
$query3=$con->query("SELECT id,likes FROM uploads WHERE Rand='$RandS'");
$row=$query3->fetch_row();
$IdU=$row[0];
$Likes=$row[1];
$Sel2=$con->query("SELECT id FROM likes WHERE User_id='$NameId' AND Post_id='$IdU'");
$num_rows=$Sel2->num_rows;
if ($num_rows>0) {
echo $Likes;
}else{
$query=$con->query("INSERT INTO likes (Post_id,User_id,`DATE`) VALUES('$IdU','$NameId',NOW())");
$query=$con->query("UPDATE uploads SET Likes=$Likes+1 WHERE Rand='$RandS'");
echo $Likes+1;
}
}
But it does not return anything untill i refresh the page
The this keyword inside the $.ajax methods callback is not the element, but the ajax call itself.
You have to either set context, or just store the outer this -value
$(".Likes").on('click', function() {
var me = $(this);
var i = me.attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
me.find(".L_c").html(data);
}
});
});

Remove records without reloading the page with AJAX

When I delete a record from database by Ajax I think you should try reloading the page until the page is deleted Is there a way to solve this problem, there
this is the jquery code
jQuery(document).ready(function ($) {
$('#del>a').click(function(){
$.post(
'ajax.php',
{ delid:$(this).next('input').val() },
function(data)
{
$('#result').html(data);
})
})
});
this is the php code
if(isset($_POST['delid']))
{
$id = mysql_real_escape_string($_POST['delid']);
$admin->DeleteItem($id,'news');
}
if(isset($_POST['delid']))
{
$id = mysql_real_escape_string($_POST['delid']);
$del = $admin->DeleteItem($id,'news');
if($del)
{
echo "deleted";
}
}
not function(data) its success: function(data)
success: function(data) {
if(data=="deleted")
{
$(this).hide();
}
},

jquery get data from controller using json_encode

ajax function
<script type="text/javascript">
var timeOutID =0;
var checkScores = function () {
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/countScoreCh',
success: function(response) {
if(response == false){
timeOutID = setTimeout(checkScores, 3000);
} else {
jsn = JSON.parse(response);
score= jsn.scoreCH;
$('#progressbar').progressbar({
value: score
});
clearTimeout(timeOutID);
}
}
});
}
timeOutID = setTimeout(checkScores,1000);
</script>
Controller
public function countScoreCh(){
$id = $this->session->userdata('userID');
$data['getScore'] = $this->lawmodel->battleUserID($id);
foreach($data['getScore'] as $row){
$scoreCH = $row->challengerScore;
echo json_encode(array('scoreCH' => $scoreCH));
}
}
Im having a problem..im using a progress bar..my idea is making the progress bar like a Hit Point/Health bar..but it seems that when i put the $('#progressbar').progressbar it will not get the value from jsn.scoreCH..jst disregards the response == false it still working i tried using console log..But when i put this code..it will not be read and display the output..
$('#progressbar').progressbar({
value: score
});
You can omit JSON.parse(response). Just use dataType: 'json'
$.ajax({
url: "http://127.0.0.1/ProgVsProg/main/countScoreCh",
dataType: 'json'
success: function(response) {
if(response.scoreCH == undefined){
timeOutID = setTimeout(checkScores, 3000);
} else {
$('#progressbar').progressbar({
value: response.scoreCH
});
clearTimeout(timeOutID);
}
}
});

Categories