Assigning global variable to following Javascript - javascript

How can we make the var modal = $("#modal"); a global variable?
Where we have the modal variable in the following code, we need it to work, it currently doesn't,
var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";
Many, many thanks!
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
})
$("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});
});

The simple solution for making value global is:
window.modal = "Value";
If you actually don't really need it but just want to store it in a way, where multiple functions will have an access to it you can create it in the scope of the function like:
(function(){
var modal = "value";
$.ajax({
success: function() {
console.log(modal);
}
})
})()

Related

Full calendar not showing events generated dynamically

My events are not getting displayed on fullcalendar. I am fetching the list of events from the backend server using nodejs. the events are getting generated dynamically. I am able to get the events in array but t he events are not showing on the calendar. Any help would be appreciated
function searchappointmentssss(forappdate) {
$.ajax({
url: 'http://localhost:3000/searchappointment',
type: 'post',
data: {
date: forappdate
},
dataType: 'json',
success: function(data) {
var aaaaaaa = [];
data.forEach(function(dataa) {
var ddddddd = dataa.date.split("T");
var appppppp = {};
appppppp.title = dataa.patientname + "\n" + dataa.purposeofvisit;
appppppp.description = dataa.purposeofvisit;
appppppp.start = ddddddd[0] + " " + dataa.time;
appppppp.end = ddddddd[0] + " " + dataa.endtime;
appppppp.id = dataa.appointmentid;
appppppp.visstatus = dataa.status;
appppppp.gicid = dataa.gic;
aaaaaaa.push(appppppp);
});
console.log(aaaaaaa);
$('#calendar').fullCalendar({
defaultView: "agendaDay",
defaultDate: "2018-10-26",
events: aaaaaaa,
eventTextColor: '#ffffff',
header: {
left: 'prev,next',
center: 'title',
right: ''
},
viewRender: function(view, element) {
var newddddddd = moment($('#calendar').fullCalendar('getDate')).format("YYYY-MM-DD");
searchappointmentssss(newddddddd);
$("#dateselectedforapp").val(newddddddd + "T00:00");
},
eventClick: function(calEvent, jsEvent, view) {
$("#exampleModal2").modal('toggle');
$("#message-textm4").val(calEvent.id);
$("#message-textm444").val(calEvent.gicid);
$("#message-textm").val(calEvent.description);
$("#message-textm6").val(calEvent.visstatus);
$("#message-textm99").val(moment(calEvent.start).format("YYYY-MM-DD"));
$("#message-textm2").val(moment(calEvent.start).format("hh:mm"));
$("#message-textm3").val(moment(calEvent.end).format("hh:mm"));
// change the border color just for fun
$(this).css('border-color', 'red');
}
});
//document.execCommand("InsertImage", false, "upload/"+data);
//alert(data);
//$("#progressbar").hide();
//location.reload();
//$("#article").load("submitArticle.php");
//window.location.href = window.location.href;
},
error: function() {
alert(data);
}
});
}
Ps: Just putting this text cos stackoverflow was saying you question contains only code. this is not relevant :P

How do i use a custom button to send to the JQGrid's editurl?

I have the below custom button added to my navigation pager, but i want it to look at what i multi selected and send it to the JQGrid's editurl for processing which is a ASHX.CS page
But i can't make sense of the documentation when it comes to custom button
I can get it call a local function with onClickButton: customButtonClicked but it doesn't send the data like the EDIT button does
In the end what i want to do it select multiple rows and press a button on the navbar and approve all the selected records
// add first custom button
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-mail-closed",
title: "Send Mail",
caption: "Send Mail",
position: "last",
editData: {
WrkId: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
}
return value;
},
CurrentUser: function () {
return '<% =System.Web.HttpContext.Current.User.Identity.Name %>';
}
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#jQGrid").trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')
return [true, response.responseText]
}
}
}
);
using a few different words (how to manually post data to server json) i was able to find a snippet of an ajax code that made more sense (i'm sure i came across this before but as someone who has no jquery experience i didn't recognize it)
but the below sends to the C# handler page the data in a JSON string that was processable, had to use dynamic to read it in but it worked, couldn't get it to not return an error even though there was no error, so i used the complete: instead of success: and then called the trigger to reload the JQGrid
Final Code:
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-check",
title: "Approve all selected entries",
caption: "Approve",
position: "last",
onClickButton: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
};
$.ajax({
type: "POST",
url: "AdministrationHandler.ashx?oper=approve",
data: JSON.stringify({
WrkId: value,
CurrentUser: "<% =System.Web.HttpContext.Current.User.Identity.Name %>"
}),
dataType: "json",
contentType: "application/json; charsset=utf-8",
complete: function (xhr, x) {
if (xhr.responseText.toUpperCase().indexOf("SUCCESS") >= 0) {
alert('Success!\n' + xhr.responseText);
}
else {
alert('Failed!\n' + xhr.responseText + '\n' + x);
};
$("#jQGrid").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
})
}
});
C# Code
try
{
String postData = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
var data = JsonConvert.DeserializeObject<dynamic>(postData);
Approve(data.WrkId.ToString(), data.CurrentUser.ToString());
strResponse = "Employee records successfully approved";
}
catch
{
strResponse = "Employee records not approved";
}
context.Response.Write(strResponse);

Error Loading the following Javascript

Could someone please tell me what's wrong with the following code. I'm guessing it has something to do with missing brackets for the Javascript, but I can't put my finger on it. We're using Full Calendar + Mandrill
Thanks a lot!
$(window).load(function() {
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
jQuery(function($) {
$("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello "+name+ ", You have signed "+modal+ " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});
});
});
});
}); //]]>
First your code should have proper indentation,
You have some errors in the closing of braces and like so for eg: you have an extra closing brace in ajax call and few others, which I have corrected and pasted.
$(window).load(function() {
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
)}
jQuery(function($) {
$("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello "+name+ ", You have signed "+modal+ " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});
});
});
Please check now.
This is what you expect ?
$(window).load(function () {
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function (event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
});
});
});
jQuery(function ($) {
$("#contact_form").submit(function () {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
})
.done(function (response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function (response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});

(#3) App must be on whitelist facebook

I'm trying to post a messsage to a wall using FB.api
My perms are: 'email, read_stream, publish_stream' and my code is:
FB.getLoginStatus(function(response){
if(response.session) {
var accessToken = response.session.access_token;
var tokenUrl = "https://graph.facebook.com/me/feed?access_token=" + accessToken + "&callback=?";
var shareUserId = document.getElementById("shareHidden").value;
var shareTxtAreaMsg = document.getElementById("shareTxtArea").value;
console.log("friends user Id: " + shareUserId + " & " + "message: " + shareTxtAreaMsg);
var data = {
message: "shareTxtAreaMsg",
display: 'iframe',
caption: "Caption",
name: "Name",
picture: 'http://someDomain.com/Dev/img/share-force-wall-img.jpg',
link: "http://www.facebook.com/pages/someapp/XXXXXXXXXXX?sk=app_XXXXXXXXXXXXXX", // Go here if user click the picture
description: "Description field",
actions: [{ name: 'action_links text!', link: 'some link' }],
}
console.log(accessToken);
FB.api(tokenUrl, 'post', data, function(response){
if (response)
{
//console.log(response);
if (response.error)
{
console.log(response.error.message);
}
else
{
if (response.id)
console.log("Posted as post_id "+response.id);
else if (response.post_id)
console.log("Posted as post_id "+response.post_id);
else
console.log("Unknown Error");
}
}
});
}
});
When when try to post the message I'm getting a "(#3) App must be on whitelist" returned. Why is this happening?
Try FB.api('/me/feed'... instead of tokenUrl because FB.api will automatically add the full url prefix.

How to display the searched data on the jgrid

this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:
filter = ''; //this is my global variable for storing filters
$('#btnsearchCode').click(function(){
var row_data = '';
var par = {
"SessionID": $.cookie("ID"),
"dataType": "data",
"filters":[{
"name":"code",
"comparison":"starts_with",
"value":$('#searchCode').val(),
}],
"recordLimit":50,
"recordOffset":0,
"rowDataAsObjects":false,
"queryRowCount":true,
"sort_descending_fields":"main_account_group_desc"
}
filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
$('#list1').setGridParam({
url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)),
datatype: Settings.ajaxDataType,
});
$('#list1').trigger('reloadGrid');
$.ajax({
type: 'GET',
url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
dataType: Settings.ajaxDataType,
success: function(data) {
if ('error' in data){
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
if ( (JSON.stringify(data.result.main.row)) <= 0){
alert('code not found');
}
else{
var root=[];
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
});
root[rowIndex] = row;
row_data += JSON.stringify(root[rowIndex]) + '\r\n';
});
}
alert(row_data); //this alerts all the data that starts with the inputed text...
}
}
});
}
i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:
$.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("ID"),
'dataType': 'data',
'filters': filter,
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
});
now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)
I modified your code based on the information from both of your questions. As the result the code will be about the following:
var myGrid = $("#list1");
myGrid.jqGrid({
datatype: 'local',
url: 'json.php',
postData: {
path: 'data/view'
},
jsonReader: {
root: function(obj) {
var root = [], fields;
if (obj.hasOwnProperty('error')) {
alert(obj.error['class'] + ' error: ' + obj.error.msg);
} else {
fields = obj.result.main.metadata.fields;
$.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
row[fields[columnIndex].name] = rowArrayValue;
});
root.push(row);
});
}
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var filter = JSON.stringify([
{
name:'main_account_group_code',
comparison:'starts_with',
value:$('#searchCode').val()
}
]);
var jsonParams = {
SessionID: $.cookie("ID"),
dataType: 'data',
filters: filter,
recordLimit: postData.rows,
recordOffset: postData.rows * (postData.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_descending_fields:'main_account_group_desc',
sort_fields: postData.sidx
};
return $.extend({},postData,{json:JSON.stringify(jsonParams)});
},
loadError: function(xhr, msg, e) {
alert('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Code', 'Description','Type'],
colModel:[
{name:'code'},
{name:'desc'},
{name:'type'}
],
rowNum:10,
viewrecords: true,
rowList:[10,50,100],
pager: '#tblDataPager1',
sortname: 'desc',
sortorder: 'desc',
loadonce:false,
height: 250,
caption: "Main Account"
});
$("#btnsearchCode").click(function() {
myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});
You can see the code live here.
The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.
By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.
prmNames: { rows: "recordLimit" }

Categories

Resources