POST dynamic HTML table values to jQuery AJAX - javascript

I am trying to get all the values present in my dynamic HTML table and POST the values to AJAX.
I have HTML table like this
When i press '+' , I can able to add rows dynamically . When i click save, How to POST array values from this HTML table to AJAX, so that i can meanwhile INSERT those values into MYSQL
I have tried getting the 'text' of each td present in my table
var rows = $("tbody tr",$("#myTable")).map(function() {
return [$("td",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
This is getting me -> <input type="text"> and so on.

you are returning the innerHTML, which is... HTML.
you can get the value of a input element with .val()
how does this work for you?
return $("td input").map(function() {
return $(this).val();
});

Use serialize function using jQuery
<script type="text/javascript">
(function ($) {
$('#formID').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/pathTo/process_form.php',
data: $('#formID').serialize()
});
});
})(jQuery);
</script>

var rows = $("td input",$("#myTable")).map(function() {
return { name : $(this).attr('name'), value :$(this).val()};
});
and you should get :
[
{
name : 'inputname',
value : 'inputval'
},
{ ... }
]
This would return an array like the .serialize() method

Related

how to pass checkboxes to mysql using ajax(jquery)?

I want to pass values of multiple checkboxes to mysql using array via ajax(Jquery).
Any ideas?
I wrote two pices of code , maybe some one help me to combine them?
$(document).ready(function(){
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
}).get();
$("#ajaxDiv").html(selected);
});
AND
<script>
$(document).ready(function () {
$('.item').change(function(){
if($(this).is(':checked')){
var name = $(this).val();
$.post('load.php', {name:name}, function(data){
$('#name-data').html(data);
});
}
});
});
</script>
2nd code: in "load.php" you can access the sent values by using $_POST['name'], etc and put them in the database with a simple mysqli-query. dont Forget to check the values, before you put them into the database.

How to print multiple html tags in jquery

How to print the multiple input boxes using jquery
I am using the following code
<script type="text/javascript">
$(document).ready(function(){
$("#taxId").change(function(){
var tax_id=$("#taxId").val();
$.ajax({
type:"post",
url:"<?php echo base_url();?>index.php/pranasInventory/get_tax_detail",
data:{tax_id:tax_id},
success:function(data)
{
var json_obj = $.parseJSON(data);//parse JSON
var len=json_obj.length;
for (var i=0;i<len;i++)
{
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
}
});
});
});
</script>
It print only one input tag.
my console message like this
Service tax # 14%<input id='taxcal' name='taxcal' placeholder='0.00'>
swachh bharat cess # 0.5%<input id='taxcal' name='taxcal'placeholder='0.00'>
I want print two input box.
please help me
The html function replaces the whole content.
You might replace
var len=json_obj.length;
for (var i=0;i<len;i++) {
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
with
$('#taxDetail').append(json_obj.map(function(obj){
return $("<input placeholder='0.00'>");
});
but you need to decide how to handle the ids of the added inputs as you can't obviously use the same for all.
.html replaces the whole content of the div. You must use JQuery append or prepend methods.

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

Not able to set form attribute value after post it

I've the form and it looks like :
<form method="POST" action="create.php" data-id="0" class="postForm">
<input type="hidden" id="#formId" value="1">
<textarea class="formBodyText"></textarea>
<button type="submit">Post</button>
</form>
The ajax call for this form is as :
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
$.post("create.php",{'formId':$("#formId").val(),'formBodyText':$(this).find('.formBodyText').val()},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
$(this).attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
the problem is with $(this).attr("data-id",data); , it's not setting the new value for the form.
what wrong with this code??
Try,
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
var cache = $(this); // get the form object here and use that inside of $.post
$.post("create.php",
{'formId':$("#formId").val(),
'formBodyText':$(this).find('.formBodyText').val()
},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
cache.attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
this inside the ajax handler does not refer to the submitted form, you can use a closure variable like $form as shown below to fix this.
$(document).on("submit", ".postFrom", function (event) {
event.preventDefault();
var $form = $(this);
$.post("create.php", {
'formId': $("#formId").val(),
'formBodyText': $(this).find('.formBodyText').val()
}, function (data) {
console.log("Return : " + data); //working fine , I mean getting expected result
$form.attr("data-id", data); // want to set the return data as form data-id attribute value
});
});
jQuery.ajax()
The this reference within all callbacks is the object in the context
option passed to $.ajax in the settings; if context is not specified,
this is a reference to the Ajax settings themselves.

How to put alert value to element

in this code i am trying to get the alert value to the element.
brief:
my ajax code checks the database values and gets the new values from database and
displays the fetched values in alert. but i am not able to put that alert values into
element...
How can i do this?
Code:
<script>
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
var rowNum = $(this).parent().parent().index();;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
setTimeout(alert(data), 2000);
var allTds = $("#rtable tr:eq('"+rowNum+"')").find('td');
$(allTds)[4].html(data[0]);
$(allTds)[3].html(data[1]);
document.getElementById("#div1").innerHTML=data;
},
error:function(data)
{
document.getElementById("#div1").innerHTML="It was a failure !!!";
}
});
});
});
</script>
HTML code:
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
In alert(data) i am getting the value.
but when i put same value like this
document.getElementById("#div1").innerHTML=data;
it is not applying the value to element
you don't need # using javascript's getElementById
try this
document.getElementById("div1").innerHTML=data; //notice no `#` in front of div1
or
using jquery that should be
$('#div1').html(data);
try
document.getElementById("div1").innerHTML=data[0];
document.getElementById("div2").innerHTML=data[1];
or
$('#div1').html(data[0]);
$('#div2').html(data[1]);
Pass the actual data inside the object to the HTML element, not the object itself.

Categories

Resources