Javascript: Access public variable from private function - javascript

I am learning javascript and was trying out some code below. I am calling the below javascript object as
var client=new atrmsClient('6247543');
var val=client.getRosterData();
I get an error on this line:
var postData= {"cmdShow": "Show", "txtEmpId" : EmpId, "txtPeopleSoft_Id": EmpId, "__VIEWSTATE": viewState }
EmpId is undefined. Can anyone tell me what I am doing wrong ?
"use strict";
function atrmsClient(EmployeeId)
{
this.EmpId=EmployeeId;
var siteUrl="http://wncrpma011.japa.ad.aexp.com/TransportRoster/EmployeeReport.aspx";
var getViewState=function()
{
$.ajax
({
type: "GET",
url: siteUrl,
dataType: 'html',
processData: false,
xhrFields:
{
withCredentials: true
}
})
.done(ExtractViewState).fail(errorFunc).always(alwaysFunc);
return "";
};
var SendPostRequest=function(viewState)
{
var postData= {"cmdShow": "Show", "txtEmpId" : EmpId, "txtPeopleSoft_Id": EmpId, "__VIEWSTATE": viewState }
$.ajax
({
type: "POST",
url: siteUrl,
data: postData,
dataType: 'html',
processData: false,
xhrFields:
{
withCredentials: true
}
})
.done(parseRosterData).fail(errorFunc).always(alwaysFunc);
};
var parseRosterData=function(data)
{
console.log(data);
};
var ExtractViewState=function(data)
{
var rawResponse=data;
var viewState=$(rawResponse).find('input[name=__VIEWSTATE]')[0].value;
console.log(viewState);
SendPostRequest(viewState);
};
var errorFunc=function()
{
};
var alwaysFunc=function()
{
};
this.getRosterData=function()
{
var viewStateVal=getViewState();
console.log("calling");
return "";
};
}

You never declare a variable called EmpId.
The only EmpId you have is a property of the atrmsClient instance.
Add
var EmpId = EmployeeId;
… or just use EmployeeId as that is still in scope.

Another solution could be:
function atrmsClient(EmployeeId) {
var that = this;
this.EmpId=EmployeeId;
var SendPostRequest=function(viewState) {
var postData= {"cmdShow": "Show", "txtEmpId" : that.EmpId, "txtPeopleSoft_Id": that.EmpId, "__VIEWSTATE": viewState }
// ...
};
}
It depends if you need EmpId to be available from outside, i.e. using client.EmpId. If yes, then this solution should suit your needs. Otherwise, use #Quentin's.

Related

jQuery post like issue

I wrote this code for like and dislike for my posts in my blog:
$(".p_like").each(function() {
$(this).click(function() {
ids = $(this).find(".pl_id").val();
t = $(this);
if ($(this).find(".bi").hasClass("bi-heart-o")) {
gfd = 'p';
$(this).find(".bi").addClass("bi-heart");
$(this).find(".bi").removeClass("bi-heart-o");
} else {
gfd = 'm';
$(this).find(".bi").addClass("bi-heart-o");
$(this).find(".bi").removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
t.find(".nol").html(result);
}
});
});
});
And when I use the code, in some of the post it likes the post and then dislike it.
What is the problem of the code and how can I fix it?
use this :
$(".p_like").find(".bi").click(function(){
ids = $(this).siblings(".pl_id").val();
t = $(this);
if($(this).hasClass("bi-heart-o")){
gfd='p';
$(this).addClass("bi-heart");
$(this).removeClass("bi-heart-o");
}else{
gfd='m';
$(this).addClass("bi-heart-o");
$(this).removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {ids:ids,k:gfd},
cache: false,
success: function (result) {
t.siblings(".nol").html(result);
}
});
});
and you maybe used this file two time!
Jquery by default query all given selectors ( here .p_like ). It's not needed to iterate over them explicitly.
Jquery methods are chanable. after you select one element you could call methods one after another: $element.addClass(...).removeClass().css(...)
Also you've leaked three variables: ids, t, gfd. maybe they're got overriten before you send em out to server so declare them to make em private to your event handler function.
$('.p_like').click(function() {
var $t = $(this),
$bi = $t.find('.bi'),
$nol = $t.find('.nol'),
ids = $t.find('.pl_id').val(),
gfd;
if ( $bi.hasClass('bi-heart-o') ) {
gfd = 'p';
$bi.addClass('bi-heart').removeClass('bi-heart-o');
} else {
gfd = 'm';
$bi.addClass('bi-heart-o').removeClass('bi-heart');
}
$.ajax({
type: 'POST',
url: 'likes.php',
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
$nol.html(result);
}
});
});

how to submit a form with a local list from javascript

I have a list that i created it in javascript and I want to send it to controller :
function submit1() {
var list_id = [];
var i;
for(i = 0; i < #Model.Count(); i++){
var x =docuzment.getElementsByClassName("bt1")[i].getAttribute("id");
var xxx = document.getElementById(x).style.backgroundColor;
if (xxx == "tomato") {
list_id.push(x);
}
}
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {list_id: String},
success: function (data) { alert("SUCCESS"); }
});
}
controller :
public ActionResult add_invitations(List<string> ls )
{
ViewBag.a = ls.Count();
return View();
}
I always get null reference exception for ls>
You are not passing the correct parameter to the action, it expecting to get a parameter named ls, but in your data object you are passing a parameter named list_id.
Try changing it to this:
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {ls: list_id},
success: function (data) { alert("SUCCESS"); }
});

Getting a 500 internal server error thanks to some javascript in symfony

This is the code:
Controller:
public function isreadAction(Request $request) {
var_dump($request->get('sentValue'));
$em = $this->getDoctrine()->getEntityManager();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBypmid($request->get('sentValue'));
$pm->setIsRead(true);
$em->flush();
return new Response();
}
js:
$(document).ready(function () {
$(".pmcontents").hide();
$(".pmbox").click(function () {
$(this).css("font-weight", "normal");
$(this).next().toggle();
var myValue = $('this').attr('id');
var DATA = 'sentValue=' + myValue;
$.ajax({
type: "POST",
url: Routing.generate('isread'),
data: DATA,
cache: false,
success: function (data) {
alert("database has been updated");
}
});
});
});
Routing:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
options:
expose: true
If i click on the error it says that the variable is undefined:
Parametersapplication/x-www-form-urlencodedNiet sorteren
sentValue undefined
Bron
sentValue=undefined
What is the problem? I have tried some things and it seems that the problem lies within the ajax part of the javascript, but i'm not sure.
Replace
var myValue = $('this').attr('id'); //<- notice quote around this
with
var myValue = $(this).attr('id');

Js variable does not update in ajax

I use jstree and want to reload it with new data but I cannot send it to new data.
var $driver = 0;
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: function () { return '{"driver":"' + $driver + '"}' },
contentType: "application/json"
}
}
});
});
$(document).on('click', '.tile', function () {
var $item = $(this);
var $driver = $item.attr('data-driver');
// alert($driver);
$('#tree_folder').jstree('refresh');
});
I got the new value when clicked, it send old default data every time. Above in alert function, it can give me the right value although json post send default one even data is written with function
function () { return '{"driver":"' + $driver + '"}' }
How can I get the new value from variable?
Remove var before $driver from .tile click function as you are created global previously,
Try this,
$(document).on('click', '.tile', function () {
var $item = $(this);
$driver = $item.attr('data-driver'); // remove var from this line
// alert($driver);
$('#tree_folder').jstree('refresh');
});
Also use cache:false in jstree like,
function getDriver() {
return '{"driver":"' + $driver+ '"}';
}
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
cache: false, // cache false
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: getDriver(), // get updated driver
contentType: "application/json"
}
}
});
});
Also take a look on change ajax options in jstree from server

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Categories

Resources