Dynamically form not submitting properly AJAX PHP - php

I am trying to generate dynamically form in table and submit but there is problem in my code which is difficult for me solve,
$(document).ready(function() {
$('#btnsummary').on('click', function() {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
$.ajax({
url: "tblsum.php",
method: "POST",
dataType: 'JSON',
data:
"&date=" +
date +
"&soid=" +
soid,
success: function(response) {
if ( response.length == 0 ) {
alert("NO DATA FOUND!");
}
else{
$("#tblsum tbody").empty();
var len = response.length;
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var shopname = response[i].shopname;
var paymentmode = response[i].paymentmode;
var finalamount = response[i].finalamount;
if (finalamount==0){
return false
}
else if (paymentmode=="Credit"){
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='0'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
else{
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='" + finalamount + "'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
}
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
})
There is two problem if final amount is 0 then save button did not appear, when I submit form first field which is invoiceno don't submit on next page,
below is submit function
function summary(){
$(document).ready(function(e) {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
var form = $('#formsum').serialize();
$.ajax({
url: "test.php",
method: "POST",
data:
"&date=" +
date +
"&soid=" +
soid+
"&form=" +
form,
success: function(data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
}
})
})
}
Below is my PHP code.
for($count = 0; $count<count($_POST['invoiceno']); $count++){
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO ".$invoiceno." Amount ".$amount.'<br>';
}
sorry for bad english.

I told you before return STOPS executing a function, so all code after it is obsolete. In this case, when finalamount == 0 you stop executing the function and return to the place where it started. So the code to create the submit button never will be reached. With some proper indentation, you could see that:
$(document).ready(function() {
//<< ===== START START START of onclick function
$('#btnsummary').on('click', function() {
....
$.ajax({
url: "tblsum.php",
....
success: function(response) {
if ( response.length == 0 ) { .... }
else{
$("#tblsum tbody").empty();
....
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var finalamount = response[i].finalamount;
....
if (finalamount==0){
return false
// STOP EXECUTING THIS FUNCTION
// AND GO DIRECTLY TO END OF FUNCTION ================= >>
// code after this will NOT be executed
}
else if (paymentmode=="Credit"){....}
else{....}
}
// if finalamount == 0, this will never be executed
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
// ===== END END END of onclick function << ===============
// continue executing script from here
})
So you could use continue instead of return to skip only one itteration in the for loop.

Related

Couldn't Calculate Price and Qty on table using Php Ajax

I am creating a ecommerce site for my final year project.while I am creating a project I ran in to the problem with product shall be able add the card but when I view the card product shown which I added into the card.my problem is if the give qty it will auto calculation and display result on the total textbox.and final totel show display below. I attached image below what i tried so far. But couldn’t calculate the total and final total.
Display the Products
<script>
getProducts();
function getProducts() {
$.ajax({
type: 'GET',
url: 'all_cart.php',
dataType: 'JSON',
success: function(data) {
data.forEach(function(element) {
var id = element.id;
var product_name = element.product_name;
var price = element.price;
$('#mytable tbody').after
(
'<tr> ' +
'<td>' + id + '</td>' +
'<td>' + product_name + '</td>' +
'<td>' + price + '</td>' +
"<input type='hidden' name='price' value='" + price + "'>" +
'<td>' + "<input type = 'text' id='qty' name='qty'/>" + '</td>' +
'<td>' + "<input type = 'text' id='amount'/>" + '</td>' +
'</tr>');
});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
Auto calcaltion the price * qty
$(function() {
$("#price, #qty").on("keydown keyup click", qty);
function qty() {
var sum = (
Number($("#price").val()) * Number($("#qty").val())
);
$('#amount').val(sum);
console.log(sum);
}
});
You dont should append multiple elements with same ID in a page
Can you try
function getProducts() {
$.ajax({
...
$('#mytable tbody').after
(
'<tr> ' +
'<td>' + id + '</td>' +
'<td>' + product_name + '</td>' +
'<td>' + price + '</td>' +
"<input type='hidden' name='price' class='price' value='" + price + "'>" +
'<td>' + "<input type = 'text' class='qty' name='qty'/>" + '</td>' +
'<td>' + "<input type = 'text' class='amount'/>" + '</td>' +
'</tr>');
});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
$(function() {
$(".price, .qty").on("keydown keyup click", function () {
var price = $(this).parents('tr').find('.price');
var qty= $(this).parents('tr').find('.qty');
var sum = (
Number($(price).val()) * Number($(qty).val())
);
$(this).parents('tr').find('.amount').val(sum);
calculateAmount();
});
function calculateAmount() {
var total = 0;
$('.amount').each(function(e){
total += Number($(this).val());
});
$('#total-amount').text(total);
}
});
This is a demo: https://codepen.io/phuongnm153/pen/bymYOQ
When you get $("#price").val() and $("#qty").val() in jQuery but you have many $("#price") & $("#qty") duplicate. You should be run this in console.
I hope it's helpful for you

how to convert my result in table format

I am trying post my json result in table format how should achieve that.Igot result as
I want it to display in table format .Here is my code
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"> </script>
</head>
<body>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'example.php',
data: "",
dataType: 'json',
success: function(data)
{
var html = "";
for(var i = 0; i < data.length; i++){
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<b>uid: </b>"+uid+"<b> firstname: </b>"+firstname+"<b> lastname: </b>"+lastname+"<b> email: </b>"+email+"<b> username: </b>"+username+"<b> password: </b>"+password;
}
$("#output").html( html );
}
});
});
</script>
</body>
</html>
the output is stored in var html what should I need to convert it into table format.
Just change this part of code to format table instead just bold text:
...
var html = "<table>";
html += "<thead><tr><th>UID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Username</th><th>Password</th></tr></thead>";
html += "<tbody>";
for(var i = 0; i < data.length; i++){
html += "<tr>";
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<td>"+uid+"</td><td>"+firstname+"</td><td>"+lastname+"</td><td>"+email+"</td><td>"+username+"</td><td>"+password+"</td></tr>";
}
html +="</tbody></table>";
...
I hope that's what you mean.
Try:
var html = "<table>";
html += "<thead>";
html += "<tr>";
html += "<th>Uid</th>";
html += "<th>Firstname</th>";
html += "<th>Lastname</th>";
html += "<th>Email</th>";
html += "<th>Username</th>";
html += "<th>Password</th>";
html += "<tr>";
html += "</thead>";
html += "<tbody>";
for (var i = 0; i < data.length; i++) {
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<tr>";
html += "<td>" + uid + "</td>";
html += "<td>" + firstname + "</td>";
html += "<td>" + lastname + "</td>";
html += "<td>" + email + "</td>";
html += "<td>" + username + "</td>";
html += "<td>" + password + "</td>";
html += "</tr>";
}
html += "</tbody>";
$("#output").html(html);
You can either directly create the Table within Javascript or within the PHP Script that returns the JSON Data however since you didn't show us your PHP Script, we'd go the Javascript Route like so:
<script id="source" language="javascript" type="text/javascript">
$(function () {
$.ajax({
url : 'example.php',
data : "",
dataType: 'json',
success : function(data) {
var html = "<table class='data-tbl'>";
html += "<tr class='data-head-row'>";
html += "<th class='data-head-cell'>UID</th>";
html += "<th class='data-head-cell'>First Name</th>";
html += "<th class='data-head-cell'>Last Name</th>";
html += "<th class='data-head-cell'>Email</th>";
html += "<th class='data-head-cell'>Username</th>";
html += "<th class='data-head-cell'>Password</th>";
html += "</tr>";
html += "<tbody class='data-content-body'>";
for(var i = 0; i < data.length; i++){
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<tr class='data-content-row'>";
html += "<td class='data-content-cell'>" + uid + "</td>";
html += "<td class='data-content-cell'>" + firstname + "</td>";
html += "<td class='data-content-cell'>" + lastname + "</td>";
html += "<td class='data-content-cell'>" + email + "</td>";
html += "<td class='data-content-cell'>" + username + "</td>";
html += "<td class='data-content-cell'>" + password + "</td>";
html += "</tr>";
}
html += "</tbody>";
html += "</table>";
$("#output").html( html );
}
});
});
</script>

append result arrays in php codeigniter using ajax

The below is the json result I got in the console. But, appending it to my dropdown, shows only Physics,Chemistry and test subject. How to get Biology also.
[
[
{"id":"1","subject_name":"Physics"},
{"id":"2","subject_name":"Chemistry"},
{"id":"9","subject_name":"test subject"}
],
[
{"id":"7","subject_name":"Biology"}
]
]
Below is my ajax code
$.ajax({
type: 'POST',
dataType:"json",
// url:'<?php echo base_url()."SchoolAdmin/delete_electricUsage";?>',
url: '<?php echo base_url('SchoolAdmin/getclass_id'); ?>',
data: { class_std : class_std},
success: function (result) {
var listItems= "";
listItems+= "<option value='" + 'select' + "'>" +'Select' + "</option>";
for (var i = 0; i < result[0].length; i++){
listItems+= "<option value='" + result[0][i].id+ "'>" + result[0][i].subject_name + "</option>";
}
$("#subject").html(listItems);
}
});
Below is my controller function,
public function getclass_id()
{
$school_id = $this->session->userdata('school_id');
$sess_id = $this->session->userdata('userid');
$user_id = $this->session->userdata('user_id');
if(($sess_id))
{
$class_id=$this->security->xss_clean($this->input->post('class_std'));
$this->load->model('School_Model');
$cid=$this->School_Model->getclass_id($class_id,$school_id);
foreach ($cid as $r)
{
$rr=$r->id;
$data[]=array_merge($this->School_Model->getSubject($rr,$school_id));
}
echo json_encode($data);
}
else
{
redirect('admin');
}
}
Here is my model,
public function getclass_id($class_id,$school_id)
{
return $this->db->select('id')->from('class_table')->where('standard',$class_id)->where('school_id',$school_id)->
get()->result();
//echo $this->db->last_query();
}
public function getSubject($cid,$school_id)
{
return $this->db->select('id,subject_name')->
from('subject')->where('school_id',$school_id)->
where('class_id',$cid)->get()->result_array();
}
Your result is an array of arrays. You need to loop everything!
Biology is in result[1], but you're only looping result[0]
You could do it manually, like this:
for (var i = 0; i < result[0].length; i++){
listItems+= "<option value='" + result[0][i].id+ "'>" + result[0][i].subject_name + "</option>";
}
for (var i = 0; i < result[1].length; i++){
listItems+= "<option value='" + result[1][i].id+ "'>" + result[1][i].subject_name + "</option>";
}
Or, in one go:
for (var j = 0; j < result.length; j++){
// loops through all result arrays;
for (var i = 0; i < result[j].length; i++){
// loops the `j`th result for entries;
listItems+= "<option value='" + result[j][i].id+ "'>" + result[j][i].subject_name + "</option>";
}
}

How can I loop all json data and insert into my HTML?

I'd like to insert the Json data into my file.php. And so each group of them are insert into group of divs. (with the same style etc.)
I have a feeling the way I am using is not smart... better solutions are very welcome. Thanks guys.
$.ajax({
url: feedURL,
jsonpCallback: 'jsonpCallback',
contentType:"application/json",
dataType: 'jsonp',
success: function(json) {
for (var i=0; i < 15; i++) {
var date = new Date(json.posts.data[i].created_time);
var months = ["/01/", "/02/", "/03/", "/04/", "/05/", "/06/", "/07/",
"/08/", "/09/", "/10/", "/11/", "/12/"];
$("#description").html(json.posts.data[i].message);
$("#caption").html(json.posts.data[i].caption);
$("#expire_date").html(date.getDate() + months[date.getMonth()] + date.getFullYear());
$("#fb_link").html(
'<a href="' + json.posts.data[i].link + '">'
+ 'Total Like: ' + json.posts.data[i].likes.summary.total_count
+ ' Total Share: ' + json.posts.data[i].shares.count
+ ' View on Facebook' + '</a>'
);
$("#profile_img").html('<img src="' + json.picture.data.url + '">');
$("#profile_name").html(json.name);
$("#full_fb_photo").html('<img src="' + json.posts.data[i].full_picture + '">');
}
},
error: function(e) {
console.log(e.message);
}
});
You can write your code in flowing way. Uncountable date print in your loop. If I know your data format, I will give you exact way.
Try this code.
for (var prop in json.posts.data) {
$("#description").html(json.posts.data[prop].message);
// other same as
}
Thanks guys, i have figured out in this way.
$.ajax({
url: feedURL,
jsonpCallback: 'jsonpCallback',
contentType:"application/json",
dataType: 'jsonp',
success: function(json) {
var social_list = "";
for (i=0; i < 15; i++) {
var date = new Date(json.posts.data[i].created_time);
var months = ["/01/", "/02/", "/03/", "/04/", "/05/", "/06/", "/07/",
"/08/", "/09/", "/10/", "/11/", "/12/"];
social_list += "<div class='social_item'><div class='item'><div class='heading'>";
social_list += "<img src='" + json.picture.data.url + "'/><span>" + json.name + "</span><i class='fa fa-facebook'></i></div>";
social_list += "<div class='content'><p>Created on" + date.getDate() + months[date.getMonth()] + date.getFullYear() + "</p>";
social_list += "<div><img src='" + json.posts.data[i].full_picture + "' /></div>";
social_list += "<p name=" + i + ">" + json.posts.data[i].message + "</p>";
social_list += "<div><a href='" + json.posts.data[i].link + "'> Total Likes: " + json.posts.data[i].likes.summary.total_count + "Total Share: " + json.posts.data[i].shares.count + " View on Facebook </a></div>";
social_list += "</div></div></div>"
}
$('#social_list').html(social_list);

Validating array of inputs using javascript

I hav a rather large form it has 8 fields for entering books .
Now for user to add more books there is a button add more books ,on click of which a javascript function is called and 7 out of 8 fields are duplicated.
User can add maximum 6 books , and all the input fields created dynamically have their names as arrays . I am able to post them and store in a table , Now i want to validate them using javascript.
I have been tryng to do this since a week and am a new to Javascript . Please help me.
MY JAVASCRIPT CODE
function addInput(divName){
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit)
{
alert("You have reached the limit of adding " + counter + " inputs");
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML ="<table>"+ "<tr align='right'>" + "<td>"+ " Name of book" + (counter + 1) + " " +" : <input type='text' name='bname1[]' > "+"</td>" + "</tr>"+"<tr align='right'>"+ "<td>"+" Name of Authour"+(counter + 1)+" "+": <input type='text' name='aname1[]'>"+"</td>"+"</tr>"+"<tr align='right'>"+"<td>"+"Publisher"+(counter+1)+" "+": <input tyme='text' name='pub1[]'>"+"</td>"+"</tr>"+ "<tr align='right'>" +"<td>"+ "ISDN Number " + (counter + 1) +" "+ ": <input type='text' name='isdn1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" +"<td>"+ " Edition " + (counter + 1) + " "+": <input type='text' name='edi1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" + "<td>"+ "Price"+(counter + 1) +" "+ " :<input type='number' name='cost1[]'>"+"</td>"+"</tr>"+"<tr align='right'>" + "<td>"+ "Number of copies"+(counter + 1) +" "+ ": <input type='number' name ='num1[]'> "+"</td>" + "</tr>"+ "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter=counter+1;
}
}
there is divsion in the html form to which all this is added.
Please help !
thanx in advance ..
here is your solution. http://codebins.com/codes/home/4ldqpbq
HTML
<div id="testDiv">
</div>
<button onclick="addInput('testDiv')">
Add New Items
</button>
<button onclick="validate('testDiv')">
Validate
</button>
JavaScript
var counter = 0;
var limit = 6
function addInput(divName) {
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<table>" + "<tr align='right'>" + "<td>" + " Name of book" + (counter + 1) + " " + " : <input type='text' name='bname1[]' > " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Name of Authour" + (counter + 1) + " " + ": <input type='text' name='aname1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Publisher" + (counter + 1) + " " + ": <input tyme='text' name='pub1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "ISDN Number " + (counter + 1) + " " + ": <input type='text' name='isdn1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Edition " + (counter + 1) + " " + ": <input type='text' name='edi1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Price" + (counter + 1) + " " + " :<input type='number' name='cost1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Number of copies" + (counter + 1) + " " + ": <input type='number' name ='num1[]'> " + "</td>" + "</tr>" + "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter = counter + 1;
}
}
function validate(divName) {
var container = document.getElementById(divName).getElementsByTagName("input");
for (var len = container.length, i = 0; i < len; i++) {
// if only requried validation
if (container[i].value == "") {
container[i].style.borderColor = "red"
} else {
container[i].style.border = ""
}
//if you want saperate validation for each
switch (container[i].name) {
case "bname1[]":
//validate according to filed
break;
case "aname1[]":
//validate according to filed
break;
case "pub1[]":
//validate according to filed
break;
case "isdn1[]":
//validate according to filed
break;
case "edi1[]":
//validate according to filed
break;
case "cost1[]":
//validate according to filed
break;
case "num1[]":
//validate according to filed
break;
}
}
}
Couple of suggestions for you to consider:
1) consider grouping ALL the fields you want to duplicate inside a single div in your form.
Then when the user wants to add new item (book) all you will need to do will be copy the content of this div. This way you will maintain only one copy of field-set.
2) consider dynamic generic form validation too. You add the validation rules to your form field definition with extra attributes i.e. [<input ... validationRules="mandatory,minimumLength=10..." />] I think that you can achieve something similar with JQuery, but I personally prefer NOT to use large libraries to do small jobs.
3) consider giving your fields unique ids too.
use
var bname= document.getElementsByName('bname1[]');
var aname=document.getElementsByName('aname1[]'); .........
for(var i=0;i<bname.length;i++)
{
//Your validations
}
for(var i=0;i<aname.length;i++)
{
//Your validations
}.....
..
do this for all elements in your code..
Validation function example:
function validate_field(f) { // f is input element
var name = f.name; // or also f.getAttribute('name')
var value = f.value; // or also f.getAttribute('value'), but should be defined
var error_div = document.getElementById(name+'err');
//alert('name '+name+' value '+value);
if (name.indexOf('bname') == 0) { // if validate book name
if (value == '') { // e.g. book name should not be empty string?
error_div.innerHTML = 'book name cannot be empty!';
return false; // field is wrong
}
}
else if (name.indexOf('aname') == 0) { // if validate author name
if (value.length<2) {
error_div.innerHTML = 'author\'s name is too short!';
return false; // at least two characters long name? :)
}
}
else if (name.indexOf('pub') == 0) { // if validate publisher
if (value.length<2) {
error_div.innerHTML = 'publisher\'s name is too short!';
return false;
}
}
else if (name.indexOf('isdn') == 0) { // if validate ISDN Number
if (value == '') {
error_div.innerHTML = 'ISDN cannot be empty!';
return false;
}
}
else if (name.indexOf('edi') == 0) { // if validate Edition
if (value == '') {
error_div.innerHTML = 'edition cannot be empty!';
return false;
}
}
else if (name.indexOf('cost') == 0) { // if validate Price
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please write a price using digits!';
return false;
}
}
else if (name.indexOf('num') == 0) { // if validate Number of copies
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please number of copies via digits!';
return false;
}
}
error_div.innerHTML = 'ok';
return true; // field is ok
// you can also have a look at http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
}
Full working script here: pastebin.com/UkVP2uLb

Categories