increase number with ajax php and mysql - php

I need it to fit and I click on a file to increase the number to 1 and saved in the database
I already have the database created and part of the AJAX code ready, in addition to the number YA INCREMENTA, the issue is that I have an update of the page manually instead of only updating the div
Number to update
<span id="'.$rowRE[id_reclamo].'" class="badge badge-primary badge-pill like">'.$rowRE[positivo].'</span>
Function with ajax
$(document).ready(function () {
$('.like').on('click', function () {
var reclamoID = $(this).attr('id');
if (reclamoID) {
$.ajax({
type: 'POST'
, url: 'like.php'
, data: 'reclamo_id=' + reclamoID
, success: function () {}
});
}
else {
alert("error");
}
});
});
php code
$reclamoID=$_POST['reclamo_id'];
$query = $db->query("UPDATE reclamos SET positivo = positivo +1 WHERE id_reclamo = $reclamoID");
//Count total number of rows
$rowCountTabla = $query->num_rows;
I need you NOT to recharge the entire page if not ONLY THE NUMBER

Return the count in the same request you make when you post your data. Something along the lines of:
PHP:
$reclamoID = pg_escape_string($_POST['reclamo_id']);
$results = $db->query("SELECT positivo FROM reclamos WHERE id_reclamo = '".$reclamoID."'");
// Whatever DB wrapper you're using here... this is just a guess.
$count = $results[0]['positivo'];
echo json_encode(array(
'id' => $reclamoID,
'count' => $count
));
Javascript:
$('.like').on('click', function () {
var element = $(this);
var reclamoID = element.attr('id');
if (reclamoID) {
$.post(
'like.php',
{
reclamo_id: reclamoID
},
function (responseData) {
element.text(responseData.count);
},
'json'
);
}
});
ALWAYS sanitize posted data, to prevent injections and other malicious code.

Related

My ajax taking too much time in for loop calling a php file

My Ajax is taking too much time on loading am calling ajax from 1 to 3000
It hit on database and get if value exist in database from 1 to 3000 then it will return
Here's my code
function Getdata(e) {
e = e;
jQuery.ajax({
type: "GET",
async: true,
url: "getdata.php",
data: "id=" + e,
success: function(t) {
jQuery(".reult_get_wish-" + e).html(t.htmltext)
},
dataType: "json"
})
}
for (var e = 1; e <= 3000; e++) {
Getdata(e);
}
Here's my getdata.php file code
$id = $_GET['id'];
$sql = "SELECT * from wishing_report where user = '".$id."'";
$result = $mysqli->query($sql);
if ($e = $result->fetch_array(MYSQLI_ASSOC))
{
echo json_encode($e);
}
Explained
If it takes some time, why not use an asynchronous approach, where you can process 'x' amount at a time, i.e. you could use setTimeout and recursion or setInterval, just so you can process a block of information/data at a time.
In this example you can see that there's an onIterate function and a onComplete function, both of these are used in different scenarios, you can use the onIterate function for each iteration, prior to the iterate function being complete. Once you've iterated enough, this is when you can fire the onComplete function, feel free to make any changes you like, i.e. include promises or whatever takes your fancy.
This could also be a better approach for the server as you're allowing the server time to recover from the last request. Alternatively you could alter your back end code so that it's more efficient, etc, you could use some limit and offset parameter(s) within your query to ensure the server isn't handling too much data at one time.
// A function to fire when the ajax request has finished.
const onSuccess = data => {
console.log(data);
};
// Simulate the ajax request.
const getData = (i, callback) => {
setTimeout(() => {
console.log(i);
return callback(i);
}, 500);
}
// A function to fire once complete.
const onComplete = () => console.log('Finished');
// A function to fire if it's not finished/complete.
const onIterate = () => console.log('NOT finished yet');
// A function to iterate, break the loop up into chuncks.
const iterate = (start, end, delay) => {
const process = data => {
iterate(++start, end, delay)
if (start > end) {
onComplete(data);
} else {
onIterate(data);
}
};
if (start <= end) {
setTimeout(() => {
getData(start, process);
}, delay);
}
};
// A starting point.
const start = () => iterate(0, 10, 1500);
// Just start the function.
start();
Your Ajax is taking a lot of time beacause you're running it 3000 times. To avoid calling it many times, I recommend putting all ids in array. I would do something like this.
JavaScript:
function Getdata(e) {
e = e;
jQuery.ajax({
type: "POST",
async: true,
url: "getdata.php",
data: {id: e},
success: function(t) {
$.each(t, function() {
$.each(this, function(k, v) {
jQuery(".reult_get_wish-" + v).html(v.htmltext);
});
});
},
dataType: "json"
})
}
var arr = [];
for (var e = 1; e <= 3000; e++) {
arr.push(e);
}
Getdata(arr);
PHP:
$id = $_POST['id'];
$sql = "SELECT * from wishing_report where user IN ('".implode(',', $id)."')";
$result = $mysqli->query($sql);
if ($e = $result->fetch_array(MYSQLI_ASSOC))
{
echo json_encode($e);
}

Queing notification in PHP using AJAX with beep sound

I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...

ajax and php to load more content from mysql when page gets to bottom

I've seen some answers to this question on this site already, but i still haven't been able to implement it as i want to for 2 days now. I'm sort of a beginner so a very clear explanation would be of great help,
i have a mysql database of some data, i want to read from a table and display 30 rows at a time, when the user scrolls to the end of the page, i want to load another 30 rows (i have been able to do the first 30, but loading the remaining is a challenge for me).
i already have this:
$(document).ready(function(){
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() -$(window).height()) {
//ive tried all sorts of things here it just doesnt work
}
});
also an example of the php file that loads the next contents would help,
i'm using php and mysqli
thanks a lot in advance.
so this is my loadmore.php, its for the functionality, haven't styled the output:
<?php
require_once 'functions.php'; //my databse connection is in this file
//i created a function queryMysql($query) in functions.php, thats what is used here
$result = queryMysql("SELECT * FROM articles WHERE live='1' ORDER BY created DESC LIMIT $start, 30");
$num = $result->num_rows;
for ($j = 0 ; $j < $num ; ++$j){
$row = $result->fetch_array(MYSQLI_ASSOC);
$title = $row['title'];
$subtitle = $row['subtitle'];
echo "$title<br />$subtitle";
}?>
for the ajax, i changed it to the first answer i got here, but all my attempts have looked like this:
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
type: method,
data: {}, //Your data
url: 'loadmore.php',
async: true,
success: function (data, textStatus, jqXHR) {
$('#article-inro-hold').append(data);
},
error: function (jqXHR) {
//Error handler
}
});
}
});
Try to implement jquery ajax, something rough like this:
$(document).ready(function () {
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
type: method,
data: {}, //Your data
url: 'your/url/to/get/more/content/from',
async: true,
success: function (data, textStatus, jqXHR) {
$('#myDiv').append(data);
},
error: function (jqXHR) {
//Error handler
}
});
}
});
});
You have to make an ajax call for each time, when you scroll amount get up, nearer to document height. Along with you also have to manage your offset, otherwise you will get duplicate records (You can use hidden field for that), and pass it each time in your ajax call.
<div id="ajax-response"></div>
<input type="hidden" value="0" id="offset" />
<script>
$(document).ready(function(){
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
url: 'requesthandler.php',
type: 'post',
data: {
task: 'show-more',
offset: document.getElementById('offset').value
},
success: function(response){
jsonObj = $.parseJSON(response);
$('#ajax-response').append(jsonObj.html);
document.getElementById('offset').value = jsonObj.offset;
}
})
}
});
});
and requesthandler.php will look like:
if($_POST['task'] == 'show-more'){
$offset = (int) $offset;
$sql = "SELECT * FROM table limit $offset, 10";
$data = '';
foreach ($conn->query($sql) as $row) {
$data .= "<div>$row['column']</div>";
}
echo json_encode(array(
'offset' => ($offset + 10),
'html' => $data,
))
}
$query = $db->query("SELECT * FROM bags ORDER BY id DESC LIMIT 7");
Can we use $_POST here to get only needed information.
$limit=($_POST["bag"]);
$query = $db->query("SELECT * FROM bags WHERE id = '.$limit.' ORDER BY id DESC LIMIT 7");

Rating not add with ajax in wordpress

I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)

Jquery and ajax, my function for username checking?

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

Categories