I want to show notifications when new row inserted.I've achieved it through the below code,
Ajax
<script>
var old_count = 0;
var i=0;
setInterval(function(){
$.ajax({
url : "shownotify",
success : function(data){
if (data > old_count)
{
if (i == 0)
{old_count = data;}
else{
$('#notify').html("New user");
old_count = data;
}
} i=1;
}
});
},1000);
</script>
Now I want to show the count of new users which I returned from controller,
public function shownotify()
{
$action=DB::table('users')->where('admin_action_at', 'null')->count();
$data=Move::count();
return compact('action', 'data');
}
How do I get it in ajax function?Can anybody help?
You need to pass the array $data but you are passing a string.
public function shownotify()
{
$action=DB::table('users')->where('admin_action_at', 'null')->count();
$data=Move::count();
$return_array = compact('action', 'data');
return json_encode($return_array);
}
And make a little change in your ajax success callback function like:
success : function(data){
if (data.data > old_count)
{
if (i == 0)
{old_count = data.data;}
else{
$('#notify').html(data.data + "New user");
old_count = data.data;
}
} i=1;
Related
So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;
Please help,
I have a dynamically generated set of button-incremented inputs. First i store id's and values into localstorage, and everything goes fine and i can see all the id-value pairs, but i cannot send the data using AJAX call.
Here's what it looks like:
The AJAX is assigned on button click:
<script>
$("#send_order").click(function (e) {
if (localStorage) {
if (localStorage.length) {
for (var i = 0; i < localStorage.length; i++) {
var pid = localStorage.key(i);
var value = localStorage.getItem(localStorage.key(i));
$.ajax({
url: "update.php?pid="+pid+"&qty="+value,
success: function(){
alert( "Прибыли данные: ");
}
});
}
} else {
output += 'Нет сохраненных данных.';
}
} else {
output += 'Ваш браузер не поддерживает локальное хранилище.';
}
)};
</script>
But nothing happens when the button is clicked.
What i do wrong?
While your code looks fine it is little inefficient to send your localstorage data one by one in a loop. It makes more sense to convert your localstorage to a json string and send everything at the same time. You can json_decode the json string in your php update script. Also I included a function to test if localStorage is available by trying to write in it. This is more reliable then if(localStorage)
$("#send_order").on("click", function () {
var output='';
if(localStorageTest() === true){
console.log('localStorage is available');
if(localStorage.length){
var data=JSON.stringify(localStorage);
$.ajax({
type: "GET",
url: "update.php?data="+data,
success: function(){
alert( "your data is send correctly!");
}
});
}else{
output += 'localStorage is empty\n';
}
}else{
output += 'localStorage is not available\n';
}
})
function localStorageTest(){
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
I have a PHP process which updates files, and writes a status report with each file.
While that is happening, I was hoping to update the user's browser until the final response.
Unless there is a better way, I simply wanted some advice on how to loop infinitely refreshing getJSON() results until the ajax response comes.
What is the best way to do this?
This ended up being the solution I used:
$(document).on('click', "#ss_batch_edit_processing", function (e) {
var ids = get_selected();
var status_location = '<?php echo symbiostock_TMPDIR . '/report.txt' ?>';
if(ids == 0){
return;
}
$('.' + loading_icon_small).show();
var data = {
action: 'ss_professional_ajax',
security: '<?php echo $ajax_nonce; ?>',
reprocessing_action: $('input:radio[name=ss_reprocessing_action]:checked').val(),
ids: ids,
};
var completed = 0;
$.post(ajaxurl, data, function (response) {
$('.' + loading_icon_small).hide();
completed = 1;
});
var get_update = function(){
$.getJSON(status_location, function (data) {
var update = '<ul><li><strong>'+data['title']+'</strong></li><li><strong>Count:</strong> '+data['count']+' / '+data['total']+'</li><li><strong>Last processed</strong>: Image # '+data['last_id']+'</li></ul>';
$('#ss-reprocessing-results').html(update).delay(1000);
});
if(completed == 1){
clearInterval(timed_requests)
return false;
}
};
var interval = 1000; // every 1 second
var timed_requests = setInterval(get_update, interval);
});
Hope your are fine!
I'm would like to execute a request (SQL) like this one:
SELECT Name FROM course WHERE IdSectionFK = '.$idSectionFK.';
I have the list of sections:
while($row = $selectAllSection->fetch(PDO::FETCH_OBJ)){
echo "<option value=".$row->IdSection.">".$row->Name."</option>";
}
And I would like to display the data only for the selected value. I tried something like this to get the value of the list:
<script>
function displayVals() {
var idSection = $("#sectionListe").val();
$.post('index.php', { 'idSection': idSection },function (){
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
}
$("select").change(displayVals);
displayVals();
</script>
So, the variable "idSection" is equale to the PHP variable "idSectionFK" in my SQL request.
But how can I execute the right SQL request ?
Thank you so much for your help!
Lapinou.
AJAX is the solution.
JS code:
function displayVals() {
var idSection= $("#sectionListe").val();
$("p").html(idSection);
$.post('/url/to/php/file', { 'idSection': idSection }, function (response) {
// do something with the response here
// e.g: $('select').append(response);
console.log(response);
});
}
$("select").change(displayVals);
displayVals();
PHP code to process the received data:
$idSectionFK = 0;
if (isset($_POST['idSection'])) {
// get the ID from ajax, run SQL here
$idSectionFK = intval($_POST['idSection']);
$query = "SELECT Name FROM course WHERE IdSectionFK = '.$idSectionFK.';";
// .... your code ...
}
Just to give you the basic idea.
In Js file I've created a function which has to send an id and return boolean value to php file which returns false or true; but how can I do it?
JS function
function findDB(id)
{
}
PHP side
include_once("kutuphane/inc.php");
$id = $_POST['tipi'];
$sql= "select count(id) from bolge_db where parent_id=$id";
$faz2= $_SESSION["VT"]->doQuery($sql);
$flag=false;
if($faz2>0)
{
$flag= true;
}
else
{
$flag= false;
}
It's simple AJAX! Try out this code in js:
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
keep in mind that you have to echo something in php! eg: echo 1; echo 0;
Or using jQuery
var data = {
var1 : "string or another var"
};
$.post('url.php',data , function(data) {
var response = data;
//Do What Ever You Want
});