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 );
});
Related
Hello i try to display a price form an AJAX call, i putted an input just to check if you get the price and it's work but i can't display the price result on a span.
{{$product->price}} have default value but it's change depending the size, i would like to display the result also in the space and hide the input.
someone knows how to do that ?
Here my html :
<input type="text" placeholder="{{$product->price}}"value="{{$product->price}}">
<div id="price">
<span class="text-muted text-normal" id="price"> {{$product->price}}€</span>
</div>
<input type="hidden" name="price" id="price" value="{{$product->price}}" />
Here my javascript :
<script>
$('#size').change(function () {
$.ajax({
type: 'GET',
url : '../{{$product->id}}/ballons-entrainement/size-price',
dataType: "json",
data : {
size : document.getElementById('size').value
},
success:function(data){
console.log(data);
$('input').attr('value', data.price);
}
});
});
</script>
You try with .html() like
<script>
$('#size').change(function () {
$.ajax({
type: 'GET',
url : '../{{$product->id}}/ballons-entrainement/size-price',
dataType: "json",
data : {
size : document.getElementById('size').value
},
success:function(data){
$('span#price').html( data.price );
}
});
});
</script>
I want to do an ajax request to update the status of an item, but for one or many selected item.
So how can I post all the selected checkbox items to process it on the handle page?
Here is some code I use., but it will only post one item to the process page.
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[78]">
</td>
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[182]">
</td>
And the javascript
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = {
item: $('input[name=item\\[\\]]').val(),
}
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
Assign the unique name to each checkbox
Put all checkboxes in a form tag (all input fields in a single form).
Use serialize() or serializeArray() for collecting data from form
store data in var formData
Code:
<form id="form-name">
<tr>
<td>
<input type="checkbox" name="item[1]">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="item[32]">
</td>
</tr>
</form>
Javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = $('#form').serializeArray();
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
},
error: function (data) {
console.log('Error:', data);
}
});
This will post an array of items to the url.
I did same thing in minor different way.
I got list of checkbox and names contain their id.
<input type="checkbox" class="bulkChecked" name="{{$value->id}}">
And Inside your event handler
var ids = [];
$(".bulkChecked:checked").each(function () {
ids.push($(this).attr("name"));
});
So at this point you have got ids of checked boxes. No you can pass 'ids' array with your ajax call
For destination text field, based on the input, the auto suggestion will be displayed as checkboxes. I can select one or more values and my requirement is to get these selected values on the controller side, Once I click on the search button. How can I achieve this for dynamic checkboxes, please provide any suggestions.
jquery:
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
HTML:
<form method="post" id="searchForm" action="someAction/showStatistics" id="ems">
<label>Destination</label>
<input type="text" id="destinationName" name="destinationName" value="${someForm.destinationName}" class="field" />
<div class="dest"></div>
<input type="submit" class="button" value="search" />
</form>
Try this
$(document).ready(function () {
var dynamicCheckbox = [];
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
};
});
}
});
$('.button').on('click', function (event) {
event.preventDefault();
$('.dest input:checked').each(function() {
dynamicCheckbox.push($(this).attr('name'));
});
console.log(dynamicCheckbox);
});
});
Here in dynamicCheckbox you will get the names of the checked checkboxes.
Hope that's what you need!
I'm very new in this topic.I have a Json result something like this :
{
"span": " 1",
"numcard": "12",
"chan": " Yes",
"idle": "Yes",
"level": "idle ",
"call": "No ",
"name": ""
}
How can I show all the json data using a ajax .I currently have this code written up and although i am getting the data its not quite working the way i want it to be.
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$.each(data, function(key, val) {
$("#span").val(val.span);
$("#numcard").val(val.numcard);
$("#chan").val(val.chan);
$("#idle").val(val.idle);
$("#level").val(val.level);
$("#call").val(val.call);
$("#name").val(val.name);
});
}
}
});
});
<input id="span" name="span" value="" />
<input id="numcard" name="numcard" value="" />
<input id="chan" name="chan" value="" />
<input id="idle" name="idle" value="" />
<input id="level" name="level" value="" />
<input id="call" name="call" value="" />
<input id="name" name="name" value="" />
when I try to alert ,example alert(val.span) it keep showing undifined .Does anyone with experience in this topic and see if any problem about my code? Any help would be greatly appreciated.Thank you .
You are returning a single set of values so you do not need the each within your success handler. Try this:
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
In theory, you shouldn't need the data != "" check as your server side code should not be allowed to return an empty response for when the result of the request is 200 OK.
Try this:
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
});
});
should be
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
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!