Remove records without reloading the page with AJAX - php

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();
}
},

Related

Ajax only gives data after page reload

I am trying to create a notification button for an inactive article for my blog and I don't want admin to reload his/her page to see a new inactive article submitted, so I want to do this with AJAX.
I prepend html data to:
<ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">
But my code only loads an new result after page reload.
Also, the each loop is repeating same data 2 times.
What's going wrong?
<script>
$.ajax({
type: "POST",
url: 'inc/file.php',
dataType: 'json',
success: function(response)
{
if (response) {
var html = '';
$.each(response, function(key, value){
html += "<li><a href='editArticle?id="+response.id+"&act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";
})
$('#menu1').prepend(html);
$('#number').text(response.number);
}
}
});
</script>
Here is my file.php while is fetching only one data:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/config/init.php';
require CLASS_PATH.'article.php';
$article = new Article();
$list = $article->getInactiveArticle();
$number = $article->countInactiveArticle();
$output = [];
foreach ($list as $lists) {
$output['title'] = $lists->title;
$output['id'] = $lists->id;
$output['story'] = $lists->story;
$output['number'] = $number[0]->inactive_articles;
}
echo json_encode($output);
You can test the following code block.
It checks every 5 seconds and performs the operations.
$(document).ready(function () {
var eint = window.setInterval(function () {
$.ajax({
type: "POST",
url: 'inc/file.php',
dataType: 'json',
success: function(response)
{
if (response) {
var html = '';
$.each(response, function(key, value){
html += "<li><a href='editArticle?id="+response.id+"&act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";
})
$('#menu1').prepend(html);
$('#number').text(response.number);
}
}
});
},5000);
)};
Try to use setTimeout() function.
function timeout() {
setTimeout(function(){
$.ajax...
timeout()
}, 3000);
}
Have a look docs here

send Images in chats using PHP + jQuery + MYSQL

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.

Get results and fade

Don't know what is wrong, I've tried everything. The code should take simple info from PHP file and for each should fade in delay and out. I was successful with getting all the data at once but it is not good.
<script type="text/javascript">
$('button').fadeOut('slow')
var progressBar = $('.progress-bar');
var percentVal = 0;
window.setInterval(function(){
percentVal += 10;
progressBar.css("width", percentVal+ '%').attr("aria-valuenow", percentVal+ '%').text(percentVal+ '%');
if (percentVal == 100)
{
percentVal = 0;
}
}, 500);
$(document).ready(function() {
$("button").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "submit.php",
data: 'html', //expect html to be returned
success: function(data){
for(var i=0;i<6;i++){
$('.input-group').html(data).fadeIn(500).delay(1000).fadeOut(500);
}
}
});
});
});
</script>
PHP CODE:
$array= ['apple','orange','grapes','avocado','banana'];
$indexedOnly = array();
foreach ($array as $row) {
$indexedOnly[] = array_values($row);
}
echo json_encode($indexedOnly);
I think you need to abandon the loops, they wont allow you to pause to wait for the animation to finish. You can try something like this where you handle each element in data then using the callback functions of .fadeIn and .fadeOut to call the next one
function disp_next() {
$('.input-group').text(data.shift()).hide();
$('.input-group').fadeIn()
.delay(1000)
.fadeOut(function(){
if(data.length !== 0) {
disp_next();
}
})
}
disp_next();
You also need to change your dataType to json as you are expecting json from the server. Here is your jquery updated
$(document).ready(function() {
$("button").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "submit.php",
datatype: 'json', //expect html to be returned
success: function(data){
data = Object.values(data);
function disp_next() {
$('.input-group').text(data.shift()).hide();
$('.input-group').fadeIn()
.delay(1000)
.fadeOut(function(){
if(data.length !== 0) {
disp_next();
}
})
}
disp_next();
}
});
});
});
Try something like this, but if you want the animation of each element to wait for the previous one to finish you need to change the approach.
$.each(data, function(i, value) {
$('.input-group').html(data).fadeIn(500).delay(1000).fadeOut(500);
});

trouble in call a ajax file in jquery

This below coding is working in chrome browser but not in mozilla. How to solve this problem in mozilla firefox.
$(document).ready(function() {
$("#del_enquiry").click(function() {
var enquiry = new Array();
$('input[name="del_enq"]:checked').each(function() {
enquiry.push(this.value);
});
if(confirm("Do you want to delete the Records"))
{
var delid="deleteid="+enquiry;
$.ajax({
url: "delete_enquiry.php",
type: "POST",
data: delid,
cache: false,
success: function(data) {
if(data==1) {
alert("Record Deleted Successfully");
} else {
alert("Record not Deleted");
}
}
});
}
});
});
You can use onsubmit atttribue of form tag function before submitting the form.
Inside my function write your confirm box conditions.
if(confirm("Do you want to delete?"))
{
return true;
}

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