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;
}
}
...
Related
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.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
//var form4 = new FormData($("#imagesform").get(0));
//alert(form4);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url :"{{url('/dbvalue')}}",
type: 'POST',
data: {form1: form1, form2: form2,form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
This is my ajax code.Here I'm passing the values of four forms
Controller:
public function finalSubmit(Request $request)
{
var_dump($_POST);
$var1 = $this->addPriceDetails1($request->form1);
$var2 = $this->addProductDetails1($request->form2);
$var3 = $this->addAdditionalInformation1($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have
$imagesform
return response()->json(["response"=>"success"]);
}
Eg. for function:
public function addPriceDetails1($request)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$request->input('skuid');
echo($priceInfo->id);
//return $request->all();
}
Also here when I'm trying to echo the values of $priceInfo->Id it echoes '0'.I don't know why
With this I'm getting FatalErrorException..call to member function input() on string
var_dump($_POST) gives me an array of forms values.
UPdate:
public function getpriceDetailsId()
{
$id = mt_rand(1000000, 9999999);
$id="PD".$id;
$count=priceInfo::select('id')->where('id',$id)->count();
if($count==0)
{
return $id;
}
else
{
$this->getpriceDetailsId();
}
}
here is my function for getpriceDetailsId().
You get that error because your input query when you access as object when it is string, you can convert your query string to an array to access like so.
public function addPriceDetails1($request)
{
parse_str($request, $input);
$priceInfo = new priceInfo ;
$priceInfo->id = $this->getpriceDetailsId();
$priceInfo->SKUID = $input['skuid'];
echo($priceInfo->id);
}
Hope this help
I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});