How to receive POST data of ajax call in a javascript function - javascript

I need a little help. I am trying to implement bootstrap data table with ajax pagination. As this is mobile app (Cordova), I am fully dependent on javascript for server side too. Thats why in the url I am calling javascript function. Now I am not sure about how to get the POST data in it. Any help will be appreciated.
$(document).ready(function(){
$("‪#‎products‬").dataTable({
aLengthMenu: [
[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]
],
aaSorting: [],
bProcessing: true,
serverSide: true,
ajax:{
url : ProductList.getProductsPaginated(),
type: "post", // type of method , by default would be get
error: function(){ // error handling code
}
}
});
ProductList.getProductsPaginated(){
// This method gets called succesfully
// Need the post data here
}
});
Edit:
Let, without using the function as url param, let use a html page directly like
url : "page.html",
Now, how to get those post data in the html or js? Is there any other way for what I am looking?

I don't understand why you need the data inside that function, but it isn't getting called on ajax success, it's invoked because of the parenthesis, the only thing I think you could do there is to return the path of your json data, however you can call a function with your post data on ajax success like this:
ajax: {
url : ProductList.getProductsPaginated(),
type: "post",
dataSrc: function (data) {
// you can call a function here with the data as parameter
// you have to return the data, with modifications if you need
return data;
}
}

Thank you all for trying to help me. I have found no way to post data to a javascript function using ajax. In this case, I am unable to use DataTable's ajax feature to minimise data loading time by pagination. Ajax call can be made to server-side scripts only. Thats why I have disabled datatable's paging and implemented custom pagination using javascript.

Related

How to use server-side processing in JQuery DataTables without Ajax

I'm using JQuery DataTables with Vue 2. The below snippet shows how I'm using it with a JSON data source fetched from a custom method using the wretch package (it also handles authorization).
...
mounted: function () {
this.dataTable = window.$(this.$el).DataTable({
data: this.getGridData,
columns: this.getColumns,
// serverSide: true
});
},
...
This method is working fine. Now I want to enable the serverSide feature to control pagination and search without using the ajax option.
My backend application is running in .NET Framework. I have created my response data structure as shown here, but it doesn't seem to help.
Simply, I want to use my custom method to fetch data into the DataTable while using the serverSide feature.
Is this possible? I'm looking forward to your help.
DataTables has various different forms for its ajax option.
One of these is as follows:
$('#example').dataTable( {
"serverSide": true,
"ajax": function (data, callback, settings) {
// whatever logic you want to use can go here,
// as long as it evaluates to a valid JSON structure
// expected by DataTables, as a server-side response.
callback(
resultsOfYourLogic
);
}
} );
You can read its description in the linked documentation - but it basically states:
As a function, making the Ajax call is left up to yourself allowing complete control of the Ajax request. Indeed, if desired, a method other than Ajax could be used to obtain the required data...
Therefore, you can use this - with serverSide: true - to use any alternative method you wish to source your data.
Example:
"ajax": function (data, callback, settings) {
var dataSet = yourCustomFunction(data);
callback(
dataSet
);
},
Here, the custom function is invoked first, returning the JSON which needs to be displayed. The request data is passed to that custom function. Then the results of that custom function are placed in the callback.
One important note here is: The data parameter in the callback will be pre-populated with the server-side request data (automatically created by DataTables whenever the user sorts/filters/pages). So you will need to handle this request data, to know how your response data needs to be built.
(The response data structure you link to in your question, is the correct structure.)

jquery tabledit dropdown: is it possible to retrieve values from mysql database?

I'm using the jquery tabledit plug-in to update a database. Works perfectly like in the official examples.
I can succesfuly include a static dropdown with a fixed number of options (defined in custom_table_edit.js).
I'd like to be able to dynamically get those options from a database instead, but I don't know how to customize the code in custom_table_edit.js.
I can code this in php with a loop querying the database and generating a html <select> field. But I don't have knowledge of javascript or if it's even possible in this framework.
This is the custom_table_edit.js file. A dropdown is defined with three colour options. I want this dropdown to be dynamically produced.
// custom_table_edit.js
$('#example2').Tabledit({
url: 'example.php',
eventType: 'dblclick',
editButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}
});
I really haven't tried anything because i'd like to know if it's possible to do in this framework.
Welcome to SO, nucelar.
What you are describing is a HTTP request from the client to server through JavaScript. This is commonly referred as AJAX or Asynchronous JavaScript And XML. This API enables you to manually send requests to the server and there are multiple implementations.
Because you are using jQuery I will recommend you to use the $.ajax function which is included in the jQuery library.
Down here I've made a very basic example of how to send a HTTP request to a server with the GET method to retrieve some data.
$.ajax({
url: 'https://yourdomain.com', // Where to send the request to. Can also be a file.
method: 'GET', // What method of request it uses.
success: function(data) { // When a response is succesfully received.
// Do something with the received data.
console.log(data); // Show what the data looks like in the console.
},
error: function(jqXHR, textStatus, errorThrown) { // When an error occurs while making a request.
console.log(jqXHR, textStatus, errorThrown); // Show the error in the console.
}
});
In your case the url property value might be the URL of a PHP file in which you query the database and return the result, as you mentioned you are able to do.
The response of the AJAX function (which is stored in the data variable in the success method) can be text, as in a string, or even JSON if you want to send structured data.
Beware of the Asynchronous part. This means that the AJAX code does not stop the execution of the rest of your JavaScript code, but simply continues and comes back whenever the HTTP request has been completed.
I hope that this is enough to get you started. Good luck and don't hesitate to ask questions.

Limiting AJAX results, and getting different outputs

I have recently started to use AJAX with JQuery. I now know how to limit results in AJAX GET requests. However, I have no idea how to make a client-side button to load more requests. Say I have 100 people on the JSON file and i want to load 3 at the time. If the button is pressed, the next three load and the last three disappear.
I used this to limit:
$.ajax({
type: "GET",
url: "/people",
data: {limit: 3, order: 'desc'},
dataType: "json",
success: function(data) {
// Do some awesome stuff.
}
});
Other than limiting results, I really have no idea how to load more results.
What you need is to determine the manner in which you can execute your ajax request such as using a button that will load more data.
Firstly, you've mentioned you can successfully return the limited data by passing parameters to your ajax request, that's great.
You can wrap your ajax request in a function that will allow you to pass parameters such as limit and order direction. Now, I won't go all out here since there's very little information to work with. But to create a button that you can click that will load more data is something that can be demonstrated here.
Here's your AJAX request. We can wrap it in a function that accepts parameters. For example, limit defaults to 3, order defaults to "desc". The possibilities here are endless. You'll obviously want offsets and such but that you can work with as you go along. The purpose of this is only to demonstrate how you could create a button to fetch more data.
jQuery has a shorthand method called $.getJSON which will load JSON-encoded data using a GET HTTP request.
So here's the function which we can later call from the click of a button.
function fetchPeople(limit = 3, order = "desc") {
$.getJSON(
"/people",
{
limit: limit,
order: order
},
function (data) {
// Do something with your data
}
);
}
The button may be something like this.
<button type="button" id="loadMore">Load more</button>
In jQuery you can bind event listeners that will trigger, e.g. on click, and this listener will trigger your function that will go off to fetch whatever it is you've configured in the wrapper function.
$("#loadMore").on("click", function () {
fetchPeople();
});
There are a plethora of plugins for jQuery and code examples across StackOverflow and the WWW in general.
But I'm hoping this steers you in the right direction.

Jquery Ajax Datatable reload

I am using jquery datatable to list my database values.
I want create a country and its state in same page while that initially the state datatable is empty.Once I create country the country id is generated and can create state with that country id in same page.It also created fine but the problem is datatable is not reloading it should show the state which was created but its not showing.The problem is country id which is generated is not passing to the ajax parameter in datatable while reloading it.
country_id=$("#country_id").val();
dataTable = $('#example').DataTable( {
"serverSide": true,
// Load data for the table's content from an Ajax source
"ajax": {
"url": datatable_url,
"type": "POST",
data:{country_id: $("#country_id").val()},
error: function () { // error handling
$(".table-grid-error").html("");
$("#table").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#table-grid_processing").css("display", "none");
}
},
],
});
I reloading it by
$.ajax({
url: 'url',
type: "POST",
data: {
//data
},
success: function (data) {
reload_tabless();
},
function reload_tabless() {
dataTable.ajax.reload(null, false); //reload datatable ajax
}
Please help me rectify it.
it looks like you have the url hard coded to the string 'url' in the code that should do the ajax call before calling reload_tabless() which most probably makes the ajax call to fail, thus not executing the success callback.
I don't think you need that extra ajax call. Simply execute reload_tabless instead of that ajax call.
Use "destroy": true inside DataTable section and call DataTable function again.
It will reload DataTable without postback.

How to get value on php page by jquery ajax call

I am using the jquery ajax script for getting the content of php page without loading of page. Using following script
$('#data_subpartition_result').live('click', function(){
$.ajax({
type: "POST",
url: "temp/model_view_result.php",
context: "language=php&version=5",
data: {train: 0.7, validation: 0.2, test: 0.1},
success: function(result){
$('div.divRightModelContent').html(result);
}
});
});
and my php file code is as follows
<?php
echo $_POST['train'];
// some other php stuff
?>
i am trying to print or using value of data which i have passed with post method by jquery ajax call but i have an error and no any value passed in post method on php page by jquery ajax call. Give me any idea how to get the value.
It's been years since I programmed in PHP, but here are a few jQuery things to correct.
context is not used the way you're using it. It's used to tell the $.ajax call to load a particular section of the url property.
Because you specified type: "POST", your .html() call should be: ('div.divRightModelContent').html(result.d).
There are some good examples on the official jQuery.ajax() webpage. They're pretty good about at least providing you with example data under each property.

Categories