jquery click happens too fast to refresh results from database? - php

I'm making a simple shoutbox and when someone posts a message the message is added to the database just fine. I made a refresh button which populates all the messages in the text area.
I am trying to call the .click() on the refresh button after the person enters the message but I think it happens too fast and doesn't catch the new message in the database. I works if I add an alert to give it more time. Is there a better way?
$("#shoutBtn").click(function(event){
event.preventDefault();
$.post("includes/shoutBoxPost.php", {"message": $("#messageBox").val(),
"name": $("#userNameWelcome").html()});
$("#messageBox").val("");
$("#shoutRefresh").click();
});
I changed my code to the long hand ajax way and it works thanks for answers folks
$.ajax({
type: 'POST',
data: {"message": $("#messageBox").val(),
"name": $("#userNameWelcome").html()},
url : 'includes/shoutBoxPost.php',
success : function(data) {
$("#messageBox").val("");
$("#shoutRefresh").click();
}
});

See the documentation for jQuery .post. You can define a success callback that will only fire once the post request successfully returns.
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
$.post("includes/shoutBoxPost.php",
{"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()},
function( data, textStatus, jqXHR ) {
$("#shoutRefresh").click();
}
);

you can add call back function to your post
$.post( "includes/shoutBoxPost.php",{"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()})
.done(function( data ) {
$("#messageBox").val("");
$("#shoutRefresh").click();
});

You need to wait for your post to finish and send a success message back (via JSON), then do the refresh action.

Related

Jquery autocomplete with post data

I have a script with autocomplete, get some data from an external source according to searched term.
I can output the json in the console but I'm struggling to pass it to the response, how do I do that?
$('#test').autocomplete({
source: function(request,response){
$.post('/schoollookup', {
query: request.term
}, function(data){
}, 'json'
);
},
minLength: 2
});
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
This is the syntax for post request. where
url : A string containing the URL to which the request is sent.
data : A plain object or string that is sent to the server with the request.
success : callback function
#Sumesh
$.post('/schoollookup', {
should be working the same, the difficulty that I have is to get response
Thank you for your answer r007ed, the issue was that it was not returning an array.
So the final code for this is :
$('#test').autocomplete({
source: function(request,response){
$.post('/schoollookup',{query: request.term}, response, 'json');
},
minLength: 2
});

Datatables - sorting by and pagination

I'm fresh, but I'm learning with the help of people like you :). I need to do a table on my site that will display sorted data by type and pagination. I thought to use this solution: https://legacy.datatables.net/examples/data_sources/server_side.html
But honestly, I do not know how to do this. Can someone give an example along with html how to do it? Or suggest a different solution?
First of you need to import some of the necessary files:
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
CSS :
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">
Then using the id attribute of the table you have created use the following code :
var table = $('#myTable').DataTable(); // this creates a table object of the DataTable class
// myTable is the id of the table you have created
table.clear().draw();
table.destroy();
$.ajax({
url: 'abc.php',
type: 'POST',
data: {value:value},//value you want to send to backend
dataType: 'json',
success:function(result){
$('#myTable').DataTable( {
"pageLength": 10, // does pagination providing 10 records per page
"destroy": true,
"language": {
"zeroRecords": "No Data Found",
"infoEmpty": "No Data Found",
},
"ajax": "objects.txt",
// Data from backend is sent to objects.txt file in JSON format
"columns": [
{ "data": "Key value from backend for 1st column in table" },
{ "data": "Key value from backend for 2nd column in table" },
{ "data": "Key value from backend for 3rd column in table" },
{ "data": "Key value from backend for 4th column in table"},
{ "data": "Key value from backend for 5th column in table" },
{ "data": "Key value from backend for 6th column in table" }
]
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
You could import more datatable javascripts that can provide more functionality such as conversion of table data to pdf or export as an excel file using button datatable javascripts. You can find more related information here : https://cdn.datatables.net/

Refesh ajax code in a given number of seconds

I have a code below and I have tried it already and its working.
What I am trying to achieve is to load data using ajax to my data tables.
The code below is working but now I would to refresh every 5 to 10 second checking if there is new data in the database.
$(document).ready(function () {
$("#get_categories").DataTable({
"ajax": { //create an ajax request to display.php
"url": "process/get_categories.php",
"dataSrc": ""
},
"columns": [
{"data": "id"},
{"data": "name"},
{"data": "action"}
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
});
As you've already defined an AJAX source for your DataTable you can simply call reload() in an interval:
var table = $("#get_categories").DataTable({
// settings...
});
setInterval(function () {
table.ajax.reload();
}, 10000);
However, as #ADyson mentions in the comments, refreshing a data source this often can lead to server load problems, depending on how may concurrent users you have accessing the data. I'd suggest looking in to using WebSockets or Server Sent Events as a more scalable alternative.

Sending POST data through datatables ajax request

I'm trying to make a simple ajax call in datatables that is reliant on a post array of IDs from a previous page's form. I am getting the error :
Invalid JSON Response
which tells me that my returned json array is probably empty or something and I have a feeling it has to do with the POST data not being sent to my php/sql external script on which ajax is requesting the data from.
I'm not sure how to test it as I don't know how to include the $_POST data in the URL to my external php page to outright trigger the script.
Heres my current datatables init and php from the results page:
<?php
include_once('../functions.php');
sec_session_start();
print_r($_POST['post_id']); <-- making sure the post data made it this far
?>
<script type="text/javascript">
$(document).ready(function() {
var compTable = $('#compTab').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "baddebt_ext_sql.php",
"type": "POST",
"dataType": 'json',
"data": {"post_id": $_POST['post_id']}
},
"Columns": [
{ "data": "provider_num" },
{ "data": "provider_name"},
{ "data": "261_total_bed_debts", "sClass": "rightAlign" },
{ "data": "271_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "281_non_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "1_cost_to_charge_ratio", "sClass": "rightAlign" },
{ "data": "291_cost_of_non_mcr_bad_debts", "sClass": "rightAlign" }
],
"scrollY": "600px",
"scrollCollapse": true,
"paging": false,
"order": [[ 2, "desc" ]],
"oLanguage": { "sSearch": "Filter All Fields By:" },
"Dom": '<"clear">lfrtipT',
"TableTools": {
"sSwfPath" : "../php/tabletools/swf/copy_csv_xls_pdf.swf" }
});
and here is my SQL:
<?php
include_once('../link_costreport_2013.php');
if(isset($_POST['post_id'])){
$in = $_POST['post_id']; <-- THIS IS WHERE THE POST DATA IS SUPPOSED TO BE RECEIVED
}
$data = array();
foreach ($in as $id){
$query = $link->prepare("SELECT id,provider_num, provider_name, 261_total_bed_debts, 271_medicare_bad_debts, 281_non_medicare_bad_debts, 1_cost_to_charge_ratio, 291_cost_of_non_mcr_bad_debts
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
$results['261_total_bed_debts'] = "\$".number_format($results['261_total_bed_debts']);
$results['271_medicare_bad_debts'] = "\$".number_format($results['271_medicare_bad_debts']);
$results['281_non_medicare_bad_debts'] = "\$".number_format($results['281_non_medicare_bad_debts']);
$results['291_cost_of_non_mcr_bad_debts'] = "\$".number_format($results['291_cost_of_non_mcr_bad_debts']);
$results['provider_name'] = "<a id='".$results['id']."' data-toggle='modal' href='#provmodal' class='push'>".$results['provider_name']."</a>";
$data[] = $results;
}
echo json_encode($data);
If anyone knows how I can get my json array from this script without utilizing the previous pages $_POST data it is supposed to send, then I will gladly post it as well.
Basically I'm just wondering if there are any steps I am missing when it comes to feeding this array of IDs through my datatables ajax query and into the second page's sql. ( an example of the post_id array is like this:
Array ( [0] => 299 [1] => 1555 [2] => 3539 ))
Diagnosing this problem is pretty easy. Simply right mouse click and "inspect element" then choose the Network tab. Toggle the transaction as you would in your interface. You'll see a new network transaction in the network tab.
Click on that new network transaction -- it should have the address that you're defining in the ajax call. The headers will show the variables you sent via post, response will show what the server returned.
The error is indicating that your response will fail if you paste the payload into jslint.com and evaluate it. What the cause of that failure is will require more details than you've provided.
In the ajax example you use, "data" is the data that's being sent to the server. To send a large amount of data in that post, I'd enclose your inputs in a form tag, then do a $.serialize or $.serializeArray on that form. You can then send that serialized data over as a variable via the data attribute, where it will be posted to your server. From there, just deal with the resulting post variables via PHP.
Please do update your code to use 1.10 API variables. Support for the old ones will be deprecated in the future versions.

Assign data to a variable in jquery

I have this code,
$(function() {
//var asd = '<?php $regions_list_full; ?>';
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
//icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
//icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
//icon: "sizzlejs_32x32.png"
}
];
$( "#find" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#find" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#find" ).val( ui.item.label );
//$( ".module h1" ).val( ui.item.value );
$(":header.title").html(ui.item.value);
//$( "#project-description" ).html( ui.item.desc );
//$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
actually this is from the autocomplete of jQueryUI, and I have an array of values which are fetched from the database. What I want is to replace my values into the var projects =[{value:asd}] such that my suggestions of the autocomplete will be the data from the database. How would I do this?
You don't want to use source: projects you probably want to define a function for the source using an AJAX call like this
$( "#search_address" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: '/path/to/script',
dataType: 'json',
data: 'whatever you need here', // i.e. term value
dataFilter: function (data, type) {
// do whatever you need to here to change data into proper autocomplete array format
// if JSON data is already in correct format you can just do this.
response($parseJSON.(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// handle error here
},
success: function(data) {
// maybe check for case of empty data object here (i.e. successful URL request, but no data returned)
return data;
}
});
}
});
Now you typically want to limit the number of results returned by your API (maybe 10 or 20 records at most), as it is likely a bad UI experience to have 1000 items show up in autocomplete. On a good autocomplete the number of results should decrease dramatically after a few letters have been types in. This also make you script perform much better in that you are only processing a handful of returned records. For the same reason, you may also want to use the minLength property of autocomplete to not even bother starting the request until X number of characters are entered.
Change
source: projects,
to
source: url_to_script
Form which script you'll send your json. See this example. If you see the source code, you'll see that in source property they use source: search.php.
Similarly, you can use your own script path and return a json data from that script, where that data will coming from server.
jQuery autocomplete will send a a querystring along to the url that you provide in the source: url , this query string will be term so remember that , because I don't think autocomplete docs tell you that , then from there you use the term querysting to query the database and send back items that start with term , You do not request every row in the database and store them in javascript variable, that would not make sense - what if there are 2,000,000 entries in the database?

Categories