i am trying to dynamically have javascript object properties to send through ajax..
Here is what i have done..
var checkBoxName = $(this).attr('name');
var postData = {
Module: ModuleID,
Group:GroupID
};
if($(this).is(":checked")){
postData.checkBoxName = 1;
}else{
postData.checkBoxName = 0;
}
$.ajax({
url: "<?php echo base_url(); ?>user_site/user_group_add_pri/updatePrivilege",
data:postData,
type: "POST",
success: function (output) {
console.log(output);
}
i have multiple checkboxes. every checkbox has different name so what i am trying to do is post data to controller with checkbox name and its value..
but instead it is sending checkBoxName for all checkboxes...
i mean CheckBoxName is a variable but when i did used it like this cuz i thought it would send its value but it is not sending,
i tried like this postData.checkBoxName = but instead of value of variable it is sending as Text??
=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
Update:
The event Occurs when checkbox value is changed.
$("input[type='checkbox']").on('change',function(e){
///Above Code Inside Here
}
If I understand right, I might have an idea.
You can do a loop through all your checkboxes and check if they are checked or not. Then push it into a tab and send through ajax :
var infoCb = new Array();
$('input[type=checkbox]').each(function(){
var tempArray = {
'nameOfCb' : $(this).attr('name'),
'value' : $(this).attr('checked')
}
infoCb.push(tempArray);
});
And then send it via Ajax.
Related
I am trying to post the 'ID' from my html table to delete the row from the SQL database when the delete button is click. So far it would appear the POST is not working but the PHP code is.
Here is the JavaScript code which takes the selected table rows value from the first columns (ID) when I select it, and on pressing the delete button a message box displays the ID (this works fine so it would appear it is reading the value). The next part then displays a message box confirming the delete, which on clicking OK does nothing.
JavaScript
$(function(){
$("#tblAssets tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
$('#btnDelete').click(function(e){
var value = $("#tblAssets tr.selected td:first").html();
alert(value);
if (confirm("Are you sure you want to delete this asset?")) {
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : value;
success : function() {
}
});
}
});
});
And here is the PHP code. When I manually adjust $value to equal an ID in my database table it works and deletes the row.
$value = $_POST['value'];
$sql = "DELETE FROM [Assets].[dbo].[Hardware] WHERE [ID] = $value";
$result = sqlsrv_query( $conn, $sql);
Thanks
this line is wrong
data : value;
Try this
data : {value:value},
^ not semi colon
You are passing value without parameter. Add parameter:
$(function(){
$("#tblAssets tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
$('#btnDelete').click(function(e){
var data = {
"value": $("#tblAssets tr.selected td:first").html();
};
if (confirm("Are you sure you want to delete this asset?")) {
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : $.param(data);
success : function() {
}
});
}
});
});
or your ajax data should be like this:
data: "value="+$("#tblAssets tr.selected td:first").html();
Moreover you cannot use ; here:
data : value;
it should be ,
data : "value"+value,//pass value with the name:ie value=10 . replace the ajax part alone as given below
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : "value"+value,//
success : function() {
}
});
You didn't create an object and passed the variable on the fly directly.
var value = $("#tblAssets tr.selected td:first").html();
//alert(value);
if (confirm("Are you sure you want to delete this asset?")) {
var dataValue = {
theValue : value // You have to create an object here
};
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : dataValue, // pass the object here
success : function() {
}
});
}
On the server side:
$value = $_POST['theValue'];
Try this one.
Assume I have 2 textbox, that's serial_no10 and serial_no12. That 2 textbox appear not simultaneously depends on case
1 PHP file for checking the SN.
1 DIV status to display the data.
jQuery Ajax
var serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();
$.ajax(
{
type: "POST",
url: "chk_dvd_part_no.php",
data: 'serial_no10='+ serial_no10 +'&serial_no12='+ serial_no12,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
}
}
}
HTML
<div id="status"></div>
PHP File
if(!empty($_POST['serial_no12']))
{
echo "Serial No 12";
}
else if(!empty($_POST['serial_no10']))
{
echo "Serial No 10";
}
Now I'm facing the problem when get POST from textbox serial_no_12, the value is undefined. But if get POST from textbox serial_no_10, I got the value.
Is that something wrong with that PHP code? Or I do something that should not be.
You have to just empty the variables before filling up. As if value is not reset then last value computed would remain in variavar
serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();ble
change it with
var serial_no10='';
var serial_no12='';
serial_no10 = $("#serial_no10").val();
serial_no12 = $("#serial_no12").val();
Noww do things it will all good
Give your form tag an id if it has no anyone. and than do something like this.
var form = $("#form_id").serialize();
$.ajax({
type: "POST",
url: "chk_dvd_part_no.php",
data: form,
success:function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
//do your stuff
});
}
});
and in php file get your post variable by its name, suppose you have 2 inputs name serial_no10 and serial_no12
now do your php code like this.
if( isset($_POST['serial_no10']) && $_POST['serial_no10'] != '' ){
echo 'Serial No 10';
}
if( isset($_POST['serial_no12']) && $_POST['serial_no12'] != '' ){
echo 'Serial No 12';
}
I have an empty form tag, and a function which generates 4000 hidden inputs which contains the data to be send by the form.
Generating the 4000 hidden inputs is pretty fast (takes about 4ms). However, the browser freezes for about 1 second when i am appending the hidden inputs in the form tag.
I have also wrapped the hidden inputs in a <div/> tag, but doesn't helps too much.
Is there any way to set the form data programmatically, without using the input DOM elements?
Something like:
$form[0].setData([{ id: 1, value: "A" }, { id: 2, value: "B" }]);
$form.submit();
Here is the function which generates the hidden inputs
function saveUIPositions() {
var $form = $("#saveUIPositionsForm");
$form.empty();
console.time("ui");
var array = [];
array.push("<div>");
var items = dataTable.dataView.getItems();
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
var index = dataTable.dataView.getRowById(item.Id) + 1;
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Item_Id' value='");
array.push(item.Id);
array.push("' />");
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Index' value='");
array.push(index);
array.push("' />");
}
array.push("</div>");
console.timeEnd("ui");
// here it gets very costly (and not because of array.join())
$form.append(array.join(""));
$form.submit();
};
Maybe you can send this data using ajax ? If so you will not have to generate and append your 4K hidden inputs to the DOM.
If ajax is not an option, can you give us the code generating and appending your inputs ? Maybe it can be optmized.
I wrote a small jsFiddle (open your debug console to see time informations)
to illustrate the difference between a generate then append all solution:
for(var i=0; i<4000; i++)
inputs += '<input type="hidden" value="' + i + '"/>'
$('form').append(inputs);
and generate and append each:
for(var i=0; i<4000; i++)
$form.append('<input type="hidden" value="' + i + '"/>');
You don't even really need a form element when working in just Javascript, data can be sent to your server with an ajax request.
$.ajax({
url: "myScript.php", //The script on your server that deals with the data
data: {
dataA: "a",
dataB: "b",
dataC: "c" //Your form input name and value key pairs
},
success: function(data){
alert("Form Submitted, Server Responded:"+data); //The server response
},
error: function(data){
alert("Error contacting server:"+data); //Error handler
}
});
You don't even need to reload the page when the form is submitted. Unless you want to, then just add:
location.href="http://link.com";
to the success callback.
You don't need to add the inputs to the DOM, you could create an array of the data an post the form via ajax e.g.
inputNames = 'YourInputNameHere'; // Could be an array of names
generatedData = arrrayOfData //presumably generated elsewhere
for (i=0;i<400;i++) {
formData[inputName][i] = generatedData[i]
// if you are using an array of names you want to change the above line to
// formData[inputName[i]] = generatedData[i]
}
$('body').on('submit', '#myForm', function(e) {
e.preventDefault();
postUrl = 'url/to/send/data';
// get any other use inputs that might have been taken from user ignore
// this line if there are no inputs
formData[] = $(this).serialize();
$.ajax(
{
url: postUrl,
type: 'POST',
data: formData,
dataType: 'html',
success: function( data )
{
// redirect, post message whatever
}
}
)
});
Hope this helps and makes sense.
I am pretty sure this is not so complicated but I have been for hours trying to figure out how to catch the id of this dynamically generated anchor tags.
What I do in my code is that everytime a text input changes, theres an ajax request that goes to a php file and returns me a json array with the prices then I render this results of search in buttons that will be clickable to do other types of request but so far here's where I'm stuck.
heres's the code that loops through the array and renders this buttons (NOTE:The Id of the buttons are variables rendered by the function too.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
success: function(data){
$('#loader_s').hide();
var jsarray = JSON.parse(data);
var length = jsarray.length;
for(i=0;i<jsarray.length;i++){
var index1 = i;
var index2 = Number(i++) + 1;
var index3 = Number(i++) + 2;
$('#modal-bod').append('<a onclick="renderProds();" class="btn btn-default-item prod_sel" style="margin-top:10px;" id="'+index3+'" data-dismiss="modal">'+jsarray[index1]+' <span class="pull-right" st>lps. '+jsarray[index2]+'</span></a>');
}
}
Then here's the function renderProds()
function renderProds(){
var id = $(this).attr('id');
alert(id);
}
the alert is just to try and catch the values for testing purposes, but what really goes there is another Ajax request.
The only thing I get here is that the var Id is undefined...
You can pass object like
function renderProds(obj) {
var id = obj.id;
alert(id);
}
Pass invoker object like
onclick="renderProds(this);"
I would do :
onclick="renderProds(this);"
function renderProds(that){
var id = that.id;
alert(id);
}
You use jQuery.. so USE jQuery !
Ajax can do the JSON.parse for you with just dataType: "json".
The inline onclick is bad practice.
Move the success function to make your code more readable.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
dataType : 'json',
success: productsUpdate
});
function renderProds(event){
var id = $(event.target).attr("id");
alert("Id is:"+id);
}
function productUpdate(data){
$('#loader_s').hide();
for(i=0;i<data.length;i++){
var link = $('<a>....</a>');
link.click(renderProds);
$('#modal-bod').append(link);
}
}
Now, this is readable.
Complete the link creation with your code, without the onclick, remove the inline css and use a real css selector and finally, check this ugly Number(i++)+ .... it looks so bad.
Hi There I need to get the names and values of checkboxes that have been checked into an array name selected, I cannot for life of me get it working, below is my attempt, if someone could clrify what I am doing wrong that would be brilliant.
//Location AJAX
//var dataObject = new Object();
var selected = new Array();
$('#areas input.radio').change(function(){ // will trigger when the checked status changes
var checked = $(this).attr("checked"); // will return "checked" or false I think.
// Do whatever request you like with the checked status
if(checked == true) {
/*$("input:checked").each(function() {
selected.push($(this).attr('name')+"="+$(this).val();
});
alert(selected)*/
getQuery = $(this).attr('name')+"="+$(this).val()+"&location_submit=Next";
$.ajax({
type:"POST",
url:"/search/location",
data: getQuery,
success:function(data){
alert(getQuery);
console.log(data);
// $('body.secEmp').html(data);
}
});
} else {
//do something to remove the content here
alert("Remove");
}
});
You're missing the closing parantheses on the call to selected.push. It should be:
selected.push($(this).attr('name')+"="+$(this).val());
Otherwise, it looks fine.
Another, possibly simpler, way to do the same thing is to use map instead of each:
var selected = $('input:checked').map(function() {
return $(this).attr('name')+"="+$(this).val();
}).get();