I want to bind my multiselect with ajax but after ajax call items does not show.I try rebuild or refresh multiselect but it still does not show
<script type="text/javascript">
$(document).ready(function () {
var categCheck = $('#multiselect').multiselect({
includeSelectAllOption: true,
enableFiltering: true
});
$.ajax({
type: 'GET',
url: "#Url.Content("~/Home/Listpositions/")",
success: function (data) {
$.each(data.data, function (index, item) {
alert(item.PositionName);
var opt = $('<option />', {
value: item.PID,
text: item.PositionName
});
opt.appendTo(categCheck);
});
}
});
$('#multiselect').multiselect('rebuild');
categCheck.multiselect('rebuild');
categCheck.multiselect('refresh');
$("select.multiselect").multiselect("refresh");
});
</script>
Here is my multiSelect page link:http://pratikisara.com/Home/Quick
How can I make ajax call from multiselect JS file(enter link description here) and in which code block should I do ajax call?
You need to to the rebuild and/or refresh in the AJAX success function. In your code, the AJAX call is made, then the multiselect is rebuild. But the rebuilt may happen before the AJAX call succeeds. Try this:
<script type="text/javascript">
$(document).ready(function () {
var categCheck = $('#multiselect').multiselect({
includeSelectAllOption: true,
enableFiltering: true
});
$.ajax({
type: 'GET',
url: "#Url.Content("~/Home/Listpositions/")",
success: function (data) {
$.each(data.data, function (index, item) {
alert(item.PositionName);
var opt = $('<option />', {
value: item.PID,
text: item.PositionName
});
opt.appendTo(categCheck);
// Rebuild after adding the options!
$('#multiselect').multiselect('rebuild');
});
}
});
});
</script>
by using reload its working fine for me. multiselect("reload") function refresh checkbox list in ajax call.
var obj_ddl_ExistingIdea = $("#ddl_ExistingIdea");
if (response.length > 0) {
for (var i = 0; i < response.length; i++) {
var str_newOption = '';
str_newOption = "<option value='" + response[i].IdeabookId + "'>" + response[i].Name + "</option>";
obj_ddl_ExistingIdea.append(str_newOption);
}
obj_ddl_ExistingIdea.multiselect("reload"); //using reload its working for me
$('#sltHeadCountdetailsCategorySiteCode').empty();
$("#sltHeadCountdetailsCategorySiteCode").multiselect('destroy');
This Is 100% fine code....
$(document).ready(function() {
var chkreport = $('#reporting_unit'); // Object creation for your dropdown
var ajaxpath = 'ajax/fend.php';
var ajaxUrl = baseUrl + ajaxpath;
$('#hospital_category').on('change', function() {
var hospital_id = this.value;
//alert(hospital_id);
$.ajax({
method: 'POST',
url: ajaxUrl,
data: {
perform_action: 'reporting_list',
hospital_id: hospital_id
},
dataType: 'html',
success: function(result) {
chkreport.append(result); // append option in the object created before ajax calling
// Now call multiselect function with their parameter
chkreport.multiselect({
columns: 1,
placeholder: 'Select Reporting Unit',
search: true,
selectAll: true
});
chkreport.multiselect('rebuild'); // it will reload dropdown need to create multiselect with checkbox option.
}
});
});
});
Related
Can I make a custom validation rule that returns true/false based on a AJAX request? the problem is that the validate call has finished running when the AJAX call completes.
Do I need to have the rule set/unset a boolean variable based on which the field is valid/invalid?
const isValidNameRule = {
getMessage(field)
{
return "The name must be unique."
},
validate(validatingName)
{
var formData = new FormData();
formData.append("validatingName", validatingName);
this.$http.post("/api/isValid?name=" + validatingName, formData)
.then(function (response) {
// success
return true;
}, function (response) {
// error
return false;
});
}
};
Didn't know how to work with Promises.
Eventually got it working by extending one of the official samples:
const customRule = {
getMessage(field, params, data) {
return (data && data.message) || 'Something went wrong';
},
validate(aValue) {
return new Promise(resolve => {
var formData = new FormData();
formData.append("nameFilter", aValue);
$.ajax({
type: "POST",
url: url,
data: {
action: "validate",
value: aValue,
}
}).done(function (data) {
if (!ok)
{
resolve({
valid: false,
data: {message: "Condition not met"}
});
}
else
{
resolve({
valid: !! aValue,
data: undefined
});
}
});
});
}
};
I have the following request to the jsreport engine:
$.ajax({
method: "POST",
contentType: "application/json",
dataType: "jsonp",
url: "http://localhost:5488/api/report",
data: {
template: {
shortid: "ry6HoQRee"
},
data: {
"D": "5"
}
},
success: function (s) {
window.open("data:application/pdf,base64," + escape(s.responseText));
},
error: function (s) {
console.log(s);
}
});
However I can't find a way to read it inside the report template:
<span>{{data.D}}</span>
How do I refer to the data object that is inside the POST body
jquery doesn't support binary responses like pdf. You should rather use XMLHttpRequest:
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:5488/api/report', true)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status == 200) {
window.open("data:application/pdf;base64," + window.btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response))));
}
}
xhr.send(JSON.stringify({
template: {
shortid: 'Syeopu_xe'
},
data: {
'D': '5'
}
}))
Example of reaching data using handlebars templating engine
<span>{{D}}</span>
Additionally...
You may also take a look at jsreport official browser client library. It wraps the XmlHttpRequest calls into more elegant calls:
jsreport.serverUrl = 'http://localhost:3000';
var request = {
template: {
content: 'foo', engine: 'none', recipe: 'phantom-pdf'
}
};
//display report in the new tab
jsreport.render('_blank', request);
or in async fashion
jsreport.renderAsync(request).then(function(res) {
//open in new window
window.open(res.toDataURI())
//open download dialog
res.download('test.pdf')
});
I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.
My application has many items in the viewModel and I would like to see those values displayed in an alert box so I can see what is actually stored in there. When trying to pass this view model back to my controller I am not seeing any values, instead I am getting an error that 'viewModel' is not defined.
Here is an example of my view model script
$(document).ready(function () {
function ViewModel() {
var self = this;
self.SectionId = ko.observable("");
self.SectionName = ko.observable("");
var SectionNames = {
Id: self.SectionId,
Name: self.SectionName
};
self.selectedSectionName = ko.observable();
self.SectionNames = ko.observableArray();
// Initialize the view-model for Work Sections
$.ajax({
url: '#Url.Action("GetSections", "Home")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.SectionNames(data);
}
});
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
Similar to creating a global variable or class level variable I would like to have this viewModel contain all of the current values for all of my observable items.
Except for the missing closing tag (as mentioned by #CSharper) your code will not throw the error you speak of. The answer to your question lies either in that missing closing tag, or in another piece of code not shown.
Here's how you can check, by mixing your code (+ closing tag) with a $.ajax stub:
$.ajax = function() {}; // Noop stub.
$(document).ready(function () {
function ViewModel() {
var self = this;
self.SectionId = ko.observable("");
self.SectionName = ko.observable("");
var SectionNames = {
Id: self.SectionId,
Name: self.SectionName
};
self.selectedSectionName = ko.observable();
self.SectionNames = ko.observableArray();
// Initialize the view-model for Work Sections
$.ajax({
url: '#Url.Action("GetSections", "Home")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.SectionNames(data);
}
});
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
$root = <code data-bind="text: ko.toJSON($root)"></code><br />
No errors on console.
I'm studying Ember.js myself and I'm stuck with a problem I'm creating a sample app and I need to send the client side values to Server Side but I dont know how to do that I know the traditional way like the below code
function create() {
var data = {
'EmailID': $('#emailid').val(),
'password': $('#password').val()
}
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data:data,
success: function (response) {
alert("hi");
}
});
return false;
}
but In Ember i dont Know How to do that my current code is given below
//Application
App = Em.Application.create();
//Model
App.Users = Em.Object.extend({
name: null,
password:null
});
//View
App.UserTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
App.PassTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
//controller
App.AlertController = Em.ObjectController.extend({
content: [],
username: '',
password: '',
alertDetails: function () {
var me = this;
var username = me.get("username");
var password = me.get("password");
alert('The User Name Is' + 'username' + 'And Password Is' + 'password');
}
});
App.alertController = App.AlertController.create();
I got the textbox values from alertDetails function and how can I pass them to server side
App.Record = Ember.Object.extend({
name: '',
other: ''
}).reopenClass({
records: [],
find: function() {
var self = this;
$.ajax({
url: "/api/records/",
type: "GET",
cache: false,
dataType: "json",
beforeSend: function() {
//if you want to call this often and need to clear + reload it
return self.records.clear();
},
success: function(results) {
var result;
for (_i = 0, _len = results.length; _i < _len; _i++) {
result = results[_i];
self.records.push(self.records.addObject(App.Record.create(result)));
}
},
error: function() {
return alert("error: failed to load the records");
}
});
return this.records;
}
});
Now that you have your model setup, you can call it from your route model hook
App.RecordsRoute = Ember.Route.extend({
model: function() {
return App.Record.find();
}
});
The find method returns an empty array right away, your template is then bound to it. When the ajax call returns w/ success and you update that array the handlebars template will update it for you w/out any DOM or jQuery glue code