Get results and fade - php

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

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

Ajax data isn't being received by php

Hello overflowers!
I can't seem to manage to send my ajax data over to my php page correctly, it has worked perfectly fine before but now it is not working.
I'm getting the correct data via console.log but on my php page i'm getting Undefined index error.
Jquery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$("#new-task").on('submit', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {task_takers_pre : task_takers_pre },
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_submit'])){
$task_takers = $_POST['task_takers_pre'][0];
var_dump($task_takers);
}
EDIT
jQuery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$(".assign").on('click', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: './core/includes/new_task.php',
cache: false,
data: {task_takers_pre : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {'task_takers_pre' : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_takers_pre'][0])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
}
if(isset($_POST['task_takers_pre'])){
$task_takers2 = $_POST['task_takers_pre']; // Just for testing
var_dump($task_takers2); // Just for testing
}
What you are attempting to do is use the same PHP code to handle the Button Press from the Form AND the AJAX Call. Don't!
(note: This answer is Only based upon the code that has been provided and what is trying to achieved with this code.)
So your current PHP is, which I am guessing is what you call when you click the submit button... In that case $_POST['task_takers_pre'] will not exist as you are generating that from the JS and sending it in the AJAX Call.
Write a separate AJAX Call.
You need to create a separate file to handle your AJAX calls and have it perform what duties it needs to perform.
// This is just for testing my AJAX Call
public function ajax_post(){
if(isset($_POST['task_takers_pre'])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
die();
}
else {
// Illegal access/entry do something...
echo 'Error - I had better check what I am posting.';
die();
}
}
If you juse want to send some data in the AJAX Call when you click the submit button,you could return false to prevent form submission in the submit event.
$("#new-task").on("submit", function(){
$.ajax({
type: "POST",
url: "",
cache: false,
data: {task_submit:1, task_takers_pre: task_takers_pre},
success: function(data){
console.log(data);
}
});
return false;
});

Merging localstorage with ajax

How would I merge these two bits of code and can someone explain what the key and value would be.
I'm building a notifications system and I'm wanting to store the last new notification_id but not have it inserted into the div over and over again if its the same one, so then the ajax searches for anything else within my server that maybe new.
Ajax
<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(dataHandler){
}
});
}
setInterval(loadIt, 10000);
</script>
Localstrorage
window.localStorage.setItem('key', 'value');
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
You've confused oldschool Ajax by hand with jQuery. The parameter to the success function in jQuery is not a function name or handler. Its a variable name that will contain the response from the server. The success function itself is equivalent to the handler functions you would have created doing it the old way.
So not:
success: function(dataHandler){ }
...
...
var dataHandler = function (response){
But rather:
success: function(response) { doCallsToSaveToLocalStorage(response); }

jquery-ajax not posting data

Refer to the following code, this script doesn't post the "limit" variable to the next page
MY JS Code:
$(document).ready(function(){
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
var dataString="2";
$.ajax({
type:"POST",
url: "load_data.php",
data: { 'limit': dataString },
success:function(data) {
$('#leftNews').load('load_data.php');
}
});
}
});
});
PHP CODE
<?php
if(isset($_POST['limit'])) {
echo $_POST['limit'];
}
else echo 'asd';
?>
Everytim i run this i get "asd" printed
That's because you're loading the PHP page, instead of loading the result.
$(document).ready(function() {
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
var dataString = "2";
$.ajax({
type: "POST",
url: "load_data.php",
data: {'limit': dataString},
success: function(data) {
$('#leftNews').html(data);
}
});
}
});
});
You make two different ajax requests. The first one is a POST-request with limit-variable set. The more important one is the second one, it is a load-requests (which is a get-requests without any parameters). Of course, your last request which shall print out the result does not containt any parameters, thats why "asd" is printed - the limit is NOT set!
In order to get the wanted result, you should change it to:
success:function(data) {
$('#leftNews').html(data);
}

Perform 2 background tasks simultaneous with jQuery and Ajax

updated my question below
I made a script where a user can import large amounts of data. After the form is submitted and the data validated I add 2 background tasks: 1 is a script that imports all the data. This script also lets the databases know how many in total and how many he has done. The second is a script that reads how much is done from the database and displays it in a nice progress bar.
Code:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
checkPercentage();
Both scripts, work fine. Except that the second script (getting the status of the process) isn't started after the first (importing the data) is finished. Which makes the complete thing kinda useless.
Any ideas how to solve this?
update:
I found out that the background process gets called only once. That's the problem. I'm just not sure how to fix it..
var checkPercentage = function() {
alert("Is this function getting called every second?");
$.ajax({
type: "GET",
async: true,
url: "required/get-process-status.php",
data: "importcode=123456",
success: function(data) {
alert(data);
}
});
setTimeout(checkPercentage, 1000);
}
The code above alerts "Is this function getting called every second?" every second. Like it should. However, the value 'data' is called only once. That's not what I expected.. Any ideas?
You mean like this?:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
I just moved checkPercantage function call from end of script to success function of first ajax. You can also move it to complete function if you wish to run it despite of errors.
Set your callback function to be:
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
if (process != 100) {
setInterval(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
}
Firstly, the if statement has to be in a callback function to work the way you want it. Secondly, you should use setInterval() instead of setTimeout() because it will recheck it every interval time.
Also, yabol is right saying that the top of your code should look like this:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});

Categories