Jquery Datatables populate after form post - javascript

I'm trying to do a form submit (POST) with some parameters and based on the parameters I want to populate my datatable. But I'm not very good with Javascript (My language is Java), so I'm trying to do it with an Ajax call. But it won't work for me. Everything works for me, except doing a POST with parameters to the servlet. The datatable always populate automatically, but it should populate after the form submit.
Does someone know an example of my case? I read a lot of form posts here and tutorials, but none of this case (?).
My code is now as follows, this works for me. Except I can't sort or search anymore in this table. What is missing?
Thank you.
<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>
<form name="myform" id="myform" action="" method="POST">
<label for="season">Season:</label>
<input type="text" name="season" id="season" value=""/> <br />
<label for="type">Type:</label>
<input type="text" name="type" id="type" value=""/> <br/>
<input type="button" id="btnSubmit" name="btnSubmit" value="Search">
</form>
<table class="display" id="example">
<thead>
<tr>
<th>Name</th>
<th>NationId</th>
<th>RegionId</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
<!-- data goes here -->
</tbody>
</table>
<script>
$("#btnSubmit").click( function() {
var formData = "season=" + $("input#season").val() + "&type=" + $("input#type").val();
$('#example').dataTable( {
"bJQueryUI": true,
"bProcessing": true,
"bDestroy": true,
"sAjaxSource": "/servlets/service/competitions/",
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = ${esc.d}.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": formData,
"success": fnCallback
} );
}
} );
} );
</script>

Ok, this is the full answer for you question
You need to make three events, the first load the database information in your datatable, the second event inserts the new information on the database, and the third refresh the datatable content.
<html>
<head>
<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
//Global variables
var otable;
var dataTab;
$(document).ready(function () {
chargeData();
$('#btnSubmit').click(function () {
insertData();
});
});
// 1. charge all data
function chargeData() {
$.ajax({
type: "POST",
//create a method for search the data and show in datatable
url: "/servlets/service/competitions/",
contentType: "application/json; charset=utf-8",
data: '{ }',
dataType: "json",
success: AjaxGetFieldDataSucceeded,
error: AjaxGetFieldDataFailed
});
}
function AjaxGetFieldDataSucceeded(result) {
if (result != "[]") {
dataTab = $.parseJSON(result);
//instance of datatable
oTable = $('#example').dataTable({
"bProcessing": true,
"aaData": dataTab,
//important -- headers of the json
"aoColumns": [{ "mDataProp": "season" }, { "mDataProp": "type" }],
"sPaginationType": "full_numbers",
"aaSorting": [[0, "asc"]],
"bJQueryUI": true,
});
}
}
function AjaxGetFieldDataFailed(result) {
alert(result.status + ' ' + result.statusText);
}
// 2. this function only insert the data in your database
function insertData() {
var email = $("#season").val();
var evento = $("#type").val();
$.ajax({
type: "POST",
//in this method insert the data in your database
url: "/servlets/service/competitions/",
contentType: "application/json; charset=utf-8",
data: '{ season : "' + season + '", type : "' + type + '"}',
dataType: "json",
success: AjaxUpdateDataSucceeded,
error: AjaxUpdateDataFailed
});
}
function AjaxUpdateDataSucceeded(result) {
if (result != "[]") {
alert("update ok");
refreshDatatable();
}
}
function AjaxUpdateDataFailed(result) {
alert(result.status + ' ' + result.statusText);
}
// 3. This function refresh only the datatable not all page in varius events you can call like INSERT,UPDATE,DELETE ;D
function refreshDatatable() {
$.ajax({
type: "POST",
//same event used in chargeData function
url: "/servlets/service/competitions/",
contentType: "application/json; charset=utf-8",
data: '{ }',
dataType: "json",
success: AjaxRefreshDataSucceeded,
error: AjaxRefreshDataFailed
});
}
function AjaxRefreshDataSucceeded(result) {
if (result.d != "[]") {
var jposts = result;
dataTab = $.parseJSON(jposts);
//when the instance of datatable exists, only pass the data :D
oTable.fnClearTable();
oTable.fnAddData(dataTab);
}
}
function AjaxRefreshDataFailed(result) {
alert(result.status + ' ' + result.statusText);
}
<script>
</head>
<body>
<form name="myform" id="myform" action="">
<label for="season">Season:</label>
<input type="text" name="season" id="season" value=""/> <br />
<label for="type">Type:</label>
<input type="text" name="type" id="type" value=""/> <br/>
<input type="button" id="btnSubmit" name="btnSubmit" value="Search">
</form>
<table class="display" id="example">
<thead>
<tr>
<th>SEASON</th>
<th>TYPE</th>
</tr>
</thead>
<tbody>
<!-- data goes here -->
</tbody>
</table>
</body>
</html>

Here the data is passed as string(formData) in ajax function and by default ajax expect the json object. Passing data in string can be done in two ways
1) Append the generated query string to the url
oSettings.jqXHR = ${esc.d}.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource + "?" + formData, /* here url need be proper, as url can have some query string params in that case it shoukd be join with "&" not "?" */
/* "data": formData, no need to have data config then */
"success": fnCallback,
"processData": false
} );
2) when data is already serialized into string then set processData flag to false in ajax
oSettings.jqXHR = ${esc.d}.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": formData,
"success": fnCallback,
"processData": false
} );

I have the same functionality as you. The way I approach things though is a little bit different.
What I do ...
<input type="text" id="searchCondition"/>
<div id="container">
<div id="ajaxDataTable"></div>
</div>
On document.ready I call the ajax function to get me the datatable passing the value of searchCondition to my servlet. The result (THIS IS JUST THE TABLE) is put in the ajaxDataTable div. On success of the ajax command, I do the normal initializations on the datatable.
Now on any search, I call the same ajax command and pass again the search condition.
Works fine for me!

Related

Why it's not working when I try to parse the data in ajax

I am uploading excel file using ajax and then from there receiving the state and the reason of the failure from the upload page to the PHP page ajax function using json_encode but am not able to access the data each one where as the alert of the data is showing perfectly
$(document).ready(function() {
$('#excel_file').change(function() {
$('#export_excel').submit();
});
$('#export_excel').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "excelupload.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data, status) {
alert(data); //
var datas = JSON.parse(data); // not working
$('#result').html(datas.a); //not woking
$('#reason').html(datas.b);
$('#excel_file').val('');
}
});
});
});
<tr style="background-color:#666;">
<td style="color:#FFF;">
<div id="result" style="color:red;"> </div>
</td>
<td style="color:#FFF;">
<div id="reason" style="color:red;"> </div>
</td>
</tr>
PHP:
<?php
$insertTable= mysql_query("INSERT INTO `rt_state_mst`( `OLE_STATE_NAME`, `OLE_COUNT_ID`) VALUES ( '$state' , '$country_result[0]');");
echo json_encode(array("a" => $state, "b" => "Record has been added"));
?>
excelupload.php should contain only php content. And if you want to return json_encode data from excelupload.php then use the below property in your ajax code.
dataType: "json",

jquery: Removing class transferred from JSON response

I created a function in laravel that raises some pictures together and returns their names, so I can view them immediately on the page without having to refresh the browser. I want to allow deleting a photo, but it does not give that return values ​​through JSON are not in the DOM. What am I doing wrong?
HTML:
<form action="" enctype="multipart/form-data" id="data">
<input type="file" name="image[]" multiple>
<button type="submit">send</button>
</form>
<hr>
<div class="returns_img"> </div>
<script type="text/javascript">
$("form#data").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "upimage",
type: "POST",
data: formData,
async: false,
success: function(msg){
$(".returns_img").append(msg);
},
cache: false,
contentType: false,
processData: false
});
});
$("#dell_msg").click(function(){
$(".up_side").removeClass(".list_img");
});
Routes.php:
Route::post('upimage', function(){
foreach (Input::file("image") as $image) {
$imagename = time(). $image->getClientOriginalName();
$upload = $image->move(public_path() . "/img/",$imagename);
if ($upload) {
$uploaddata [] = $imagename;
}
echo "<div class='list_img'><img src='/img/". $imagename. "'><button id='dell_msg'>X</button> </div>";
}

Send checkbox values in Ajax

The following code is my original code. In the code, I tried to post value of an input for each checkbox which is checked.
<tbody class="myFormSaldo">
<tr>
<td> <input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$ref.'" onchange="enableList(this);" class="chb_group" /> </td>
<td> <input name="items['.$i.']" type="text" readonly value="'.$obj->items.'" /> </td>
<td> <input name="size['.$i.']" type="text" readonly value="'.$obj->size.'Kg" /> </td>
<td> <input name="quantity['.$i.']" type="text" readonly value="'.$obj->myquantity.'" /> </td>
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_size=$_POST['size'][$i];
The code above is working fine. It post the value of each inputs for each checkbox which were checked. For example; if there were three checkedbox which were checked and the form was submited, then it would post three arrays (3 loop) of : $product_name,$product_size,etc..
What I want now is to use Ajax. Like this:
var product_name= document.getElementById('product_name').value;
var product_size = document.getElementById('product_size').value;
$.ajax(
{
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: product_name='+product_name+'&product_size ='+product_size ,
cache: false,
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
But it doesn't count or find the checkbox
So my question now is how to do the same as the php do with foreach($_POST['checkbox'] as $i) in ajax?
I am just a beginner in all of these things.
Thank you for any help.
You are using your product_name as a string, not as a variable:
Try this:
data: 'product_name='+product_name+'&product_size='+product_size,
Or, as Ghost sad in comments, use formdata.
var dataString = $('form').serialize();
and later, in the ajax:
data: dataString,
...
Try this...
<script>
$.ajax({
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: "{'product_name':" + product_name + ", 'product_size':" + product_size+ "}",
cache: false,
dataType: "html"
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
</script>
Try this
Ajax is simplified check here
var data = $('form').serialize();
$.post( "../actions/selectReferenceOrder.php", { name: data}).done(function( data ) {
alert( "Data Loaded: " + data );
});
OR
$.post( "../actions/selectReferenceOrder.php", { product_name: product_name, product_size : product_size }).done(function( data ) {
alert( "Data Loaded: " + data );
});

send json form data to server

I am trying to take data from a form and send it to remote server :
The code is:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h2>Create Sensor</h2>
<form id="form">
<form enctype='application/json'>
<input name='version' value='1.0.1'>
<input name='sensors[0][sensor]' value=''>
<input name='sensors[0][output][0][name]' value=''>
<input name='sensors[0][output][0][type]' value=''>
<br>
<input id="input" type="submit" name="submit" value="Create Sensor" />
</form>
<script>
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$(document).ready(function() {
$('#input').click(function() {
var send = $("#form");
$.ajax({
url: "http://posttestserver.com/post.php",
type: "POST",
data: send,
success: function (sreg, status, jqXHR) {
alert(JSON.stringify(sreg));
},
error: function (jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
});
});
</script>
</body>
</html>
But the JSON is not properly formed as I am returning by alert. Can anyone please help me out? I am not good at coding just trying to learn
This is the expected JSON:
{
"version": "1.0.1",
"sensors": [
{
"sensor": "",
"output": [
{
"name": "",
"type": ""
}
]
}
]
}
Another query is : is there any online platform through which I can get expected JSON by inputing JSON form like this? Please help me out
Your script at: post.php should work with form data and return a JSON Object.
To send array data to your script you should use.
var send = $("#form").serializeArray();
You can easy check if your JSON is valid here:
http://jsoneditoronline.com/

on click save data of drop down list using Java Script , Jquery or Ajax

I have a drop down list. I am trying to save data of that drop down list on click event without using a button. I have tried some code but it is not working please help.
Here is the view of my drop downlist
#model MyYello.Admin.Models.FeedBack
#{
ViewBag.Title = "Feed Back";
}
#*#using (Ajax.BeginForm("SelectFeedBack", "Admin", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "mainContent" }, new { #id = "formId" }))
*#
<form method="post" id="formId" action="#Url.Action("SelectFeedBack","Admin")">
#Html.ValidationSummary(true);
<fieldset>
#Html.HiddenFor(item => item.FeedBackId)
<legend>Create Notes</legend>
<div class="editor-label">
#Html.LabelFor(item => item.FeedBackDrpDown, "Select feed Back")
</div>
#Html.DropDownList("FeedBack")
<input type="hidden" id="isNewNote" name="isNewNote" value="false" />
#* <p>
<input type="Submit" value="Save" id="Save" />
</p>*#
#* #Url.Action("CreateNote", "Admin")*#
</fieldset>
</form>
<script type="text/javascript">
$(function () {
$("#FeedBack").change(function () {
console.log("test");
$("#formId").submit(function () {
console.log("test1");
$.ajax({
type: "POST",
//url: urlAction,
data: {},
datatype: "JSON",
contentType: "application/json; charset=utf-8",
success: function (returndata) {
if (returndata.ok)
window.location = returndata.newurl;
else
window.alert(returndata.message);
}
});
});
});
});
You can adjust your onChange-Method like this:
$("#FeedBack").change(function () {
var urlAction = "/whatever/url/"; // someURL
// var urlAction = $("#FormId").attr("action"); // or grab the form-url?
var postData = {
"whateverName" : $(this).val() // selected drop-down-value
};
$.ajax({
type: "POST",
url: urlAction,
data: postData, // send postData-Object
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function (returndata) {
// make shure that the attributes ok,newurl and message are available - otherwise this throws an error and your script breaks
if (typeof returndata.ok !== "undefined" && typeof returndata.newurl !== "undefined" && returndata.ok)
window.location.href = returndata.newurl;
else
window.alert(returndata.message);
}
});
});
this is how you just submit the select-field-value to whatever URL. Do you wish to submit the whole form when the dropdown changes?

Categories

Resources