Refresh JSON from external PHP - php

I want to refresh my data, obtained from an external PHP page, every second. The PHP sends JSON data, retrieved with an AJAX call. With this code, I see the table correctly, but I need to refresh my browser to see the new data.
$(document).ready(function() {
$("#list").jqGrid({
url: 'get_data.php',
datatype: 'json',
mtype: 'GET',
jsonReader: {
repeatitems : false,
},
colNames: [.............],
colModel: [.............],
autowidth: true,
height: 'auto',
loadonce: true,
key: true,
altRows: true,
altclass: 'odd',
rowNum: 100,
viewrecords: true,
gridview: true,
gridComplete: function(){
if(this.x == undefined){
var j = 0;
this.x = 1;
while(j < mydata2.length){
jQuery("#list").addRowData(mydata2[j].id, mydata2[j]);
j++;
}
}
return true;
}
})
});
To update the data I've already tried this:
var $grid = $("#list"), timer;
timer = setInterval(function () {
$grid.trigger('reloadGrid', [{current: true, datatype: 'json', url: 'get_data.php'}]);
}, 1000);
And this:
var refreshId = setInterval(function() {
// ... jqGrid function ...
}, 1000);
but neither worked.

The main error is the usage datatype: 'json', url: 'get_data.php' as an option of reloadGrid. The method reloadGrid understand only two options: current and page (see the answer). What you need is to reset datatype option of jqGrid because of usage loadonce: true. So you need replace the line
$grid.trigger('reloadGrid',
[{current: true, datatype: 'json', url: 'get_data.php'}]);
called inside of setInterval to the following
$grid.jqGrid("setGridParam", {datatype: "json"})
.trigger("reloadGrid", [{current: true}]);
It should solve you main problem with refreshing of data. Additionally I would recommend you to examine the code of gridComplete which seems me suspected. I don't full understand it. You should take in consideration that addRowData calls internal updatepager method which calls gridComplete and can follows to recursion (see the line of code and the answer).

Related

Encapsulated the Ajax calls into a class and works odd when I'm using it to upload files

I've recently used lots of Ajax methods in one of my projects, since in every $.ajax call you have to write many of the same codes, like:
{
type:'POST', // Default value is 'GET'
beforeSend: function(xhr){
// Usually do some Page Loading Animation stuff here
},
error:function(){
// Handling the Exceptions here
}
}
So I've encapsulated the Ajax call into a class, called JAjax, like this :
(function ($) {
// More details, see: http://api.jquery.com/jquery.ajax/
var defaults = {
data: {},
url: '',
type: 'POST',
dataType: 'JSON',
isOverlay: true,
async: true,
cache: true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
overlayTarget: $(document.body),
dealyClean: 500,
f_before: function () {},
f_done: function () { },
f_always: function () { },
f_fail: function (xhr) {
if (xhr.status !== 200) {
// Handling the Exceptions
}
}
};
function JAjax(_options) {
this.options = $.extend({}, defaults, _options);
this.execute();
}
function createOverLayer(options) {
// Create a page loading animation layer
}
JAjax.prototype = {
execute: function () {
var parent = this;
var response = $.ajax({
data: parent.options.data,
url: parent.options.url,
type: parent.options.type,
dataType: parent.options.dataType,
contentType: parent.options.contentType,
async: parent.options.async,
cache: parent.options.cache,
processData: parent.options.processData,
beforeSend: function (xhr) {
parent.options.f_before();
if (parent.options.isOverlay) {
createOverLayer(parent.options);
}
}
});
response.done(parent.options.f_done);
response.always(parent.options.f_always);
response.fail(parent.options.f_fail);
}
};
jQuery.extend({
jajax: function (_options) {
_options = _options || {};
if (typeof _options === 'object') {
return new JAjax(_options);
}
}
});
})(jQuery);
For most Ajax requests (GET, POST), it works fine. But when I use it to upload some files, The file will successfully upload to the server and back to me a filename(string) as an execution result. But somehow, it doesn't trigger the f_done function, below is how I use it to upload the files:
var url = '/ajax_common_file_upload';
var file_data = new FormData();
for (var i = 0; i < _files.length; i++) {
var file = _files[i];
file_data.append('input_files[]', file);
}
$.jajax({
url: url,
data: file_data,
cache: false,
contentType: false,
processData: false,
f_done: function (result) {
// Never to be executed :-(
alert('show me something, please!');
}
});
I spend days to try to figure it out why it doesn't 'SHOW ME SOMETHING' but all failed, will be very appreciated that someone can help me out and explain why the f_done() method cannot be triggered when I use it to upload files.
Update:
I made some screenshots for both JAjax and original $.ajax on Request Headers and merge them together like below:
I used the same parameters to make the request for both JAjax and $.ajax, but I don't know why they have a different Accept value!
ANYONE?
Still can not trigger the f_done() function!!! but since I can do the same thing at f_always(), I'm gonna skip this and moving on. I will keep this post open and always appreciate for any suggestions!

jQuery Select2 JSON data

My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).
Output of test.php
[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]
jQuery script:
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
alert(data);
},
processResults: function(data) {
return {
results: $.map(data.suggestions, function(obj) {
return {
id: obj.key, text: obj.value
}
})
};
}
}
});
I have been searching and checking all other solutions. It it not working for me. I'm stuck.
Update: jQuery script so far
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
placeholder: "Voer uw postcode in..",
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
return {
ajax_call: 'addressZipcodeCheck_BE',
zipcode: '1200'
};
},
processResults: function(data) {
alert(data);
correctedData = JSON.parse(data)[0]suggestions;
alert(correctedData);
return {
results: $.map(correctedData, function(obj) {
return {
id: obj.key,
text: obj.value
}
})
};
}
}
});
Here is a working fiddle for your example.
I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.
Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.
Run this code in your JQuery enabled browser console and you will undestand.
var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;
Also check this answer to see how a proper response should look like.
Updated answer:
Sending additional data to back-end:
$('#billing_postcode_gemeente').DataTable(
{
......
"processing" : true,
"serverSide" : true,
"ajax" : {
url : url,
dataType : 'json',
cache : false,
type : 'GET',
data : function(d) {
// Retrieve dynamic parameters
var dt_params = $('#billing_postcode_gemeente').data(
'dt_params');
// Add dynamic parameters to the data object sent to the server
if (dt_params) {
$.extend(d, dt_params);
}
}
},
});
Here dt_params is your additional parameter (the zipcode
that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.
There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code) pair to the dt_params key in your request JSON:
function filterDatatableByZipCode() {
$('#billing_postcode_gemeente').data('dt_params', {
ajax_call: 'addressZipcodeCheck_BE',
zip_code : $('#some_imput_box').val()
});
$('#billing_postcode_gemeente').DataTable().destroy();
initDatatable();
}
Try this way
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return data.items;
},
cache: true
},
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

Global Variables with jQuery

Just got the FooTable responsive table plugin to work. Now I am trying to setup a PHP script to pull PostgreSQL and return a JSON encoded array.
Everything is working fine so far. I am really close to making this jQuery script work, but I'm not sure why my variables are not passing along.
Here is the script:
var columns_json;
var rows_json;
jQuery(function($){
$.ajax(
{
type: "POST",
dataType:"JSON",
url: "a.php",
data: {action: 'test'},
success: function(data)
{
columns_json = data[0];
rows_json = data[1];
console.log(columns_json);
console.log(rows_json);
},
failure: function(data)
{
alert("Something went wrong");
}
});
$('.table').footable(
{
"paging": {"enabled": true},
"filtering": {"enabled": true},
"sorting": {"enabled": true},
"columns": columns_json,
"rows": rows_json
});
});
If I look at my console, I can even see the two data arrays returned correctly... I even tried to output the data to make sure it was correct (no issue there):
console.log(JSON.stringify(columns_json))
So what I am not understanding about jQuery is:
When I update the variables I declared at the top of the scripts from within the $.ajax function, why are the JSON arrays not available at the $('.table').footable( function?
Admitting I've been only playing with jQuery for a little over a month so this is all new to me.
I did find one workaround to get this to work and that was the suggestion on this Post. I modified my script and got it to work. However the console throws a warning:
"Synchronous XMLHttpRequest on the main thread is deprecated because
of its detrimental effects to the end user's experience.".
Like always, any thoughts and suggestions are much appreciated.
Move the logic that fills your table inside the success callback.
Alternatively you can also encapsulate your logic in a function and call that function from the success callback.
The reason your code is not working, is because $.ajax is async, meaning it will not wait for the server request to finish, instead the next code will be executed immediately.
In the answer you linked you find async: false - wich is a (bad) alternative, because it will make your ajax call wait for the server response - but it will also look to the user as if the browser is frozen.
Suggestion: also show a loading animation/overlay, while you're doing ajax calls that may take a few seconds to finish.
After you've modified your code, check if your variables still need to be global.
var columns_json;
var rows_json;
jQuery(function($) {
$.ajax({
type: "POST",
dataType: "JSON",
url: "a.php",
data: {
action: 'test'
},
success: function(data) {
columns_json = data[0];
rows_json = data[1];
$('.table').footable({
"paging": {
"enabled": true
},
"filtering": {
"enabled": true
},
"sorting": {
"enabled": true
},
"columns": columns_json,
"rows": rows_json
});
},
failure: function(data) {
alert("Something went wrong");
}
});
});

how to display data in jqgrid using a post ajax request?

I cant seem to find a way to display the data using post ajax
When i predefined the json data inside a variable it does read. But when i retrieve the data from the server using post ajax and display it in jqgrid it doesnt seem to work.
Heres my code:
var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
$.post(pathFile+"loadPaymentDetails",{id:id,action:'loadPaymentDetails'},function(response,status){
var result = [{"0":"3","id":"3","1":"82","payment_id":"82","2":"0000-00-00 00:00:00","payment_issue_date":"0000-00-00 00:00:00","3":"100","payment_ref_number":"100","4":"0","payment_mode_id":"0","5":"121212","payment_amount":"121212","6":"","payment_description":""}];
if (status == "success") {
var grid_data = response
$(grid_selector).jqGrid({
data: grid_data,
datatype: "local",
height: 250,
colNames:[' ', 'payment_issue_date','payment_ref_number'],
colModel:[
{name:'myac',index:'', width:80, fixed:true, sortable:false, resize:false
},
{name:'payment_issue_date',index:'payment_issue_date', width:60, sorttype:"int", editable: true},
{name:'payment_ref_number',index:'payment_ref_number',width:90, editable:true, sorttype:"date"},
],
viewrecords : true,
rowNum:10,
rowList:[10,20,30],
pager : pager_selector,
altRows: true,
//toppager: true,
multiselect: true,
//multikey: "ctrlKey",
multiboxonly: true,
//editurl: $path_base+"/dummy.html",//nothing is saved
caption: "jqGrid with inline editing",
autowidth: true
});
}
})
I can display the data in jqgrid using the result variable but when i use the response from the ajax call it doesnt seem to work although there output is the same.
I use:
$("#tab_vsebine").jqGrid({
mtype: 'POST',
url:<your ajax url call>,
postData: {param1:value, param2:value,...},
datatype: "json",
colNames:[...],
colModel:[...],
.
.
.
});

Trying to send an array from jquery to PHP function

I'm trying to load an array in my javascript. I need to send this array in some format to a PHP script that I'm going to call. In the example below, gSelectedMeds is my array. The value count will tell the PHP script how many meds items to expect to receive. I'm having trouble getting the data from the array into a format that I can send via the data option of $.ajax. Any help would be greatly appreciated!!
The part of the code below that is giving me grief at the moment is the data option:
$('#export').click(function() {
$.ajax({
url:'ajax-exportMeds.php',
data:
{"number":gSelectedMeds.length},
$.each(gSelectedMeds,
function(intIndex, objValue){
{"med"+intIndex:objValue},
}
),
type: "GET",
//dataType: "text",
success: function(data){
$('p#allMeds').text('');
$('a.bank').text('');
//clear array, bank and storedList divs
$(this).text('');
gSelectedMeds[] = '';
//$('ul#storedList').fadeOut('fast');
$('ul#storedList').text('');
return false;
},
}),
});
You should send the data as json. Then you can read it using json_decode() in php >= 5.2.0
I ended up stringing out the array and sending a count at the end of the url that I called:
$('#export').click(function() {
$.each(gSelectedMeds,
function(intIndex, objValue) {
i=intIndex + 1;
if(i>1) {string+='&';}
string+='med'+i+'="'+objValue+'"';
}
)
string += "&count="+i;
$.ajax({
url: 'ajax-exportMeds.php?'+string,
type: "GET",
dataType: "text",
success: function(data){
$('#dialog_layer').dialog({
autoOpen: true,
bgiframe: true,
modal: true,
closeOnEscape: true,
buttons: {
"OK": function() { $(this).dialog("close"); }
}
})
}
})
});

Categories