I am working on wijgrid and I have given a radio button to html form.
I have used jquery to get the value of radio button and it is displying on the form but its not showing at grid.
I want to get the value of paramcode on selection of radio button and this value should display at wijgrid.My code is working fine and its showing the value but when I am saving the the data of form its not accepting radio button values inside the grid.
Please help ...Thanks Tina!!
This is my JSON (reformatted for legibility, but actually minified):
{
"jsonWrapperforGrid": {
"page": "1",
"total": "2",
"rows": [
{
"tenantId": 0,
"paramType": "UserGender",
"paramCode":"F",
"langCode":"en",
"paramValue":"Female"
},
{
"tenantId": 0,
"paramType": "UserGender",
"paramCode": "M",
"langCode": "en",
"paramValue": "Male",
"paramBlob": ""
}
]
}
}
This is my jQuery script:
<script type="text/javascript">
$.ajax({
url: "UserGender",
type: "GET",
dataType: "json",
contentType : "application/json",
success: function (responce) {
if (responce.jsonWrapperforGrid.rows.length > 0) {
$.each(responce.jsonWrapperforGrid.rows, function (i, entity) {
$('#gencom01').append(
$('<label />', { 'for': 'gender' + entity.paramValue,
'text': entity.paramValue }),
$('<input />', { 'id': 'gender' + entity.paramCode,
'type': 'radio',
'name': 'gender',
'value': entity.paramValue })
.click(function() {
var inputValue = $('input:radio:[name=+"gendernew"]:checked').val(entity.paramCode);
$("#gencom").val(entity.paramCode );
})
);
});
}
}
});
</script>
This is my HTML:
<body>
<div id="gencom01">
<td><input id="gencom" style="width:205px ;" name="gendernew">
</div>
</body>
Is it really all your code?
If you start making ajax calls at load, maybe it's something you could have handled on the server side? But you probably have your reasons.
First you need to use the $(document).ready(); event, you cannot start appending stuff to a tag that is probably not in your DOM yet.
Your if statement is useless if (responce.jsonWrapperforGrid.rows.length > 0) , your .each() loop will just not do anything if the length is 0, no need to test for that before.
Then even worse, you started declaring a .click() inside a .append(), while it might work, that looks a bit weird and can be source of many errors. It is usually easier to debug to keep your DOM manipulation and your events separate. And use .on(), more up to date.
I don't know your technology behind your AJAX call, but parsing your JSON into a real JS object can help : var jsonData = $.parseJSON(responce);
Thus, it's good practice to make as little .append() as possible, using it in a loop can take time. I'd advise saving your data in a variable and only at the end of your loop you can append everything.
And I don't know what this <td> is doing in your <div>.
Here is how your code could look like, I couldn't test anything since I don't know how your JSON looks like :
$(document).ready(function()
{
$.ajax({
url: "/mgw/pankanis/admin/SysParameter?Paramtype=UserGender",
type:"GET",
dataType: "json",
contentType : "application/json",
success: function (responce)
{
var jsonData = $.parseJSON(responce);
var toAppend = "";
$.each(jsonData.jsonWrapperforGrid.rows,function(i,entity)
{
toAppend += '<label for="gender'+entity.paramValue+'">'+entity.paramValue+'</label>';
toAppend += '<input id="gender'+entity.paramCode+'" type="radio" name="gender" value="'+entity.paramValue+'">';
});
$('#gencom01').append(toAppend);
$("#gencom01 input:not(#gencom)").on("click",function()
{
$("#gencom").val($(this).attr("id").substr(6)); // entity.paramCode
})
}
});
});
Related
Before submitting with Ajax, I am changing the ids of all inputs on the form, due to a need.
The problem is when I submit using Ajax, I need to replace the html of all fields in the form using the replaceWith function, but it is not doing that. It is simply changing the html, but it seems to be keeping the original html when I inspect it in the browser.
HTML should be replaced as shown in image 2.
Why can't HTML be replaced correctly? Shouldn't the replaceWith function be used for such a situation?
var genericModal = getLastGenericModalObject();
var frmFormaContato = genericModal.find('.frm-create-edit');
var valdata = frmFormaContato.serialize();
$.ajax({
url: url,
type: "POST",
traditional: true,
data: valdata,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
frmFormaContato.replaceWith(data);
stopLoadGlobal();
},
error: function (e) {
stopLoadGlobal();
redirectToError(e.status);
return false;
}
});
Thank you :)
The solution was to change the IDs before replacing the HTML according to the DOM.
var dataChanged = changeIds($(data));
frmFormaContato.replaceWith(dataChanged);
I have an AJAX Post that I'm trying to fix, but with a multitude of checkboxes on the input, I'm getting stuck.
At the moment, say I've this:
<input type="checkbox" name="billToEmail[]" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail[]" value="email2#email.com">email2#email.com
And I've a button called "Send Notifications", which starts the following script:
<script>
$('.modal-footer').on('click', '.sendNotificationNow', function() {
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: {
'billTo': $('.billToEmail:checked').val(),
'shipTo': $('.shipToEmail:checked').val(),
'shipFrom': $('.shipFromEmail:checked').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#sentNotifications').modal('show');
toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
toastr.success('Successfully Sent Notifications!', 'Success Alert', {timeOut: 5000});
$('div.notificationssent').fadeOut();
$('div.notificationssent').load(url, function() {
$('div.notificationssent').fadeIn();
});
}
},
});
});
</script>
Now, I'm sure my issues are popping up near the top, where I'm trying to "translate" the multiple values into the data variables. Should I be putting something besides .val()?
I've a few more fields like this that I need to work on with the multiple checkboxes but if I can get some help for the billToEmail alone, I'm sure I can fix the remainder.
First, you don't need the [] sign. So, your checkbox html will look like this :
<input type="checkbox" name="billToEmail" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail" value="email2#email.com">email2#email.com
Second, you need to push selected value on checkbox into javascript array variable using foreach :
var billToEmail= [];
$("input:checkbox[name=billToEmail]:checked").each(function(){
billToEmail.push($(this).val());
});
Third, you need to convert javascript array into string using JSON.stringify().
billToEmails= JSON.stringify(billToEmail);
Then after that, pass the billToEmails variable into your data in AJAX. So, it will look like this :
var dataString = "billTo="+billToEmails+"&shipTo="+$('.shipToEmail:checked').val()+"&shipFrom="+$('.shipFromEmail:checked').val()+"&_token="$('input[name=_token]').val();
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: dataString,
In order to PHP can fetch the array, you need to decode the billToEmails string first using json_decode in your controller.
$variable = json_decode($request->billTo,true);
Try this-
billtoemail = $('input[name='billToEmail[]']:checked").map(function () {
return this.value;
}).get();
or
billtoemail= new Array();
$("input[name='billToEmail[]']").each(function(){
billtoemail.push(this.value);
});
Now send this variable billtoemail like other variable in your ajax. In your controller you can get all the values by a simple foreach($request->billTo as $billtoemail)
So I have on my page a div with id="machine-content", which I use to display various info about my machines. Mainly, I display information in tables. I am trying to use DataTables (https://datatables.net/), but I have problem initializing the table. After click on action (i.e. "show me repairs", "show me workhours"), I load a table element from external html and fill it with data through AJAX according to chosen action.
So here's how my files look.
In index.php (jquery and datatables are loaded in head):
<script src="data.js"></script>
...
<div id="machine-content" class="col-md-9" style="float:right">
</div>
...
External html is super simple:
<h1 id="machine-content-h1"></h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"></table>
I then have data.js that controls index.php. There, I handle clicks to actions and loading of table through AJAX. All the data is loaded correctly but when I want to initialize a DataTable (to get search field, paging, etc.) it doesnt work. As far as I know, I have to initialise it after the data is loaded, anyway I also tried initialising it before. Here is data.js:
//EXAMPLE of handling chosen action with button click
//I TRIED putting //I TRIED putting $.('#example').DataTable(); HERE
//wrapped in $(document).ready
$('#arentals').click(function(){
$( '#machine-content' ).load("/gui/machines/machines/templates/table.html", function() {
load_service_table("RENTALS");
});
});
function load_service_table(action){
var action_url;
switch(action) {
case 'REPAIRS':
action_url='/gui/machines/machines/show_services.php';
break;
case 'RENTALS':
action_url='/gui/machines/machines/show_rentals.php';
break;
case 'REVENUES':
action_url='/gui/machines/machines/show_revenues.php';
break;
default:
action_url='/gui/machines/machines/show_hours.php';
}
$.ajax({
url: action_url,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "html",
type: "POST",
success: function(data) {
//I TRIED putting $.('#example').DataTable(); HERE
$( '#machine-content-h1' ).text(action);
$( '#example' ).html(data);
//I ALSO TRIED putting $.('#example').DataTable(); HERE
}
});
//AND HERE
}
PHP functions are simple and in AJAX return only head and body elements of table, so I guess there is no problem.
So my question is: How can I initialize this thing? I mean, if I am able to set html to #example in AJAX success function, why can't I initialise the same element there? Any help would be deeply appreciated.
EDIT
I always get this error:
jquery.dataTables.min.js:65 Uncaught TypeError: Cannot read property 'aDataSort' of undefined
SOLUTION
I only added $('#machine-content').find('#example').DataTable(); to AJAX success function which now looks like this:
$.ajax({
url: action_url,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "html",
type: "POST",
success: function(data) {
$( '#machine-content-h1' ).text(action);
$( '#example' ).html(data);
$('#machine-content').find('#example').DataTable();
}
});
datatable has a build-in ajax method
$('#myTable').DataTable( {
ajax: '/api/myData'
} );
https://datatables.net/manual/ajax#Loading-data
or use:
$('#machine-content').find('.table').DataTable();
I know this post is older so probably of no help to you now but for anyone else who comes across this.
Something like the following should work:
var adminUsers = {
list: () => {
var action = 'list_users';
var url = base_url+'index.php/admin/users/io';
var data = { }
var response = ajaxRequest.post(action, url, data);
response.then(
function(obj){
var data = JSON.parse(obj);
console.log(data);
//console.log(data.data.result);
$.each(data.data, function(i,e){
var html = '';
html = html + '<tr>';
html = html + '<td>'+e.id+'</td>';
html = html + '<td>'+e.username+'</td>';
html = html + '<td>'+e.first_name+' '+e.last_name+'</td>';
html = html + '<td>'+e.status+'</td>';
html = html + '<td>'+e.locked+'</td>';
html = html + '<td>'+e.uuid+'</td>';
html = html + '</tr>';
$('#users-list tbody').append(html);
});
$('#users-list').DataTable(adminUsers.dataTable());
},
function(jqXHR, textStatus, errorThrown){
ajaxRequest.error(jqXHR, textStatus, errorThrown);
});
},
dataTable: () => {
var config = {
initComplete : function() {
$("#users-list_filter").detach().appendTo('#search');
$("#users-list_length").detach().appendTo('#display_length');
$("#users-list_length").attr('style', 'margin-right:10px;');
$("#users-list_filter input").addClass('form-control');
},
language: {
search: "",
searchPlaceholder: 'Search...'
}
}
return config;
}
};
I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.
I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/