Javascript Object Initialization not working [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Have code structure like this :
SkillEidt.js (Javascript File):
var SkillEdit = ({
_designtemplate: ["", "input", "dropdownlist", "checkbox"],
_designTemplateData: {},
readValue: function() {
/* when try to read value from customer.Html it's null */
return this._designTemplateData;;
},
RequestResponse: function (data) {
/* able to get and set value from ajax call */
this._designTemplateData = data;
},
ajaxCall : function() {
$.ajax({
url: "/VendorDetails/GetVendorDetails",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (result) {
alert(result.statusText);
},
success: function (result) {
requestReponse(result);
}
});
});
SkillEdit.ajaxCall() /* very important to set _designTemplateData data */
Customer.Html (page):
<script src="~/Scripts/SkillEdit.js"></script>
<script type="text/javascript">
function SomeBuuttonClickEvent() {
var notAbleToGetValue = SkillEdit.readValue();
}
</script>
------------------------------------------------------------------------
When debug and see SkillEdit.ajaxCall() will call ajaxCall() method and on success will call RequestResponse and set _designTemplateData. But When i click Button (SomeBuuttonClickEvent) on Customer.Html page readValue is returning null value. How can i set the _designTemplateData data.
..
Have added $.ajax function. How to slove the problem by using any of the solution
What code to be added
What code need to be written inside :
RequestResponse: function (data)
or
ajaxCall : function()

Please try this.
SkillEdit.js
var SkillEdit = function(){
_designtemplate= ["", "input", "dropdownlist", "checkbox"],
_designTemplateData= {},
readValue = function () {
$('#templabel').text(_designTemplateData);
return _designTemplateData;
},
RequestResponse = function (data) {
debugger;
return _designTemplateData = data;
},
ajaxCall= function () {
//return this.RequestResponse(["12", "13"]);
$.ajax({
url: "/Home/GetVendorDetails",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (result) {
alert(result.statusText);
},
success: function (result) {
RequestResponse(result);
console.log(result);
}
});
}
return {
readValue: readValue,
RequestResponse: RequestResponse,
ajaxCall : ajaxCall
}
}();
In ViewPage:
<script src="~/js/SkillEdit.js"></script>
<label id="templabel"></label>
<input type="button" value="stake overflow question" onclick="return SkillEdit.ajaxCall();"/>
<input type="button" value="read Value answer" onclick="return SkillEdit.readValue();" />
In Controller:
[HttpPost]
public ActionResult GetVendorDetails()
{
return Json("[12,13]");
}

Your code appears to be working : (run it below)
var SkillEdit = {
_designtemplate: ["", "input", "dropdownlist", "checkbox"],
_designTemplateData: {},
readValue: function() {
return this._designTemplateData;;
},
RequestResponse: function (data) {
this._designTemplateData = data;
},
ajaxCall : function() {
this.RequestResponse("test successful");
}
};
SkillEdit.ajaxCall()
alert(SkillEdit.readValue()) // Should alert "Test successful"
Your error may be in the treatment of your ajax response.

Related

How to set serialization in Asp .Net Core

Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

How do I make a function call execute first before executing subsequent codes? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am trying to learn JS by building a random Quote Machine but this problem has been bugging me. I saw the other answers but I really couldn't understand them due to lack of context. Any help will be appreciated. The code is:
$(document).ready(function () {
$("#btn").click(function () {
getQuote(); //This should execute first, then the next lines
var quoteData = jSonify();
var quote = quoteData[0];
var author = quoteData[1];
console.log(quote);
console.log(author);
console.log("Button Clicked");//This Should execute last.
});
//Get them quotes
function getQuote() {
$.ajax({
url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type: 'GET',
data: {},
datatype: 'json',
success: function (data) { jSonify(data); },
error: function (err) { alert(err); },
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
}
});
}
//Convert to jSon
function jSonify(rawData) {
var jSonified = jQuery.parseJSON(rawData);
var quote = jSonified.quote;
var author = jSonified.author;
console.log(quote);
console.log(author);
return [quote, author];
}});
getQuote() won't be done by the time JavaScript runs the next line, var quoteData = jSonify();. This is because it has a $.ajax call inside of it, which could take a long time to complete.
getQuote won't be done until the success method in the $.ajax method is called.
So what you need to do is pass a callback into getQuote, like so:
$("#btn").click(function () {
getQuote(function() {
var quoteData = jSonify();
var quote = quoteData[0];
var author = quoteData[1];
console.log(quote);
console.log(author);
console.log("Button Clicked");
});
});
//Get them quotes
function getQuote(done) {
$.ajax({
url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type: 'GET',
data: {},
datatype: 'json',
success: function (data) { jSonify(data); done(); }, // Call the callback!
error: function (err) { alert(err); },
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
}
});
}
The callback will only be called once the ajax has actually finished. Once it's called, the rest of the computation will take place.
you can embed later to be called statements inside ajax success
$(document).ready(function () {
$("#btn").click(function () {
getQuote(); //This should execute first, then the next lines
});
//Get them quotes
function getQuote() {
$.ajax({
url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type: 'GET',
data: {},
datatype: 'json',
success: function (data) {
var quoteData = jSonify(data);
var quote = quoteData[0];
var author = quoteData[1];
console.log(quote);
console.log(author);
console.log("Button Clicked");//This Should execute last.
},
error: function (err) { alert(err); },
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
}
});
}
//Convert to jSon
function jSonify(rawData) {
var jSonified = jQuery.parseJSON(rawData);
var quote = jSonified.quote;
var author = jSonified.author;
console.log(quote);
console.log(author);
return [quote, author];
}});

How to load data from ajax to zabuto calendar plugin?

As title, I tried load data from ajax to zabuto calendar, but seem it's not working, ref of zabuto calendar http://zabuto.com/dev/calendar/examples/show_data.html. And i want to use this function load data when click nav prev month or next month. (use two action action and action_nav). This is snipped code
<script>
$(document).ready(function () {
function load_data() {
var list = '';
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
list = $.parseJSON(data.d);
console.log(list);
}
});
return list;
}
function myNavFunction(id) {
//code in here
}
function myDateFunction(id) {
//code in here
}
$("#my_calendar").zabuto_calendar({
data: load_data(),
action: function () {
return myDateFunction(this.id);
},
action_nav: function () {
return myNavFunction(this.id);
}
});
});
</script>
When i test this, data not show, the data from ajax as
{ "date": "2016-06-01", "title": 2, "badge": true },{ "date": "2016-06-04", "title": 1, "badge": true },{ "date": "2016-06-10", "title": 1, "badge": true }
Thank you so much.
Try the following: you need to place the calendar function in the success function of the ajax call because ajax is asynchronous
$(document).ready(function () {
function load_data() {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var list = $.parseJSON(data.d);
$("#my_calendar").zabuto_calendar({
data: list;
});
},
error: function (data) {
console.log(data.d);
}
});
}
load_data();
});
I solved the issue by the code as below. It works well in window's browser but not in a mobile browser.
function initZabuto(id, events, month){
$('#zabuto_parent').empty().append("<div id='"+id+"'></div>");
$("#"+id).zabuto_calendar({
year:moment(month).format("YYYY"),
month:moment(month).format("MM"),
language:"cn",
data: events,
action: function () {
zabutoDayClick(this.id);
},
action_nav: function () {
zabutoMonthChange(this.id);
}
});
}
This is the code I used to refresh Zabuto calendar after a modal. The problem with other options is that upon refresh, Zabuto would create a new batch of modals appended to the current body. This solutions clears all those "old" modals and opens room for the new. Key area is the success section of the modal update ajax.
$(document).ready(function () {
$("#date-popover").popover({html: true, trigger: "manual"});
$("#date-popover").hide();
$("#date-popover").click(function (e) {
$(this).hide();
});
load_calendar();
});
function load_calendar() {
$("#my-calendar").zabuto_calendar({
show_next: 1,
action: function () {
return myDateFunction(this.id, false);
},
ajax: {
url: "calendar-info.php",
modal: true
},
});
}
function myDateFunction(id, fromModal) {
$("#date-popover").hide();
if (fromModal) {
$("#" + id + "_modal").modal("hide");
var date = $("#" + id).data("date");
var optradio = $("#" + id + "_modal").find("input[name='optradio']:checked").val();
$.ajax("calendar-update.php?status="+optradio+"&date="+date, {
success: function(data) {
$(".modal").remove();
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
$("#my-calendar").empty();
load_calendar();
},
error: function() {
alert("Problem!");
}
});
}
var hasEvent = $("#" + id).data("hasEvent");
if (hasEvent && !fromModal) {
return false;
}
return true;
}

How to combine multiple call to Ajax Data base from different JS files

I have some code on a file that makes Ajax calls. This file is being called as a function by multiple other files that creates a new instance each time.
This is the JS code that is being called:
define(["underscore", "homeop", "domReady!"],
function (_, homeop, domready) {
var timeout = 500;
return function (opUrl, opList, onCallback) {
// IRRELEVANT CODE
var getFetch = function (optionName) {
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
}
});
};
self.getInfo = function (optionName) {
if (homeop.globalCache[optionName] === undefined) {
if (!_.contains(homeop.getOption(), optionName)) {
getFetch(optionName);
}
// MORE IRRELEVANT CODE GOES HERE
In other JS files, I call the get function; for example
var these = new getOptions(optionsUrl, optionsList, onLoadCallback);
var getOpt = these.get(OptionsUrl);
The problem is I am making multiple calls to the get information from the database causing multiple call to my JS file. Each new instance of the JS file will create a ajax call.
Is there a way to wait for all the calls to be done and then get data from the database? In other words how can I somehow combine all the call to my 'getOption.js'?
Thanks
Try this.. You can also implement queue in place of stack
var optionStack = [];
var isAvailable = true;
var getFetch = function (optionName) {
if(isAvailable){
isAvilable = false; // function not available now
}
else {
optionStack.push(optionName)
return;
}
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
},
done: function (){
isAvailable = true;
if(optionStack.length > 0){
getFetch(optionStack.pop());
}
}
});
};

Calling Javascript function inside controller action -YII

I'm trying to call Javascript function inside controller action method, Is there any right way to call setTimeout() to be invoked on certain condition inside controller action method ?
window.setTimeout(function() {
alert("test");
$.ajax({
type: "POST",
url: "'.$this->createUrl("/operator/createViopNode/").'",
data: {
id: '.$bc_id.',
callid:"'.$num.'",
taskid:'.$this->taskid.'
},
success: function(msg){
var ifrm = document.getElementById("frame");
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(msg);
ifrm.document.close();
},
error: function (jqXHR, textStatus, errorThrown){
alert("" + textStatus + ", " + errorThrown);
}
});
}, parseInt('.$tps_call.'));
I need to write above js function inside controller action method, how to write this ?
Index.csHtml
function abc()
{
alert("called")
}
now Ajax Call function
function ExecuteAjax(URL,Data,Success)
{
try {
$.ajax({
type: "post",
url: URL,
data: Data,
contentType: "json",
success: function (data) { if (typeof Success == "function") { Success(data); } }
})
} catch (e) {
alert(e.message)
}
}
Call ajax like this
ExecuteAjax("/Home/FillColorDropDown", "", function (data) {
eval(data.script);
});
return from controller
if(demo=="true")//put condition here whatever you want
{
string strscript="abc();";
}
protected JObject jobj = new JObject();
jobj.Add("Script", strscript);
return Json(jobj);
Execute js function when controller return success
You should register your javascript function like this:
function actionTest(){
$cs = Yii::app()->clientScript;
$cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);
$this->render('any_view');
}
source

Categories