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

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.

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.)

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.

Show response from server on web page using AJAX?

I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes

200/'parsererror' with jquery on ajax post to a https

I've read loads of other questions about this argument, but none could solve my problem.
I make a call to a php page in this way.
$.ajax({
url: 'https://mydomain/page.php',
type: "POST",
data: {
"arg1": arg1,
"arg2": arg2
},
success: function(data, textStatus, xhr) {
//do stuff
},
error: function(xhr, textStatus) {
alert("doLogin\n- readyState: "+xhr.readyState+"\n- status: "+xhr.status);
}
});
Now, if I put this stuff on the same server as the php it works fine. Troubles start when I launch it from localhost.
In that case I receive the following in the xhr:
readyState=0, status=0, statusText="error".
Reading some answers on the topic it seems to be because of a same-origin restriction, so I added a few parameters to the call. notably:
dataType:"jsonp",
crossDomain: true,
Apparently this works better, cause now I receive readyState=4, status=200, statusText="success". Trouble is, textStatus="parsererror". I also tried other things as jsonpCallback, cache, async, jsonp in many configurations with no luck.
Now, I receive no data back, cause this call will only give me a cookie that I need.
My question is: am I doing things correctly, for starters? In both cases, what is the reason of such an error? Does the fact that I call a 'https'/POST change something, rather than a plain http/GET?
Second question is, later on I will have to call some webservices through soap requests, which will return data in xml. Will using this same technique work (assuming jQuery doc is fine and I can write dataType:"jsonp xml" to have it converted on the fly (and assuming it is the right technique as well))? I assume it won't be, as jsonp expects something on the line of callbackFN({...}) rather than an xml, right?
If none of this is correct, what would the correct way to proceed be? I can't touch the server, thus I am limited to client side.
If you set dataType as JSONP, you can only get data as JSON.
So if the url (https://mydomain/page.php) doesn't response a JSON object, you will get parsing error, because it tries to parse it and fails.
JSONP is for JSON format data only! So if you receive a parseerror this means that the output of your PHP might not be well-formed JSON
And no, it is not easily possible to have XML as response to a JSONP call ..

How to avoid values not to display with the url while using window.location.href to pass values from one page to other?

In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!

Categories