I have the following code:
// auto_suggest.js
function AutoSuggest(textboxElem, resultElem, url) {
this.textboxElem = textboxElem;
this.resultElem = resultElem;
this.url = url;
this.registerEvent();
}
AutoSuggest.prototype = {
registerEvent: function() {
this.textboxElem.onkeyup = this.getSuggestions;
},
getSuggestions: function() {
// This doesn't work either: this.loadResponse("some data");
$.get(this.url, { text: this.textboxElem.value }, this.loadResponse);
},
loadResponse: function(data) {
// Not called
this.resultElem.innerHTML = data;
}
};
// suggest.html
<script src="jquery-1.6.1.js" type="text/javascript"></script>
<script src="auto_suggest.js" type="text/javascript"></script>
<script>
$(function() {
var suggest = new AutoSuggest(document.getElementById("suggest"),
document.getElementById("result"),
"result.txt");
// This DOES work: suggest.loadResponse("123");
});
</script>
<input type="text" id="suggest" /><br>
<div id="result"></div>
The function loadResponse refuses to be called from within the object, but from the outside it is fine. What could be the problem?
The AJAX callback (AutoSuggest.loadResponse) is, by default, passed the jqXHR object as its context (this value). You need to override this by passing the context option to $.ajax. Replace your $.get function with this:
$.ajax({
url: this.url,
type: 'GET',
data: { text: this.textboxElem.value },
success: this.loadResponse,
context: this
});
This makes jQuery set this to the correct value.
The code
this.textboxElem.onkeyup = this.getSuggestions;
should be
var t = this;
this.textboxElem.onkeyup = function() {
t.getSuggestions();
}
Related
I'm trying to dynamically load partial view with a different model instances inside of main view. Everything is working fine, until I have to reload partial view content. Then I have to reload 1 select list options, that is not in model. I have js method for that. Problem is, sometimes options are added, and disapear instantly. What am I doing wrong?
There are no any methods, that are changind this select control.
Main view:
<div id="tableContainer">
#{Html.RenderPartial("_TableView", Model.Tables[0]);}
</div>
<script type="text/javascript">
function loadTable () {
var selectedElement = $("#tableSelect").children("option:selected").val();
$("#tableContainer").load("/Home/UpdateTable/" + selectedElement);
getDishes();
};
window.onload = function () {
getDishes();
};
</script>
getDishes function:
function getDishes() {
$.ajax({
type: "GET",
url: "/GetDishes",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
success: function (result) {
if (result.success) {
fillDishList(result.message);
}
else
alert("Błąd podczas pobierania dostępnych dań! Treść błędu: " + result.message);
}
})
}
And fillDishList function:
function fillDishList(list) {
for (var a = 0; a < list.length; a++) {
var element = { val: a, text: list[a].Name };
$("#dishes").append($("<option>").attr('value', element.val).text(element.text));
}
updateDishPrice();
}
EDIT
Ok I got it working. There was timing issue. Function that should append elements to select list were launched before partial view were completely loaded. Here is solution:
<script type="text/javascript">
function loadTable () {
var selectedElement = $("#tableSelect").children("option:selected").val();
$("#tableContainer").html("");
$("#tableContainer").load("/Home/UpdateTable/" + selectedElement);
window.requestAnimationFrame(ready);
};
var ready = function () {
var dishes = $("#dishes");
if (dishes) {
getDishes();
if (dishes.children().length != 0)
return;
};
window.requestAnimationFrame(ready);
};
window.onload = function () {
getDishes();
};
</script>
I have two files:
example.html:
<div class="my-div"></div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "example1.html",
type: "get",
success: function(response) {
$(".my-div").html(response);
}
});
$(document).on("click", "button", function() {
console.log(alpha); // Should print "data",
});
});
</script>
example1.html:
<button></button>
<script type="text/javascript">
$(document).ready(function() {
var myDropzone = new Dropzone("", {
success: function(file, response) {
const alpha = "data";
}
});
});
</script>
In example.html, I need console.log(alpha) to output "data". I make an Ajax request to example1.html, and update the contents of my div with the returned html. The constant alpha isn't useable until new Dropzone() succeeds. How can I make this code work?
One option is to make your alpha variable global.
You declared your alpha variable inside success function so you can only use that variable inside it.
<button></button>
<script type="text/javascript">
const alpha; /* Init it here */
$(document).ready(function() {
var myDropzone = new Dropzone("", {
success: function(file, response) {
alpha = "data"; /* Assign the value here */
}
});
});
</script>
Now you can access it as
$(document).on("click", "button", function() {
console.log(alpha); // Should print "data",
});
i am using the knockout js, i am finding diffcult to bind the data while in ajax get method, i have created model, viewModel, and ajax function, i have the ajax method in the same js file where i have created viewModel i am calling the ajax on page load and trying to bind my html with konckout js, i am getting the error userModel is undefined if i give this.name = ko.observale(result[0].name) before the ajax call, after the ajax called it give name is undefined need help
<html>
<head>
<script src="js/jquery1.9.js"></script>
<script src="js/knockout-3.3.0.js"></script>
<script src="js/knockout.mapping.js"></script>
<script src="model/usermodel.js"></script>
</head>
<body>
<div>
<h1><span data-bind="text:user().name"></span></h1>
<h1><span data-bind="text:user().userName"></span></h1>
</div>
<script src="ViewModel/userDetailsViewModel.js"></script>
</body>
</html>
////Model////
function userModel(result) {
var self = this;
this.name = ko.observable(result[0].name); /// give me error undefined before the ajax call and after ajax call i get the value in result
this.userName = ko.observable();
}
/////View Model////
var result
var userDetailsViewModel = function(result) {
self = this;
self.user = ko.observable(new userModel(result));
};
var mainUserDetailsViewModel = new userDetailsViewModel(result);
ko.applyBindings(mainUserDetailsViewModel);
////ajax called on the page load ////
$.ajax({
type: "POST",
dataType: "json",
url: baseUrl + 'api/xx/xxx',
data: jason.strigfy(),
success: function(data) {
result = data;
////I am getting in result json data object 0=["name":"nnnn","Username":"mmmmmm"],
//// i am passing this result to ViewModel and to Usermodel Constructor//
mainUserDetailsViewModel.user(new userModel(result));
},
error: function(error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
Here is my suggestion to have a clean nested view model.
Example : https://jsfiddle.net/kyr6w2x3/28/
function UserViewModel() {
var self = this;
self.UsersList = ko.observableArray([]);
self.GetUsers = function() {
$.ajax({
type: "POST",
dataType: "json",
url: baseUrl + 'api/xx/xxx',
data: jason.strigfy(),
success: function (data) {
//Here you map and create a new instance of userDetailVM
self.UsersList($.map(data, function (user) {
return new UserDetailViewModel(user);
}));
}
});
}
//call to get users list when the VM is loading or you can call it on any event on your model
self.GetUsers();
}
function UserDetailViewModel(data){
var self = this;
self.Name = ko.observable(data.name);
self.UserName = ko.observable(data.username);
}
ko.applyBindings(new UserViewModel());
View :
<h1 data-bind="foreach: UsersList">
<div data-bind="text: Name"></div>
<div data-bind="text: UserName"></div>
</h1>
If I have a script like below that's ran to load a table with data injected into it from an external PHP file on to the page.
<script>
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
success : function(text)
{
response = text;
}
});
alert(response);
});
</script>
I have another script down below where a user can add records to the database.
<script id="sosurce" language="javascript" type="text/javascript">
$("#newitemadd").click(function(){
$('#New').modal('show');
$("#insertResults").click(function(){
var getname = $('#getname').val();
var getquant = $('#getquant').val();
var getprice = $('#getprice').val();
var getdesc = $('#getdesc').val();
$.ajax({
url: 'api2.php',
data: "name="+getname+"&quantity="+getquant+"&price="+getprice+"&description="+getdesc,
success: function(data)
{ $('#New').modal('hide');
$("#success").html(data);
$('#success').slideDown().delay(3000).slideUp().reload
},
error: function() {
$("#failure").alert('show');
}
});
});
});
</script>
It works fully as intended but, how can I get the first script to Re-Run so the table that's inserted onto the page is refreshed to show the new results that were just added?
you can do like this .
<script>
var renderTable = function() {
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
success : function(text)
{
response = text;
}
});
alert(response);
}
// Call function onload
jQuery(function($){
renderTable();
$(".refreshBtn").click(function(){
renderTable();
})
});
</script>
Move first code into an function like
<script>
$(document).ready(LoadData);
function LoadData() {
var response = '';
$.ajax({
type: "GET",
url: "Records.php",
success : function(text) {
response = text;
}
});
alert(response);
};
</script>
And call this function from other function, example does it on success
<script id="sosurce" language="javascript" type="text/javascript">
$("#newitemadd").click(function() {
$('#New').modal('show');
$("#insertResults").click(function() {
var getname = $('#getname').val(),
getquant = $('#getquant').val(),
getprice = $('#getprice').val(),
getdesc = $('#getdesc').val();
$.ajax({
url: 'api2.php',
data:
"name="+getname+"&quantity="+getquant+"&price="+getprice+"&description="+getdesc,
success: function(data) {
$('#New').modal('hide');
$("#success").html(data);
$('#success').slideDown().delay(3000).slideUp().reload
// Call load data again to refresh the table
LoadData();
},
error: function() {
$("#failure").alert('show');
}
});
});
});
</script>
I have the following function that is called in the head tag.
Page::IncludeJavascriptFile('js/packages.js');
Page::AddHeadElement('
<script type="text/javascript">
$(document).ready(function() {
pollClientTable('.TriplecastConfig::get('transfer_polling_period')*1000 .', true);
});
</script>
');
pollClientTable is defined in packages.js which is before the function call.
pollClientTable function:
var pollClientTableTimer = null;
var pollClientTableTimerPoll = null;
function pollClientTable(poll, async) {
clearTimeout(pollClientTableTimer);
$.ajax({
url: "ajax_requests/getClientPackages.php",
async: async,
timeout: poll,
success: function(data) {
$('#packagesForm').empty();
$('#packagesForm').append(data);
}
});
pollClientTableTimerPoll = poll;
pollClientTableTimer = setTimeout(function(){pollClientTable(poll, true);}, poll);
}
The functions work in any other browser bar IE8. Any ideas why?