data coming back but not able to post in jquery ajax - javascript

For the life of me I can not see why this is happening.
Basically I am using the following code to bring back table rows from the database.
var getCposInputs = {
'type': 'viewcpos',
'quoteid': '<?php echo $_GET['id']; ?>'
};
$.ajax({
type: 'POST',
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
data: getCposInputs,
dataType: 'html',
encode: true
}).done(function(data){
//$('body').html(data);
buildcotable += data;
});
So as you can see there is commented out line that when removed shows the details straight into the body instead of the variable which is later sent out using the .html() function within JavaScript.
So the full jQuery code is:
var buildcotable = '';
var buildtrs = $('#formentry15').val();
var coArray = '';
var coArrayNumber = 1;
buildcotable += '<div class="table-responsive">';
buildcotable += '<table class="table table-bordered">';
buildcotable += '<thead>';
buildcotable += '<th class="text-center">Number</th>';
buildcotable += '<th class="text-center">Price</th>';
buildcotable += '<th class="text-center">Installments</th>';
buildcotable += '<th class="text-center">Contact Initials</th>';
buildcotable += '<th class="text-center">Options</th>';
buildcotable += '</thead>';
buildcotable += '<tbody id="jquerypotable">';
//lets do a check and see how many are listed
if(buildtrs != 'TBC'){
var getCposInputs = {
'type': 'viewcpos',
'quoteid': '<?php echo $_GET['id']; ?>'
};
$.ajax({
type: 'POST',
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
data: getCposInputs,
dataType: 'html',
encode: true
}).done(function(data){
$('body').html(data);
buildcotable += data;
});
} else {
buildcotable += '<tr id="jqueryporow1">';
buildcotable += '<td><input type="hidden" value="No" id="jqueryponumber1" class="form-control">No CPO\'s have been submitted</td>';
buildcotable += '<td><input type="hidden" value="" id="jquerypovalue1" class="form-control"></td>';
buildcotable += '<td class="text-center"><input type="hidden" value="" id="jquerypoinstallments1" class="form-control"></td>';
buildcotable += '<td><input type="hidden" value="" id="jquerypocontactinitials1" class="form-control"></td>';
buildcotable += '<td class="text-center"> </td>';
buildcotable += '</tr>';
}
buildcotable += '</tbody>';
buildcotable += '</table>';
buildcotable += '<p>Add New CPO Number</p>';
buildcotable += '<p>Done</p>';
buildcotable += '</div>';
$('.ubl-section-7').html(buildcotable);
I know that the data is coming back fine, because when I remove the comment for $('body').html(data); then it shows the information.
But if trying to put it into a variable it simply does nothing.
Any ideas on why this is happening?
Thanks

You have to make sure that the output is generated after the ajax request retrieved its data. Else your last line of code is run even before the buildcotable += data; has been executed, because the ajax request isn't ready yet (it's asynchronous). Try something like this:
var buildcotable_beg = '<table><tr> ...';
var buildcotable_cnt = '';
var buildcotable_end = '...</table>';
var full_bld_tbl = '';
if (buildtrs != 'TBC') {
$.ajax(...).done(function(buildcotable_cnt) {
full_bld_tbl = buildcotable_beg + buildcotable_cnt + buildcotable_end;
$('.ubl-section-7').html(full_bld_tbl);
});
} else {
buildcotable_cnt = '<tr>...</tr>';
full_bld_tbl = buildcotable_beg + buildcotable_cnt + buildcotable_end;
$('.ubl-section-7').html(full_bld_tbl);
}

Related

Downloading CSV contents via Ajax and PHP

I am trying to download CSV contents via PHP script hosted on the server.
This is the jquery code that executes and creates a table:
$(document).ready(function() {
$("#btnSubmit").click(function(){
$.ajax({
type: 'GET',
url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
data: null,
success: function(text) {
var fields = text.split(/\n/);
fields.pop(fields.length-1);
var headers = fields[0].split(','),
html = '<table>';
html += '<tr>';
for(var i = 0; i < headers.length; i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for(var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
Contents of get-csv.php file:
<?php
header('Content-Type: text/plain');
$csv = file_get_contents('http://mydomaincom/wp-content/uploads/csv-samples.csv');
echo $csv;
?>
Here is the code for button:
<!-- Begin Button -->
<div class="demo">
<input id = "btnSubmit" type="submit" value="Get It"/>
</div>
<!-- End Button -->
From browser:
I can access http://mydomaincom/wp-content/uploads/get-csv.php - no issues
I can access http://mysitecom/wp-content/uploads/csv-samples.csv - no issues
When I click on button nothing happens.
Thanks
Below I tried to put together a working snippet where you can possibly see how it works when it works ...
$(document).ready(function () {
$("#btnSubmit").click(function () {
$.ajax({
type: 'GET',
// url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
// url: 'https://jsonplaceholder.typicode.com/users', // --> JSON
url: "https://data.cdc.gov/api/views/45um-c62r/rows.csv",
data: null,
success: function (text) {
var fields = text.split(/\n/);
fields.pop(fields.length - 1);
var headers = fields[0].split(','), html = '<table>';
html += '<tr>';
for (var i = 0; i < (headers.length,3); i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for (var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmit">get data</button>
After looking around a bit further I did actually find some publicly available CSV data ("Rates of TBI-related Emergency Department Visits, Hospitalizations, and Deaths - United States, 2001 – 2010" from the U.S. Department of Health & Human Services) and I am now using that to demonstrate the AJAX process.
So, your code basically works. It could be simplified of course but that is not the point. I guess that the problems you encounter with your site are probably CORS-related.

JS: Live search not working with spaces between two query

performing this search operation on JSON data, it works show filter data when enter term in search bar but it works only with one term as soon as I add space and other term it shows nothing, what am I doing wrong? Also it takes time to filter data around 14000 records are in JSON file
$(document).ready(function() {
$('#selectterm').change(function() {
var sterm = $(this).val();
$.ajax({
type: "GET",
url: "/fee/get/" + sterm,
success: function(res) {
if (res) {
$('#txt-search').keyup(function() {
var searchField = $(this).val();
if (searchField === '') {
$('#filter-records').html('');
return;
}
var output = '<div class="row">';
var count = 1;
$.each(res, function(key, lol) {
if ((lol.strm.toLowerCase().indexOf(searchField.toLowerCase()) != -1) ||
(lol.subject_cd.toLowerCase().indexOf(searchField.toLowerCase()) != -1) ||
(lol.catalog_nbr.toLowerCase().indexOf(searchField.toLowerCase()) != -1)) {
output += '<table class="table">';
output += '<thead>';
output += '<tr>';
output += '<th scope="col">Term</th>';
output += '<th scope="col">Subject</th>';
output += '<th scope="col">Catlog Nbr</th>';
output += '</tr>';
output += '</thead>';
output += '<tbody>';
output += '<tr>';
output += '<td>' + lol.strm + '</td>';
output += '<td>' + lol.subject_cd + '</td>';
output += '<td>' + lol.catalog_nbr + '</td>';
output += '</tr>';
output += '</tbody>';
output += '</table>';
if (count % 2 == 0) {
output += '</div><div class="row">'
}
count++;
}
});
output += '</div>';
$('#filter-records').html(output);
});
}
}
});
});
});

Adding Parameter to Javascript AJAX

this is my simple hardcoded version.
$(document).ready(function(){
$.support.cors = true;
var this_id = '123456789123456';
$.ajax({
url: 'https://thisservice/delivery/'+this_id,
type: "get",
dataType: "json",
data: { },
success: function(response){
console.log(response);
var html = '';
html += '<tr>';
html += '<th>Customer Name: </th><td>'+response.custName+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line1:</th><td>'+response.addrLine1+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line2:</th><td>'+response.addrLine2+'</td>';
html += '</tr>';
html += '<th>Address Line3:</th><td>'+response.addrLine3+'</td>';
html += '</tr>';
html += '<th>Address Line4:</th><td>'+response.addrLine4+'</td>';
html += '</tr>';
html += '<th>Address Line5:</th><td>'+response.addrLine5+'</td>';
html += '</tr>';
html += '<th>Address Line6:</th><td>'+response.addrLine6+'</td>';
html += '</tr>';
html += '<th>Customer PostCode:</th><td>'+response.custPostCode+'</td>';
html += '</tr>';
$('#theDelivery').append(html);
}
})});
the code above works perfectly fine, however im now working to make this_id as a url parameter, so when the webpage is called along with a valid 16th digit number as a substring, it will return the contents of the objects that i am trying to access from this webservice.
How exactly is it done? i have attempted to do this in the code below, but no luck.
<script type="text/javascript">
function getthisId(this_id){
$.support.cors = true;
$.ajax({
type: "get",
url: 'https://thisservice/delivery/'+this_id,
dataType: "json",
cache: false,
data: { this_id },
success: function (response) {
console.log(response);
var html = '';
html += '<tr>';
html += '<th>Customer Name: </th><td>'+response.custName+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line1:</th><td>'+response.addrLine1+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line2:</th><td>'+response.addrLine2+'</td>';
html += '</tr>';
html += '<th>Address Line3:</th><td>'+response.addrLine3+'</td>';
html += '</tr>';
html += '<th>Address Line4:</th><td>'+response.addrLine4+'</td>';
html += '</tr>';
html += '<th>Address Line5:</th><td>'+response.addrLine5+'</td>';
html += '</tr>';
html += '<th>Address Line6:</th><td>'+response.addrLine6+'</td>';
html += '</tr>';
html += '<th>Customer PostCode:</th><td>'+response.custPostCode+'</td>';
html += '</tr>';
$('#theDelivery').append(html);
}
});
}
$(document).ready(function () {
getthisId(this_id);
});
this error occurs:
Uncaught ReferenceError: this_id is not defined
at HTMLDocument.<anonymous> (1032987988503654:59)
at i (jquery-1.12.3.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.12.3.min.js:2)
at Function.ready (jquery-1.12.3.min.js:2)
at HTMLDocument.K (jquery-1.12.3.min.js:2)
im very new to this, any help would be great :)
The server side is expecting the value in a parameter named parcel_id, so you need to provide that as the key in the object you provide to data, like this:
data: { parcel_id: this_id },
you should do like this
'https://thisservice/delivery/?id='+this_id

Removing & Updating Table Rows Using jQuery

I am a novice when it comes to jQuery so please bear with me a little and I apologies for my poor coding in advance.
The logic to my code is simple or at least that was the aim.
A jQuery script checks a type field and then gets its values and builds a table. That all works 100%.
The issue comes when deleting rows and then updating the table id's on the new appended rows that is generated by clicking on the new row button.
The new rows do not delete.
Here is the code but I have also created a jsfiddle so you can check it out live, but there are some bugs that are not there on the site - for instance you need to double click the button for some reason for it to work
JS:
$('.purchase-order-button').on('click', function(){
var buildcotable = '';
var buildtrs = $('#formentry15').val();
var coArray = '';
var coArrayNumber = 1;
buildcotable += '<div class="table-responsive">';
buildcotable += '<table class="table table-bordered">';
buildcotable += '<thead>';
buildcotable += '<th class="text-center">CO Number</th>';
buildcotable += '<th class="text-center">CO Price</th>';
buildcotable += '<th class="text-center">Options</th>';
buildcotable += '</thead>';
buildcotable += '<tbody id="jquerypotable">';
//lets do a check and see how many are listed
if(buildtrs.indexOf(',') !== -1){
coArray = buildtrs.split(',');
$.each(coArray, function(){
var splitCoArray = this.split('=');
var coArrayPrice = splitCoArray[1].trim().replace('£', '');
var coArrayCode = splitCoArray[0].trim();
buildcotable += '<tr id="jqueryporow'+coArrayNumber+'">';
buildcotable += '<td><input type="text" value="'+coArrayCode+'" id="jqueryponumber'+coArrayNumber+'" class="form-control"></td>';
buildcotable += '<td><input type="text" value="'+coArrayPrice+'" id="jquerypovalue'+coArrayNumber+'" class="form-control"></td>';
buildcotable += '<td class="text-center"><a class="btn btn-danger delete-co-row" id="deletepo'+coArrayNumber+'">Delete CO Number</a></td>';
buildcotable += '</tr>';
coArrayNumber += 1;
});
} else {
if(buildtrs == '' || buildtrs == 'TBC'){
buildcotable += '<tr id="jqueryporow1">';
buildcotable += '<td><input type="text" value="" id="jqueryponumber1" class="form-control"></td>';
buildcotable += '<td><input type="text" value="" id="jquerypovalue1" class="form-control"></td>';
buildcotable += '<td class="text-center"><a class="btn btn-danger delete-co-row" id="deletepo1">Delete CO Number</a></td>';
buildcotable += '</tr>';
} else {
var splitSingleCoArray = buildtrs.split('=');
var coSinglePrice = splitSingleCoArray[1].trim().replace('£', '');
var coSingleCode = splitSingleCoArray[0].trim();
buildcotable += '<tr id="jqueryporow1">';
buildcotable += '<td><input type="text" value="'+coSingleCode+'" id="jqueryponumber1" class="form-control"></td>';
buildcotable += '<td><input type="text" value="'+coSinglePrice+'" id="jquerypovalue1" class="form-control"></td>';
buildcotable += '<td class="text-center"><a class="btn btn-danger delete-co-row" id="deletepo1">Delete CO Number</a></td>';
buildcotable += '</tr>';
}
}
buildcotable += '</tbody>';
buildcotable += '</table>';
buildcotable += '<p>Add New CO Number</p>';
buildcotable += '<p>Done</p>';
buildcotable += '</div>';
$('.ubl-section-7').html(buildcotable);
$('.ubl-section-7').show();
$('.model-background').fadeIn(500);
//add new row
$('#addnewpo').on('click', function(e){
e.preventDefault();
var numPoRows = $("#jquerypotable > tr").length;
var makeNewRowNum = numPoRows + 1;
var createnewporow = '<tr id="jqueryporow'+makeNewRowNum+'">';
createnewporow += '<td><input type="text" value="" id="jqueryponumber'+makeNewRowNum+'" class="form-control"></td>';
createnewporow += '<td><input type="text" value="" id="jquerypovalue'+makeNewRowNum+'" class="form-control"></td>';
createnewporow += '<td class="text-center"><a class="btn btn-danger delete-co-row-new" id="deletepo'+makeNewRowNum+'">Delete CO Number</a></td>';
createnewporow += '</tr>';
$('#jquerypotable').append(createnewporow);
});
//delete row
$('#jquerypotable > tr').on('click', '.delete-co-row', function(e){
e.preventDefault();
var getCoId = $(this).attr('id');
var coLastChar = parseInt(getCoId.substr(getCoId.length - 1));
var coHowManyRows = parseInt($("#jquerypotable > tr").length);
var makeMinusId = '';
var newi = coLastChar;
if(coLastChar == coHowManyRows){
$('#jqueryporow'+coLastChar).remove();
} else {
//before removing rows we need to rebuild the information given.
for(newi; newi <= coHowManyRows; newi++){
if(newi == coLastChar){
$('#jqueryporow'+newi).remove();
} else {
makeMinusId = (newi - 1);
$('#jqueryporow'+newi).attr('id', 'jqueryporow'+makeMinusId);
$('#jqueryponumber'+newi).attr('id', 'jqueryponumber'+makeMinusId);
$('#jquerypovalue'+newi).attr('id', 'jquerypovalue'+makeMinusId);
$('#deletepo'+newi).attr('id', 'deletepo'+makeMinusId);
}
}
}
});
});
enter link description here
Any help is gratefully received
You added an eventListener to the delete buttons at the initialization of the page but didnt do it again when creating the rows. I suggest adding the following code to your addnewpo button:
$('#addnewpo').on('click', function(e){
// your original code here
//...
//now add an event listener to the new deletebuttons
$('#jquerypotable > tr').on('click', '.delete-co-row-new', function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
});
I Found the issue, the issue was the listener needed to remove the tr.
so instead of:
/now add an event listener to the new deletebuttons
$('#jquerypotable > tr').on('click', '.delete-co-row', function(e){
It needed to be:
/now add an event listener to the new deletebuttons
$('#jquerypotable').on('click', '.delete-co-row', function(e){
Thanks everyone for trying to help :)

Jquery nested table creation clean approach

I have written below code which creates a table inside another table from json response.
Main Table Code
var user = '<table width="98%" cellspacing="0" cellpadding="1" style="text-align: left; margin: 0 auto;';
user += 'border-collapse: collapse;" >';
$.each(html.ListOfReportModelData, function (key, val) {
user += '<tr>';
user += '<td>';
user += '<table width="100%" id="internalTable" border="0" cellspacing="2px" cellpadding="2px" >';
if (flag == "false") {
user += '<tr class="GreenColor">';
user += '<td style="width: 15%" class="accord">';
user += 'PR Number';
user += '</td>';
user += '<td style="width: 10%" class="accord">';
user += 'Created On';
user += '</td>';
user += '<td style="width: 10%" class="accord">';
user += 'Site Name';
user += '</td>';
user += '<td style="width: 10%" class="accord">';
user += 'Order ID';
user += '</td>';
user += '<td style="width: 55%" class="accord">';
user += 'File Name';
user += '</td>';
user += '</tr>';
}
var count = 0;
$.each(val.Orders, function (key, child) {
//debugger;
user += '<tr class="PinkColor">';
if (count == 0) {
user += '<td valign="top" rowspan="' + val.Orders.length + '" style="width: 15%"><a href="javascript:GetFinanceData(' + "'" + val.SiteName + "','" + val.Req_Number + "'" + ');">';
user += val.Req_Number;
user += '</a></td>';
count = 1;
}
user += '<td valign="top" style="width: 10%">';
user += val.CreatedDateText;
user += '</td>';
user += '<td valign="top" style="width: 10%">';
user += val.SiteName;
user += '</td>';
user += '<td valign="top" style="width: 10%">';
user += child.OrderId;
user += '</td>';
user += '<td style="width: 55%;break-word: word-wrap;">';
if (child.ShowLink) {
user += '<a href="javascript:Export(' + "'" + child.ID + "','" + val.SiteName + "'" + ');">';
}
user += child.Attachments_FileName;
if (child.ShowLink) {
user += '</a>';
}
user += '</td>';
user += '</tr>';
});
user += '<tr class="PinkColor">';
user += '<td colspan="5"><div id="' + val.Req_Number + '" ></div>';
user += '</td>';
user += '</tr>';
user += '</table>';
user += '</td>';
user += '</tr>';
flag = "true";
});
user += '</table>';
Child Table Creation
$.getJSON("/Home/FinancialInformation", data, function (html) {
totalRecords = html.FinanceData.length;
if (totalRecords == 0) {
$('#' + Req_Number + '').empty();
alert('No Finance Data Available!!!!!');
}
else {
var Fin = '<table id=' + Req_Number + ' width="100%" border="0" cellpadding="2px" cellspacing="2px" >';
Fin += '<tr class="GreenColor">';
Fin += '<td class="accord" style="width: 45%">Approval Type</td>';
Fin += '<td class="accord" style="width: 10%">Approval Required</td>';
Fin += '<td class="accord" style="width: 15%">Approved By</td>';
Fin += '<td class="accord" style="width: 10%">Approved By 521</td>';
Fin += '<td class="accord" style="width: 20%">Approved Date</td>';
Fin += '</tr>';
$.each(html.FinanceData, function (key, val) {
Fin += '<tr class="PinkColor">';
Fin += '<td style="width: 45%">' + val.Approval_Type + '</td>';
Fin += '<td style="width: 10%">' + val.Approval_Required + '</td>';
Fin += '<td style="width: 15%">' + val.Approved_By + '</td>';
Fin += '<td style="width: 10%">' + val.Approved_By_521 + '</td>';
Fin += '<td style="width: 20%">' + val.Approved_Date + '</td>';
Fin += '</tr>';
});
Fin += '</table>';
$('#' + Req_Number + '').empty()
$('#' + Req_Number + '').append(Fin);
}
});
I can see my table created correctly but I see lot of cumbersome activity in creating these codes.Is there better approach to achieve the same thing?Mostly using some plugins.
How others have said you should use a template engine like : handlebarsJS, mustacheJS, underscoreJS or maybe something like reactJS
Or if you want to keep it with jQuery, you can structure your code like :
Instead of injecting html directly like that, you can use jQuery syntax to create each element
You can split logic with functions
You can use only CSS classes(no style) and add it with jQuery
Here it's an example :
var getParentTable = function() {
// add style to CLASS in CSS
return $('<table></table>').addClass('parentTableClass');
};
var getInternalTable = function() {
return $('<table></table>')
.addClass('childTableClass')
.attr('id', 'internalTable');
};
var getRow = function(classValue) {
return $('<tr></tr>').addClass(classValue);
};
var getCol = function(textValue, classValue) {
return $('<td></td>')
.addClass(classValue)
.text(textValue);
};
var parentTable = getParentTable();
parentTable.append(internalTable);
$.each(html.ListOfReportModelData, function (key, val) {
var internalTable = getInternalTable();
var simpleRow = getRow();
var simpleCol = getCol();
var row1 = getRow('GreenColor');
var row3 = getRow('PinkColor');
row1
.append(getCol('PR Number', 'td1 accord'))
.append(getCol('Created On', 'td2 accord'))
.append(getCol('Site Name', 'td3 accord'))
.append(getCol('Order ID', 'td4 accord'))
.append(getCol('File Name', 'td5 accord'));
internalTable.append(row1);
$.each(val.Orders, function (key, child) {
var row2 = getRow('PinkColor');
.append(getCol(val.Req_Number, 'td1 accord'))
.append(getCol(val.CreatedDateText, 'td2 accord'))
.append(getCol(val.SiteName, 'td3 accord'))
.append(getCol(child.OrderId, 'td4 accord'))
.append(getCol(child.ShowLink, 'td5 accord'));
internalTable.append(row2);
});
internalTable.append(row3);
simpleCol.append(internalTable);
simpleRow.append(simpleCol);
parentTable.append(simpleRow);
});

Categories

Resources