In my function I am calling method passing $obj as a parameter in the function. I have defined currsel object, now in the method its showing me $obj.currsel.html() is not a function. I am sharing my code below.
$(document).on('change','.ui-modulelist1',function(e){
var $targetSel =coreFrameWork.frModuleContId;
var $thisVal= $(this).find("option:selected").val();
var loadUrl = '../ux_framework_New/_'+$thisVal+'/index.html';
commonFramework.initLoad({'url':loadUrl, 'currSel':$targetSel, 'mode':'autoload'});
});
var commonFramework ={
initLoad:function($obj){
$.ajax({
type: "GET",
url: $obj.url,
dataType: "html",
cache:false,
async:false,
beforeSend: function(xhr){
xhr.withCredentials = false;
},
success: function(html) {
$obj.currSel.html(html);
$obj.currSel.attr(projCommonAttr.autoloadAttr,'loaded');
commonFramework.contentSpecific({'currSel':$obj.currSel,'mode':$obj.mode});
},
error: function(qXHR, textStatus, errorThrown){
}
});
},
It's hard to tell without seeing an example url. What is coreFrameWork.frModuleContId? Try logging it in your console. I'm guessing you need to do
var $targetSel = $(coreFrameWork.frModuleContId);
Is this:
var $targetSel =coreFrameWork.frModuleContId;
a jQuery object?
The function html() belongs to jQuery, so if your object is not a jQuery one, it won't find that method.
I don't exactly know what that variable is, but you can try by wrapping it into a jQuery object:
var $targetSel = jQuery(coreFrameWork.frModuleContId);
Also, it is not a good practice to use names beginning with $ to name simple js objects (those names are often used to name variables representing jQuery objects or so).
Hope this helps you.
Regards,
Marcelo
url: $obj.url,
This parameter needs to be a string. If you want a dynamic url from your obj variable do this:
url: $obj+".php", // .php or whatever the file type is of the page you're requesting
Related
I need to pass list of strings from multiple select to the controller. Though the requirement looked very simple to me, I was breaking my head for the past hour in this. I have did a fair research on this, but unable to succeed.
Below is my Javascript code. Please ignore the comments. I was successfully able to fetch the list of items in the multiple select. While i do the ajax call, I get the error "Object reference not set an instance of an object.
function submitForm() {
var selected = $('#selectedTasks option').map(function(){
return this.value
}).get()
var postData = { selectedTasks : selected } //corrected as suggested
//selectedTasks = JSON.stringify({ 'selectedTasks': selected });
alert(postData);
$.ajax({
type: "POST",
//contentType: 'application/json; charset=utf-8',
url: '#Url.Action("AssignTasks", "MonthEndApp")',
dataType: 'json',
data: postData,
traditional: true,
success: function (data) {
alert("Success");
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
MonthEndAppController.cs
[HttpPost]
public void AssignTasks(List<String> selectedTasks)
{
//do something
}
Can someone guide me where exactly I have gone wrong? Can someone suggest me what is wrong?
EDIT : As suggested by Mr. Rory I have made the java script changes. Now the Java script part works absolutely fine. But the Controller is not getting called when the ajax request is made. Can someone help me out if something wrong in the call made to controller ?
Have you tried with string[] instead of List<String> ?
The parameter your AssignTasks action is expecting is called selectedTasks, not values:
var postData = { selectedTasks: selected };
Also note that when debugging anything in JS you should always use console.log() over alert(), as the latter coerces all types to a string, which means you're not seeing a true representation of the actual value.
I use jQuery's getJSON call to rerieve the content from a file called my.json.
Now sometimes the JSON file contains a certain character, that would invalidate the syntax. Unfortunately, it is not in my power to change that.
I thought it would be easy to use the success thing to intercept the JSON string and dix it, before $.getJSON() reads it and fails because the syntax is invalid. Obviously, it's not as easy, as I thought.
I would appreciate, if someone could help me out fixing below code.
$.ajaxSetup({
beforeSend: function(xhr){
if (xhr.overrideMimeType) {
xhr.overrideMimeType("application/json");
}},
cache: false
});
$.getJSON("my.json", function(data){
// Do something with the JSON
console.log("JSON object: " + data);
}).success(function(data, textStatus, jqXHR) {
// Intercept JSON string and modify it.
var fixed_json = fix_json(jqXHR.responseText);
jqXHR.responseText = fixed_json; // Obviously not as simple as I thought.
});
You can use the success callback of $.ajax() to do the required check on the returned data. It would require you to set the dataType to text though, so that jQuery doesn't try and automatically parse it for you. Try this:
$.ajax({
url: "my.json",
dataType: 'text',
success: function(data) {
var obj;
try {
obj = JSON.parse(data);
}
catch(e) {
obj = fix_json(data);
}
// work with the object here...
})
});
Example fiddle
Depending on the work that fix_json does, and assuming that it always returns an object, you could call that directly and remove the try/catch.
I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.
I'm having an issue where jQuery.ajax() is calling my data objects functions. For example, I have an object structure similar to the following:
var TestFactory = (function () {
var _id;
var _attributes;
return {
createObject: function (objectId) {
var value = null;
_id = objectId;
_attributes = {};
function _showErrorStatus() {
$('label')
.css('background-color', 'red')
.css('color', 'black')
.text('jQuery called me...');
}
function _attr(key, value) {
if (value == null) {
return _attributes[key];
}
_attributes[key] = value;
return this;
}
return {
id: _id,
attributes: _attributes,
showErrorStatus: _showErrorStatus,
attr: _attr,
}
}
}
})();
I'd like to use this object as the data value for my jQuery.ajax() call, as follows:
var myObject = TestFactory.createObject(12345);
myObject.attr('name', 'Fred Flinstone');
$.ajax({
url: '/echo/json/',
type: 'GET',
data: myObject,
dataType: 'json',
});
The issue I'm running into is jQuery.ajax() is calling the showErrorStatus() function from the object returned by the factory --nowhere in my code do I call this function.
I like the OOP qualities I get out of using this object, so is there any way to handle this case without a significant rewrite (e.g., dropping all my functionality from the "class")?
NOTE: I found it difficult to explain this problem, so here is a complete running example on jsfiddle.
Use JSON.stringify (not a jQuery method).
$.ajax({
url: '/echo/json/',
type: 'GET',
data: JSON.stringify(myObject),
dataType: 'json',
});
http://jsfiddle.net/HJ9AS/10/
It happens because it's a feature, though not documented as far as I can tell.
If you pass an object, then it assumes you want it to call any functions that are values of object properties.
One way of doing it is to use a function like Underscore's pick(). It can be used to cherry-pick certain properties you need from the object. It is a useful library anyways, but you can also implement this simple method if you wish.
$.ajax({
url: '/echo/json/',
type: 'GET',
/* only send id and attributes! */
data: _.pick(myObject, 'id', 'attributes'),
dataType: 'json',
});
It might be a nice habit to always whitelist stuff, not just send everything blindly. Specifying exactly what to send can save you from future surprises (like the one you just encountered). Most of the time you simply don't want to send everything that is stored in your object.
You can also implement some way for your object to be able to return its sendable contens. It could get a .getJSON() method that just collects from the object everything to be sent.
Concerning the function calling:
Processing the data property uses $.param(), which has this in the docs:
As of jQuery 1.3, the return value of a function is used instead of the function as a String.
This is a feature, not a bug :). I understand the logic behind it, because if there is a function in the object that you just specified as data to be sent, there must be a good reason behind it...
Instead of passing data: myObject,
try setting this: var serializedObject = myObject.param()
then passing data: serializedObject
Check out jQuery's param function here.
I have this code snippet in .js file
$(function () {
// KeyDates
var url = "http://localhost:8732/Design_Time_Addresses/Intel.IIP.MDF.WCF/ProgramCalendarService/GetKeyDatesCalendarNew";
$.ajax({
url: url,
data: null,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
success: function (GetKeyDatesCalendarDataNew) {
alert(GetKeyDatesCalendarDataNew);
$(document).ajaxStop($.unblockUI);
}
});
});
How do i process the key value pair in GetKeyDatesCalendarDataNew?
You probably want to know how to access an object's props. For that, use the for in loop to iterate over the object's values:
success: function (GetKeyDatesCalendarDataNew) {
for(var key in GetKeyDatesCalendarDataNew)
{
var value = GetKeyDatesCalendarDataNew[key];
// do somehitng based on the key and/or value iterated
}
}
For this case, the argument of the success function is the evaluated JSON that was returned from the Ajax request. Therefore GetKeyDatesCalendarDataNew, which you should rename to something like data, becomes the actual data that your server returned.
You can only process the data if you know its structure. One simple way of knowing this would be to do console.log(GetKeyDatesCalendarDataNew) and then easily process it with a for loop if it's an array or for x in.. if it's an object.
You can use JQuery "getJSON" function where you need to pass the url and specify a callback function.Your ajax call will be handled by the getJSON function. In the callback function, you can access the Keys as properties. A nice example
Lav G
$.each(GetKeyDatesCalendarDataNew,function(key,value){
//do something here
})