Tried to load table dynamically using AJAX but rows not displayed - javascript

In a form, i have a dropdownlist and a textbox which will get user's input. Then when the user submits the form, i don't want the whole page to refresh. i only wanted the table which is just below it to refresh and load data from database. I tried code below but only alert pops up. The table is still empty.
$('#frmPrescDrugList').submit(function (e) {
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: '/consultation/PrescDrugList',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html',
success: function (data) {
var row_data = "";
row_data += "#{ var rowNum = 0; } #foreach (var item in Model.LoadDrugList) {
rowNum += 1;
<tr Class="odd gradeX">
<td>#rowNum</td>
<td>#item.dsubsystem</td>
<td>#item.tradename </td>
<td style="text-align: center; vertical-align: middle;"><form Class="form-horizontal" role="form" action="#Url.Action("Prescription", "consultation", new {dgid = item.dgid})" method="post"><Button type="submit" Class="btn btn-default" name="btnDrugListSelect">Select</Button></form></td>
</tr>
}";
$("#LoadDrugListTable").append(row_data);
alert('Drug list has been loaded.');
},
error: function () {
alert('Ajax Submit Failed ...');
}
}); // end ajax
}); // end form-submit
LoadDrugListTable is the table's id. Why didn't it load the data when the ajax is already successful? Can anyone please help point out my mistake or suggest me a better example reference?
I tried following this example, but i'm stuck at the #Url.Action(). Its underlined red. And when i try to separate them by "" and + it's still underlined red saying
Too many characters in character literal.
UPDATED
This is the form i mentioned that doesn't pass the id properly. I'm passing it to a get method. By the way, this is an entirely different page than the one i mentioned above. When i try to do the same thing in another page, it passes a null paid value. Paid is the id. Maybe because this time i'm passing to another page.
"<td style='text-align: center; vertical-align: middle;'><form Class='form-horizontal' role='form' action='#Url.Action("PatientMedicalInfo", "consultation", new { paid = Html.Raw(" + data[i].paid + ") }) method='get'><Button Class='btn btn-default' name='btnSelectPatient' id='btnSelectPatient'>Select</Button></form></td>"
This is the controller:
[HttpGet()]
public ActionResult PatientMedicalInfo(string paid)
{
PatientLookupVM Patient = new PatientLookupVM();
dynamic CurrentPatientDetailsByPtId = Patient.GetCurrentPatientDetailsByPtId(paid);
Patient.LoadCurrentPatientDetails = CurrentPatientDetailsByPtId;
return View(Patient);
}

Try replacing double " quotes with single ' quotes in action.
Well for consistency you could replace them everywhere.
<td ... action='#Url.Action("Prescription", "consultation", new {dgid = item.dgid})' ... </td>

Related

Laravel blade condition in ajax

I have my data returning by ajax into table in blade but i need a filter in my returned data.
Example
If I use blade loop I can use #if ($loop->last) in order to make special changes for my last record, but since my data is returning by ajax (JSON) I'm not sure how to do that.
Code
Commented the part i need filter
$.ajax({
type:'GET',
url:'{{url('dashboard/getProjectReimburses')}}/'+projectID,
success:function(data){
$(data.data).each(function(_, i){
var number = i['amount'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
var row = `<tr data-id="${i.id}">'+
'<td>${i.created_at}</td>'+
'<td>${i.spent_date}</td>'+
'<td>${i.cost_name}</td>'+
'<td class="text-right">${nf.format(number)}</td>'+
'<td>${i.description}</td>'+
'<td>Attachments here</td>'+
'<td>${i.statusName}</td>'+
#role('employee|admin')
'<td>${i.statusDate}</td>'+
'<td>
// I need show this delete button only for latest row, for other rows just empty <td></td> //
<Form method="DELETE" id="organizationFormDel">
#csrf
#method('DELETE')
<button type="submit" data-id="${i.id}" class="btn btn-sm reimDelete btn-danger">Delete</button>
</form>
// I need show this delete button only for latest row, for other rows just empty <td></td> //
</td>'+
'</tr>`;
#else
'<td>status date here</td></tr>`;
#endrole
$('#visit_table2').append(row);
});
}
});
Any idea?
Update
Here is screenshot of my blade, I select 1 row from table 1, data shows in table 2
Now in table 2 as i marked it i want to show edit and delete button only for latest row other 3 rows empty <td>
You can use a partial view for ajax. For example when you will send an ajax request on the backend then you will use a partial blade file on the backend and there you can use if statement in blade file and you will return Html as response and then you will append that Html to DOM on success.
$html = view('partial-blade',['data'=> $data])->render();
return $html;
You have to make a view and set all html code there. after calling Ajax and render view
$view = view('blade',["data"=>$data,])->render();
return $view;
Solved
Well I manage to do it the way I wanted, thanks to comments but my problem wasn't in controller unfortunately I couldn't convince friends that what i need is handle my ajax data on success and not controller.
Anyway here is my solution which works perfectly for me :
$(data.data).each(function(_, i){
//.....
var ms = _ == data.data.length -1; //get latest row
if(ms == true){ // if is latest row
// show my tr's with action buttons
var row = `<tr data-id="${i.id}">'+
//....
} else {
// show mt tr's without buttons
var row = `<tr data-id="${i.id}">'+
//....
}
});
Thanks for all helps.

Reload specific Selection tag without reloading the whole page

I am trying to make a form page in adding new client in a database. The form consist of a selection tag that has options for adding house number. But there are circumstances like house number is not yet placed on the database, so I decided to create a button for adding new house no (using modals).
Form:
<div class="col-md-3 form-group" id="autoload">
<label>
Household: <a data-toggle="modal" data-target="#addHousehold"
style="cursor: pointer; text-decoration: none;">
<i class="fa fa-plus" >Add</i></a>
</label>
<select class="form-control select2" style="width: 100%;">
<option selected="selected">Select Household</option>
<?php foreach($result3 as $row): ?>
<option><?=$row['house_no']?></option>
<?php endforeach ?>
</select>
</div>
Script for adding new house number, and refresh the selection when new house number is successfully added:
$('#addHouseholder').click(function(){
var householder = $('.householder').val()
var street = $('.strsel1').val();
$.ajax({
method: "POST",
url: "insert.php",
data: {householder:householder,street1:street}
}).then(()=>{
$("#autoload").load(" #autoload");
alert('Household Added')
})
This function successfully, the only problem is the division of the selection is deformed. I also forgot to say that I reload the div, but I wonder if it is possible to just reload the selection. I am not sure how to execute this. Looking forward for your help. Thank you very much!
Are you using select2 (https://select2.org/)?
If so, you can use the ability to programmatic control the select.
https://select2.org/programmatic-control/add-select-clear-items
By using:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
You could return the option in the ajax response and populate the select.
You just need to echo json format of your data in insert.php file then modify your js script to
$.ajax({
type: "POST",
url: "path/insert.php",
data: {householder:householder,street1:street},
success: function(data){
// Parse the returned json data
var opts = $.parseJSON(data);
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
// You will need to alter the below to get the right values from your json object. Guessing that d.no / d.anyOtherInfo are columns in your data
$('#autoload').children(".orm-control.select2").append('<option value="' + d.no + '">' + d.anyOtherInfo + '</option>');
});
}
});
Good luck.
Edit 1: adding source.
check Populate Select box options on click with Javascript/Jquery with Json data

Table not getting displayed on a button click in AngularJS

Hi I'm learning AngularJS and I have a question. I want to display a table on a button click. On clicking the button, JSON data gets fetched but I have to press the button twice for the data to be displayed.
This is the HTML page.
<html>
<body>
<div class="container">
<label for="tags" style="margin-top: 30px;margin-left: 15px;">GSTIN </label>
<input id="tags">
<button ng-click="searchfunction()">search</button>
</div>
<br/>
<hr>
<div class="container">
<div ng-show="tshow" ng-repeat="x in searchdata">
<table class="table table-bordered table-responsive">
<thead>
<tr>
<th>MON</th>
<th>SGST</th>
<th>CGST</th>
<th>IGST</th>
<th>CESS</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in x">
<td>{{i.mon}}</td>
<td>{{i.sgst}}</td>
<td>{{i.cgst}}</td>
<td>{{i.igst}}</td>
<td>{{i.cess}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
This is the controller:
app.controller("searchcontroller", function ($scope,$http) {
$scope.tshow=false;
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$scope.searchfunction=function() {
$scope.tshow=true;
var tf=document.getElementById("tags");
var value=tf.value;
var auth = make_base_auth("gstadmn112","Gstn#123");
var url6 = "http://164.100.148.67:8080/wsgstr3B/rest/payment/gstinsearch?gstin="+value+"&year=201718";
xml = new XMLHttpRequest();
// jQuery
$.ajax({
url : url6,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
},
success:function(response) {
console.log(response);
scope.searchdata=response;
},
failure:function() {
window.alert("wrong input data doesn't exist");
}
});
}
});
I need to click twice on the search button for the table to be displayed. I want the table to be hidden initially and once the search is successful the table should be displayed. The table is hidden initially and after clicking twice correct data gets displayed.
Maybe, you try to add $scope.tshow=true; in function success:
success:function(response) {
console.log(response);
$scope.tshow=true;
$scope.searchdata=response;
},
P.S. I advise to use $http instead of $ajax.
This problem is related to the digest loop of angularjs which keeps all changes sync between your view and controller.
When you invoke the searchfunction(), angularjs will know whats happening inside the method and sync the changes made with the view when its completed.
The problem is that your method uses $.ajax which has some async callback methods.
When these methods gets invoked angularjs have already left the party (digest loops is over) and don't know what these methods have done to your controller $scope.
The jQuery success callback will however set the $scope.searchdata=response; and this change gets notified the next time angularjs is in the party (the next time you click).
So basically you need to make sure angularjs is aware of the async methods which makes changes to your $scope.
To solve this I would inject angularjs own $http service (which takes care of async changes to the scope) and use that instead.
var req = {
method: 'GET',
url: url6,
headers: {
'Authorization': auth
}
}
$http(req).then(function(response){
console.log(response);
$scope.searchdata=response;
}, function(){
window.alert("wrong input data doesn't exist");
});
You can use this way.
$scope.searchfunction=function(){
$scope.tshow=true;
var tf=document.getElementById("tags");
var value=tf.value;
$http.get("http://164.100.148.67:8080/wsgstr3B/rest/payment/gstinsearch?gstin="+value+"&year=201718")
.success(function(result) {
$scope.searchdata=response;
$scope.tshow=false;
})
.error(function() {
window.alert("wrong input data doesn't exist");
});
}

Create Array from HTML to send via AJAX

Im having a unusually hard time with this. If I have form that looks like this
HTML
<form id='logForm' method='post' action='seatingProcess.php'>
<span class='close' style='display:none' id='255' desk='9-4' deskval='2-3' changeType='REMOVE'></span>
<span class='close' style='display:none' id='255' desk='7-4' deskval='5-3' changeType='ADD'></span>
<span class='close' style='display:none' id='255' desk='8-4' deskval='8-3' changeType='CHANGE'></span>
<div class='btn btn-primary' type='submit' id='submit'>Submit</div>
</form>
What I want to happen is, when i click the button to submit the form, I want to have an array of the different elements in the span created so it can be sent via AJAX to process in PHP. How do you recommend I do this?
Also, this information will be dynamically created in this form based on user action. They will all be span's but will contain more or less the same attributes with a value attached to them. The idea is for php to receive the arrays and depending on what the attribute "changeType" says, it will generate the SQL script to perform that action. I may need help with this as well.
All I have for javascript. I dont have anything about making the array, thats what I need help with.The HTML above is an example output, but ill post one of the functions that generates the information. :
Javascript
function remDeskId(){
userObject = $dropObject.find('div.dragTest');
userObjectChange = 'REMOVESEAT';
userObjectID = userObject.attr('data-info');
userObjectDeskID = userObject.attr('data-id');
userObjectDeskIDVal = 0;
$('form#logForm').append("<span class='close' style='display:none' id='"+userObjectID+"' desk='"+userObjectDeskID+"' deskval='"+userObjectDeskIDVal+"' changeType='"+userObjectChange+"'></span>");
userObject.attr({"data-id":""}); //remove desk number for new user location
userObject.appendTo('#userPool');
}
$('#submit').click(function(){
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
//var formData = {
// };
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'seatingProcess.php', // the url where we want to POST
data : $('#logForm').serialize(), // our data object
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Thanks in advance
You can iterate through the spans and create an array.
var spans = $('#logForm span');
var data = [];
$.each(spans, function(i, item){
var newItem = {};
newItem.id = $(item).attr('id');
newItem.desk = $(item).attr('desk');
newItem.deskval = $(item).attr('deskval');
newItem.changeType = $(item).attr('changeType');
data.push(newItem);
});

Ajax POSTS not updating screen content

So I have a "scenario", made up of lots of "forms" which contain lots of "events" and "data" etc. To populate all this information I have this in the page to run once the page is finished
$(document).ready(function() {
var scenarioID = ${testScenarioInstance.id}
var myData = ${results as JSON}
populateFormData(myData, scenarioID);
});
This then calls the functions below (the first calls the second, done like this as I had an issue where as it was ajax the variables in the loop were updating before things were being appended and so everything ended up in the last sub table): -
function populateFormData(results, scenarioID) {
$table = $('#formList')
for ( var i in results) {
var formIDX = (results[i]["forms_idx"])
var formID = (results[i]["form_id"])
appendSubTable(formIDX, scenarioID, $table, formID);
}
}
function appendSubTable(formIDX, scenarioID, $table, formID) {
var url = "http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
$subTable.append(data)
}).fail(function() {
alert("it failed!")
});
}
This then goes off grabs the data from the controller like so..
def ajaxPopulateSubTables(int formIDX, int scenarioID, int formID) {
def db = new Sql(dataSource)
String mySQL = "Loads of SQL STUFF"
def subTableResults = db.rows(mySQL)
render(template: "subTableEntry", model: [subTableResults:subTableResults, formID:formID, formIDX:formIDX])
}
and fires it at the gsp:
<colgroup>
<col width="150"/>
<col width="350"/>
<col width="350"/>
<col width="350"/>
</colgroup>
<g:if test="${subTableResults != null && !subTableResults.isEmpty()}">
<tr>
<th>eventIDX</th>
<th>eventID </th>
<th>objID</th>
<th>testVal</th>
</tr>
</g:if>
<g:each in="${subTableResults}" status = "i" var="item">
<tr id = ${i} class="${((i) % 2) == 0 ? 'even' : 'odd'}" name="main">
<td>${item.events_idx}</td>
<td>${item.type}</td>
<td>${item.object_description}</td>
<td><g:textField id = "testData[${formIDX}:${formID}:${i}]" name="testData[${formIDX}:${formID}:${i}]" value="${item.value}" optionKey="id" /></td>
</tr>
</g:each>
Before then jamming it into the relevant sub table.
The problem is, sometime when I load up a page not all the sub tables are filled out, but if I hit F5 to refresh the page this then seems to fix the issue... Although not always, sometimes I then get a different section not refreshing :(
I put a println into the controller to see if all the SQLs were being fired off but it always returns all the individual form SQL strings fine...
Looking in firebug all the POSTs are coming back fine but the page just isn't updating...
Any suggestions or ideas as to what might be causing this would be appreciated, I'm at a loss..
I also tried updating my appendSubTable function where the post is to include a fail in case something was failing, but this isn't hit either, have updated code above to show this
Oddly I altered the post function slightly to the below, moving the finding of the table to the beginning of the function rather than within the post itself and that seems to have done the trick, although why I'm not sure... Whether someone can explain why this is or not I'd be interested to know why!
function appendSubTable(formIDX, scenarioID, $table, formID) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url = "http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
$subTable.append(data)
}).fail(function() {
alert("fail")
});
}

Categories