Using javascript to check true/false condition on viewmodel - javascript

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?

Related

Create Cookie in Controller, read cookie from Javascript

using MVC.
In one of my controllers I am creating a cookie like the following:
Function Login(ByVal access_token As String) As ActionResult
Response.Cookies.Add(New HttpCookie("access_token", access_token))
End Function
I want to check the value of the cookie called "access_token" client-side, in order to know the next step to take in javascript.
How can I do that?
Any help would be appreciated
UPDATE
I found the solution:
I just add this function in Javascript :
function ReadCookie(cookieName) {
var theCookie = "" + document.cookie;
var ind = theCookie.indexOf(cookieName);
if (ind == -1 || cookieName == "") return "";
var ind1 = theCookie.indexOf(';', ind);
if (ind1 == -1) ind1 = theCookie.length;
return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}
and I call it on Document.ready() with the name of the cookie that I want to retrieve like that:
if (ReadCookie("access_token") != '')
{ }

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

Why doesn't Chrome allow changing of style tag via JS?

I'm running this code:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=".concat(document.getElementById('name').value).concat(document.getElementById('domain').value), function(data) {
if(data == "true") {
document.getElementById('containerThree').style = "background-color:#20bb47;";
}else{
document.getElementById('containerThree').style = "background-color:#b33535;";
}
document.getElementById('avail').style = "color:#272727;";
document.getElementById('emt').style = "color:#272727;";
});
It works fine in FireFox, but in chrome not at all. I've tried using .style.background = "#mycolorcode" but it still doesn't work in chrome(and in that case, firefox too).
Try this:
if (data === 'true') {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
http://devdocs.io/html/element/style
http://youmightnotneedjquery.com/
NOTE: 'true' is a string. You would most likely would rather use the Boolean true.
Based on the latest edit to your question, does this cleanup of your surrounding code help?
jQuery.get('http://email.hackmailer.com/checkuser.php?email='
.concat(document.getElementById('name').value)
.concat(document.getElementById('domain').value),
function (data) {
if (data === true) {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
document.getElementById('avail').style.color = '#272727';
document.getElementById('emt').style.color = '#272727';
});
You don't need to send a string as 'true' to check a condition. Use it like:
var data = true; //use boolean but not 'true' as string.
Then you can simple use it as follows:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=" + document.getElementById('name').value + document.getElementById('domain').value, function(data) {
var colorValue = "#272727";
document.getElementById('containerThree').style.backgroundColor = data == "true"?"#20bb47":"#b33535";
document.getElementById('avail').style.color = colorValue;
document.getElementById('emt').style.color = colorValue;
});
BTW, I am not sure how .style = "background-color:#20bb47;"; is working for you.

MVC posting via javascript to controller strange json object behavior

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: "" };
}
};

Javascript data not loading at first time

I have the following code, it have one problem, on first load it wont display anything, but when I press next button on my carousel, everything will work perfectly, so the problem resides somewhere on the first call, as the other calls are exactly the same but theese are working :S
I wont put where the display code, as it is working because it's only jquery adding data to divs and stuff, but as I said, on first time, data is empty.
var dificildecision = function() {
}
dificildecision.prototype = {
is_animating : false,
base_url : window.base_url,
current_decision : null,
decisiones_seen : 0,
historial_decisiones : {
"decisiones" : []
},
is_previous : false,
previous_id : 1,
next_decision : function(replace) {
if (this.is_animating != true) {
this.is_animating = true;
if (this.is_previous) {
decision = this.get_decision(this.previous_id);
} else {
if (this.get_current_decision() === false)
decision_id = 1;
else
decision_id = this.current_decision.id;
this.get_new_decision(decision_id);
decision = this.get_current_decision();
$('#decision-carousel').html("This is: " + decision.key);
this.is_animating = false;
this.is_previous = false;
}
} else {
// console.log("Slow down");
}
},
get_new_decision : function(decision_id) {
if (typeof (decision_id) === "undefined" || decision_id === null) {
decision_id = 1;
}
$.getJSON('http://echo.jsontest.com/key/value', this.set_current_decision);
},
get_current_decision : function() {
return (this.current_decision) ? this.current_decision : false;
},
set_current_decision : function(decision) {
// THIS DOESN'T WORK
this.current_decision = decision;
// THIS WORK SECOND+ TIME EXECUTED
//dificildecision.prototype.current_decision = decision;
}
};
var dificil = new dificildecision();
dificil.next_decision(true);
$('#testlink').on('click', function(){
dificil.next_decision(true);
});
With this code nothing is displayed on console, but if I change
set_current_decision : function(decision) {
this.current_decision = decision;
}
to
set_current_decision : function(decision) {
dificildecision.prototype.current_decision = decision;
}
It outputs the object only when the carousel function is handled, but not at page load...
I've also tried to change
get_new_decision : function(decision_id) {
if (typeof (decision_id) === "undefined" || decision_id === null) {
decision_id = 1;
}
$.getJSON('/~robhunter/dificildecision/web/app_dev.php/new/'
+ decision_id, this.set_current_decision);
},
to
get_new_decision : function(decision_id) {
if (typeof (decision_id) === "undefined" || decision_id === null) {
decision_id = 1;
}
$.getJSON('/~robhunter/dificildecision/web/app_dev.php/new/'
+ decision_id, dificildecision.prototype.set_current_decision);
},
But exactly as original code, nothing is displayed ever :S
You can try it out here http://jsfiddle.net/TUX5a/
Try:
$(document).ready(function() {
// window.dificildecision = new dificildecision();
var dificildecision = new dificildecision();
}
And use this inside your dificildecision.prototype.next_decision
Explanation:
When you declare your function using this line: function dificildecision() in global scope, there will be a new property named dificildecision assigned to your window object.
When you call window.dificildecision = new dificildecision();, this property (a reference to a function) is replaced with an instance
=> this would cause unpredictable behavior in the application and should be avoided.
Update after the OP created a fiddle:
I have checked your fiddle, you have problem with asynchronous nature of ajax. When you call decision = this.get_new_decision();, you fire an ajax request to server to get the decision. And the next line you call decision = this.get_current_decision();, the decision is not set yet ( the callback set_current_decision is not run yet).
There are 2 solutions to this problem:
Use synchronous ajax by using $.ajax function with async: false. However, this solution is not recommended because it will block the browser and degrade user experience.
Use callback or promise API (recommended). Below is a demo how to do this:
DEMO
Return a promise from getJSON
get_new_decision : function(decision_id) {
if (typeof (decision_id) === "undefined" || decision_id === null) {
decision_id = 1;
}
return $.getJSON('http://echo.jsontest.com/key/value', this.set_current_decision);
}
And return it again inside next_decision:
next_decision : function(replace) {
if (this.is_animating != true) {
this.is_animating = true;
if (this.is_previous) {
decision = this.get_decision(this.previous_id);
} else {
if (this.get_current_decision() === false)
decision_id = 1;
else
decision_id = this.current_decision.id;
decision = this.get_new_decision(decision_id);
this.is_animating = false;
this.is_previous = false;
}
} else {
// console.log("Slow down");
}
return decision;//this could be a promise or a value.
},
Use $.when to execute a callback when data is ready, if the parameter is not a promise, the callback will be called immediately (considered it as a resolved promise):
$.when(dificil.next_decision(true)).then(function(decision){
$('#decision-carousel').html("This is: " + decision.key);
});
This code is just a demo of how to use promise API, you may need to restructure your code to make it fit into this programming model.
Actually I've found that I needed to change get_new_decision method to use $.ajax instead of $.getJSON and set async: false to store variable this way
get_new_decision : function(decision_id) {
if (typeof (decision_id) === "undefined" || decision_id === null) {
decision_id = 1;
}
$.ajax({
async : false,
type : 'GET',
url : '/~robhunter/dificildecision/web/app_dev.php/new/'
+ decision_id,
dataType : 'json',
// data: myData,
success : function(data) {
dificildecision.prototype.set_current_decision(data);
}
});
},
And change into set_current_decision method to use this.current_decision = decision; :)
With this change, everything works perfectly!

Categories