MVC posting via javascript to controller strange json object behavior - javascript

When a form is submitted I capture it in javascript. I do some validation and create a json object and pass that to $.post(). In my controller I have an object defined with the same definition as the json object. I'm finding if I don't access the json object in javascript then it's null when it gets to the controller. If I do an alert on it's fields then the controller has the values filled in. Any idea why this is happening?
$(function(){
$("#VideoForm").submit(function () {
var video = $("#txtVideo").val();
var val = getVideoID(video);
if (val.ID == -1) {
event.preventDefault();
alert("Invalid url. Only Vimeo and YouTube are supported.")
$("#txtVideo").val("")
return false;
}
// if this is commented out then my controller parameter object is null
// if this is uncommented then my controller parameter object is filled in
//alert(val.ID);
//alert(val.Source);
$.post('/Home/Index', val, function (data) {
});
});
function getVideoID(videolink){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = videolink.match(regExp);
if (match && match[7].length == 11)
{
//alert("youtube video id : "+ match[7]);
alert("Youtube match");
return { ID: match[7], Source: "youtube" };
}
regExp = "vimeo\\.com/(?:.*#|.*/videos/)?([0-9]+)";
match = videolink.match(regExp);
if(match)
{
var videoid = videolink.split('/')[videolink.split('/').length - 1];
alert("Vimeo match");
//alert("vimeo video id :"+videoid);
return { ID: videoid, Source: "vimeo" };
}
else
{
return { ID: -1, Source: "" };
}
};

Related

Uncaught TypeError: Cannot use ‘in’ operator to search for ‘length’ in jquery-1.11.1.js:583

I have two JS files as shown below (page1.js) and (page2.js for reference included below). I am basically referring to the following JSON response while working :
{
"webservice_status": {
"status": "SUCCESS",
"message": ""
},
"my_document_list": [{
"doc1": "445",
"doc2": "445",
"doc3": "445",
"doc4": "445",
"content": "Some text here to display"
}
]
}
Here is my page1.js related work:
$("#mydoclist").on('rowclick', function (event) {
row = event.args.rowindex;
datarow = $("#mydoclist").jqxGrid('getrowdata', row);
var response = JSON.stringify(datarow, null, 10);
var docID = datarow["doc_id"];
self.getMyDocumentContents(docID);
});
this.getMyDocumentContents = function (contentID_) {
var data = {
doc_id: contentID_
}
app_.get(data, self.processContent, app_.processError, url_name);
}// End of getMyDocumentContents
this.processContent = function(data_,textStatus_,jqXHR_) {
data_ = app_.convertResponse(data_,jqXHR_);
console.log("Checking for actual data_ content:", data_);
console.log("Actual Data Length Check for data_ content:", data_.my_document_list.length);
// debugger;
var collection = data_.my_document_list.length[0].content;
console.log("Collection Check",collection);
//debugger;
var source = {
localdata: collection,
datafields: [{
name: 'content',
type: 'string'
}],
datatype: "array"
};
var dataAdapter = new $.jqx.dataAdapter(source, {
loadComplete: function (records) {
debugger;
var html;
//Get data
var records = dataAdapter.records;
console.log("Check for records:",records.length);
var length = records.length;
html = "<div style='margin: 10px;'><pre>" + records[0].content + "</pre></div>";
$("#docContentPanel").jqxPanel('clearcontent');
$("#docContentPanel").jqxPanel('append',html);
},
loadError: function (xhr, status, error) { },
beforeLoadComplete: function (records) {
}
});
// perform data binding
dataAdapter.dataBind();
var panel = $("#docContentPanel");
var content = panel.html();
panel.jqxPanel({ width: '750', height: '500', scrollBarSize: 20 });
}// End of processContent
Here is my page2.js related work:
this.get = function (data_, done_, fail_, webServiceKey_) {
// Lookup the requested web service URL
var url = https://documentlookup.com:8443/getmydocuments;
// Create the AJAX request.
$_.ajax({
data: data_,
method: "GET",
url: url
})
.success(done_)
.error(fail_);
};
// If the JSON data was returned with content type of "text/plain", parse as JSON before returning.
this.convertResponse = function (data_, jqXHR_) {
return (typeof(data_) === "object" ? data_ : JSON.parse(data_));
};
Basically there is a list of rows displayed in a jqxgrid(not mentioned in the code above), when a user clicks on it
$("#mydoclist").on('rowclick gets called , which calls the following function:
getMyDocumentContents function: This function basically passes the doc_id inside data variable which is made
available for the following function:
processContent:
In this function, I am trying to show in jqxPanel the value of the contentwhich is in my_document_list array.
Problem I am facing inside this function:
As can be seen, there are debugger I placed at various places which are currently commented except at one place
which is just below this line loadComplete: function (records) {
I don’t get any error above this line var dataAdapter = new $.jqx.dataAdapter(source, { , however, as soon as
I place it inside it, I get the following error:
Uncaught TypeError: Cannot use ‘in’ operator to search for ‘length’ in jquery-1.11.1.js:583
Where length is a numerical number which keeps on changing depending upon the length of value of content in the above JSON response.
Could anyone tell me what’s going wrong? thanks in advance !
Just in case needed, here is the jQuery line #583 isArraylike function :
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj; // THIS is LINE 583 which throws error
}
Should I try changing the jQuery version?
At data_.my_document_list.length[0].content; I think you need data_.my_document_list[0].content;.
my_document_list is an array and as such the array access should occur there.

Array value becomes null while passing from Ajax

I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.

how to validate serialized data in Ajax

I have this particular problem, where I need to validate the data before it is saved via an ajax call. save_ass_rub function is called when user navigates to a different URL.
In my application, I have a custom Window and user is allowed to input data. I am able to capture all the data in this step: var data = $('form').serialize(true);. But I need to loop through this and check if data for some specific elements is empty or not. I can't do it when the user is in the custom window. The Custom window is optional for the user. All I want is to alert the user in case he has left the elements blank before the data is submitted.
We are using Prototype.js and ajax .
<script>
function save_ass_rub() {
var url = 'xxxx';
var data = $('form').serialize(true);
var result;
new Ajax.Request( url, {
method: 'post',
parameters: data,
asynchronous: false, // suspends JS until request done
onSuccess: function (response) {
var responseText = response.responseText || '';
if (responseText.length > 0) {
result = eval('(' + responseText + ')');
}
}
});
if (result && result.success) {
return;
}
else {
var error = 'Your_changes_could_not_be_saved_period';
if (window.opener) { // ie undocked
//Show alert in the main window
window.opener.alert(error);
return;
}
return error;
}
}
// Set up auto save of rubric when window is closed
Event.observe(window, 'unload', function() {
return save_ass_rub();
});
</script>
Can some thing like this be done?
After Line
var data = $('form').serialize(true);
var split_data = data.split("&");
for (i = 0; i < split_data.length; i++) {
var elem = split_data[i];
var split_elem = elem.split('=');
if( split_elem[0].search(/key/) && split_elem[0] == '' ){
console.log( split_elem );
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
}
Instead of using the serialized form string, I would use the form itself to do the validation. if $('form') is your form element then create a separate function that checks the form element so its compartmentalized.
function checkform(form)
{
var emptytexts = form.down('input[type="text"]').filter(function(input){
if(input.value.length == 0)
{
return true;
}
});
if(emptytexts.length > 0)
{
return false;
}
return true;
}
and in the save_ass_rub() function
//..snip
if(checkform($('form') == false)
{
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
var data = $('form').serialize(true);
var result;
I only added text inputs in the checkform() function you can the rest of the input types and any other weird handling you would like to that function. As long as it returns false the error will be displayed and the js will stop otherwise it will continue

json passing function is not working in jquery

i pass json value my controller is working i checked my controller using break points but my json is not working it didn't responding alert message also not working please some one helpme friends. . .
My jquery
$('#Group').change(function () {
var name = $('#Tournament').val();
$.post("/DataCollection/Fee", { name: name, group: $('#Group').val() }, function (result) {
alert('hai');
$('#Fee').val(result.value.Fees);
$('#Count').val(result.value.NoOfboys);
$('#CName').empty();
$('#CName').append($("<option></option>").html("--SELECT--"));
$.each(result.Cname, function (key, value) {
$('#CName').append($("<option></option>").html(value).val(value));
});
}, "json");
});
My Controller
public JsonResult Fee(string name, string Group)
{
var value = entity.TblClsGroups.FirstOrDefault(x => x.TName == name && x.GroupName == Group && x.RecordStatus == 1);
var Cname = entity.TblGroups.Where(x=>x.RecordStatus==1 && x.TName == name && x.GroupName == Group).Select(c=>c.Cid);
var getFee = new { Cname, value };
return Json(getFee, JsonRequestBehavior.AllowGet);
}
try this:
return Json(new { Cname = Cname, value = value }, JsonRequestBehavior.AllowGet);
and in view use them like result.Cname and result.value
Try this:
var getFee = new { Cname = Cname, value = value };

Using javascript to check true/false condition on viewmodel

I am using local storage variable to hold the location of a users current progress. I have ran into a problem whereby if the last section that the user was on has been since deleted I am getting a target invocation must be set error. This is my code:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
I need to check using javascript that the localStorage course section is still existing in the database so I created the following ViewModel method:
public bool CourseSectionLaunchStillExistCheck(int courseSectionID)
{
this.TargetCourseSection = courseSectionRepository.Get(cs => cs.CourseSectionID == courseSectionID).FirstOrDefault();
if (this.TargetCourseSection != null)
{
return true;
}
else
{
return false;
}
}
But when I try to use the following javascript:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
if ('#Model.CourseSectionLaunchStillExistCheck(id)' != true) {
var id = '#Model.CourseSections.First().CourseSectionID';
}
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
It is failing to recognise the id parameter saying it does not exist in the current context. How can I ensure that the course section exists using javascript before setting the variable?
Could I use a post such as:
var postData = { 'courseSectionID': id };
$.post('/Course/CourseSectionLaunchStillExistCheck/', postData, function (data) {
});
and then how could i check if the result of this post data would be true or false?

Categories