Save variable from console output Javascript/Python/Jinja2 - javascript

I am using Trello API to create a card. This works fine but while the script runs it prints a ID variable of the newly created card to the console. I'd like to take this variable and pass it back to my python code. Is this possible? I am using Jinja2 to pass variables from Python to HTML, can I use this here?
This is the output to the console in Chrome, I want to grab the first ID variable so I can work with it in my Python code.
{
"id": "5a46fa28620367df83fe08f7",
"badges": {
"votes": 0,
"attachmentsByType": {
"trello": {
"board": 0,
"card": 0
}
},
"viewingMemberVoted": false,
"subscribed": false,
"fogbugz": "",
"checkItems": 0,
"checkItemsChecked": 0,
Here is my Javascript:
var authenticationSuccess = function() {
console.log('Successful authentication');
};
var authenticationFailure = function() {
console.log('Failed authentication');
};
window.Trello.authorize({
type: 'popup',
name: 'Work Requests App',
scope: {
read: 'true',
write: 'true' },
expiration: 'never',
success: authenticationSuccess,
error: authenticationFailure
});
//console.log(trelloTitle);
//console.log(trelloContent);
var myList = '5a3ec86f7920a6e66b28e4bc';
var creationSuccess = function (data) {
console.log('Card created successfully.');
console.log(JSON.stringify(data, null, 2));
};
//var data = $('#resultsdata').data();
//console.log(trelloId);
var newCard = {
name: trelloTitle,
desc: trelloContent,
// Place this card at the top of our list
idList: myList,
idMembers: trelloId,
pos: 'top'
};
window.Trello.post('/cards/', newCard, creationSuccess);
EDIT: I am now using this AJAX method:
var creationSuccess = function (data) {
console.log('Card created successfully.');
console.log(JSON.stringify(data, null, 2));
var url = "/ajaxtest";
$.post(url, {card_id: data.id});
};
I am having difficulty passing card_id into my python method:
class AjaxTest(webapp2.RequestHandler):
def post(self):
data = card_id
I know this is wrong, can anyone help?

Here's the complete answer:
var creationSuccess = function (data) {
console.log('Card created successfully.');
var http = new XMLHttpRequest();
var url = "URL to your server (where you want to send the data)";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send("card_id=" + data.id);
};
This will send the card id as card_id to your server (to the URL you specified) through an AJAX call.
This is assuming that you're only using pure Javascript. If you're using jQuery, then making an AJAX call would be much easier. like:
var creationSuccess = function (data) {
console.log('Card created successfully.');
var url = "URL to your server";
$.post(url, {card_id: data.id});
};
Edit: As for the server code, you could now receive card_id like this:
class AjaxTest(webapp2.RequestHandler):
def post(self):
data = self.request.get('card_id')
Hope that helps.

Related

AJAX Post call no data

Hello wenn i want to send a post request to my Controller there is no data.
I tried to log my Json file and there is something. But when I send the post request my controller shows it is empty.
Here is my call:
var item = {};
var jsonObj = [];
item["ProductCategoryId"] = i;
item["Name"] = txtName;
item["Description"] = txtDescription;
item["Price"] = txtPrice;
item["Stock"] = txtStock;
item["ProductCategory"] = txtProductCategory;
item["Image"] = await getAsByteArray(txtImage);
jsonObj.push(item);
var jsonString = JSON.stringify(jsonObj);
console.log("jsonString : " + jsonString);
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
}
});
//Here I make a breakpoint but my string is empty
public JsonResult SaveProductToDB(string dataToSend)
{
List<Product> _List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(dataToSend);
}
the getAsByteArray
async function getAsByteArray(file) {
return new Uint8Array(await readFile(file))
}
function readFile(file) {
return new Promise((resolve, reject) => {
// Create file reader
let reader = new FileReader()
// Register event listeners
reader.addEventListener("loadend", e => resolve(e.target.result))
reader.addEventListener("error", reject)
// Read file
reader.readAsArrayBuffer(file)
})
}
I found out if I remove the Image. that the controller is then able to resize it. Thanks for the help so far. So I need to look at this place where the problem is.
You are checking against data.status as if it's a given that it exists. Just console.log(data) instead and you will see whether or not status is being returned.
Also, if you open the Network tab in Chrome you can click on the post request & see if your headers are going through accurately and also click on 'Preview' to see an unfiltered result from the controller.
You might want to modify your code to catch errors for debugging, ie:
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
},
error:function (xhr, ajaxOptions, thrownError) {
// Set up whatever error reaction you want, here. ie:
console.log('An error was encountered.');
alert(xhr.status);
alert(thrownError);
}
});
Another tip is to validate empty data being submitted prior to the Ajax call, so you only touch the backend server when your data is valid - to avoid an error.

Storing a variable in ajax response as a global variable and use for sending other ajax requests?

I am getting ajax response as
{ pid: 6, status: true }
I need to store pid and pass it in the next ajax post request.
My current vue js is as follows
submitBox = new Vue({
el: "#submitBox",
data: {
name: '',
gstno: '',
about: '',
pid: '',
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['name'] = this.name;
data['gstno'] = this.gstno;
data['about'] = this.about;
$.ajax({
url: 'alpha/add/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
alert(" Success")
} else {
vm.response = e;
alert(" Failed")
}
}
});
return false;
}
},
});
I need to store pid as a global variable and use the same for all the ajax requests. How can I achieve this?
small thing, if you have small application and there is not much architecture or js is resides on that page only then you can use global variable
using vuex for just this little thing is not suggestible (it will be good if he is already using it)
when you get back ajax response then you can set id globally
if (e.status) {
window._postPid = e.pid; // assume `e` is response and e.pid is 6
}
else {
// according to your need.
// this is optional window._postPid = null;
}
now you can access it anywhere you want using
console.log(window._postPid); // 6
this is not preferred for large scale app. as we dont want to spoil global namespace or conflict variables.
but it will do what you want.

ASP.NET MVC POST Route does not point to the correct Method

I´ve got a problem with my current mvc project.
I´m using an ajax call to send new comments to the server but the method does not even get called.
My js code:
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Threads")';
var threadId = $("#threadId").val();
var msg = $("#answer_msg").val();
alert(actionUrl);
alert(msg);
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: "Message=" + msg + "&threadId=" + threadId,
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
as you see I´ve alerted the url, msg and threadId and they are all correct. url: "/Threads/AnswerThread", msg: "test", threadId: 1.
I´ve already tried to put a breakpoint inside the AnswerThread method but it does not get called. The "AnswerThread" method is inside the "ThreadsController" and looks like this:
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
var userId = User.Identity.GetUserId();
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = Message,
PublishTime = DateTime.Now,
ThreadId = threadId,
UserId = userId
});
db.Complete();
}
return PartialView("/Views/Partial/Clear.cshtml");
}
That´s exactly the same way I did it in the backend controllers but there it just works fine.
I hope somebody can help me..
UPDATE:
Made some changes just to try if any other way works.
Change1 js:
var data = {
threadId: threadId,
Message: msg
};
$.ajax({
url: actionUrl,
type: "POST",
content: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: function (msg) {
if (msg.success == true) {
hideLoadingTab();
location.reload();
}
else
{
alert("Ein Fehler ist aufgetreten: " + msg.error);
}
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
Change 2 c#:
[HttpPost]
public JsonResult AnswerThread([System.Web.Http.FromBody]PostDataModel data)
{
var userId = User.Identity.GetUserId();
string error = "";
bool success = false;
try
{
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = data.Message,
PublishTime = DateTime.Now,
ThreadId = data.threadId,
UserId = userId
});
success = true;
db.Complete();
}
}
catch(Exception ex)
{
error = ex.Message;
}
return Json(String.Format("'Success':'{0}', 'Error':'{1}'", success, error));
I tried this now with and without the "[FromBody]" statement.
Oh yes and I´ve added the DataModel like this:
public class PostDataModel
{
public int threadId { get; set; }
public string Message { get; set; }
}
and I also tried to manually configure the pointed route.
routes.MapRoute(
name: "AnswerThread",
url: "threads/answer",
defaults: new { controller = "Threads", action = "AnswerThread" }
);
The "actionUrl" variable in js get´s changed to /threads/answer but I´m always getting 500 Internal Server Error. When I put a breakpoint inside the method it does not stop at any point of the ajax call.
In the Chrome Dev Tools at the "Network" tab it says to me that there is a parameter called "id" which is null which causes to this 500 internal server error. I tried to find out more information about this but the error does not tell me where this parameter is located.
I´ve got no parameter called "id" inside this method or the data model so where does this come from?
Solution:
My Routes mapping was bad. I first mapped the route /threads/{id} and THEN did /threads/answer so when the /threads/answer got called it thought "answer" is an id so it tried to enter the "Index" method. So for my particular problem (and maybe for some other guys having the same issue) the solution was just to put the mapping of the /threads/answer route in front of the /threads/{id} route and it worked.
Please check your parameter types, in controller threadId is int type and from ajax call you are passing string type.
In Js
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Home")';
var threadId = parseInt($("#threadId").val());
var msg = "Answer message";
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: { Message: msg, threadId: threadId },
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
In Controller
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
return Json("Data");
}

Saving data to server via AJAX not working

having some issues with my save function on knockout. I was following the tutorial on the Knockout site http://jsfiddle.net/rniemeyer/bGsRH/. WHen I implement the code to my site I get an error an error 400 Bad request stating that my JSON data is invalid. After debugging a bit more I see that it`s returning [object, object] instead of my modified JSON data.
To give a little context, I basically have a table with my list of data and each row has their edit button. Upon clicking the edit button it opens a modal and shows the data of the selected item. The issue occurs when I try to modify and then save the data.
Here is my javascript code I have so far, would anyone know what im missing?:
<script type="text/javascript">
function EmployeeModal() {
var self = this;
self.Employees = ko.observableArray([]);
//Start of select/edit functions
//This codes allows to pass selected data to the hidden modal
self.currentEmployee = ko.observable(null);
self.showEmployee = function(vm){
self.currentEmployee(vm);
$('#myModal').modal('show');
};
//END of select/edit functions
//Start of the save function
self.save = function() {
var New_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents';
var UPDATE_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents('+ encodeURIComponent($('#Incident_ID').val())+')';
var createIncidentUrl = $('#Incident_ID').val() != '' ? UPDATE_Incident_URL : New_Incident_URL;
var CREATE_Headers = {"accept": "application/json;odata=verbose"};
var UPDATE_Headers = {"accept" : "application/json;odata=verbose","X-HTTP-Method":"MERGE","If-Match":"*"};
var headertype = $('#Incident_ID').val() != '' ? UPDATE_Headers : CREATE_Headers;
$.ajax(createIncidentUrl, {
data: {
json: ko.toJSON({
Description: this.Description,
Incident: this.Incident
})
},
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
headers: headertype,
success: function(result) {
alert(ko.toJSON(result));
$('#myModal').modal('hide');
}
});
};
//Start - Go get data from Sharepoint.
$.getJSON("../../../../_vti_bin/listData.svc/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc",
function (data) {
if (data.d.results) {
self.Employees(ko.toJS(data.d.results));
}
}
);
//END - Go get data from Sharepoint.
}
$(document).ready(function () {
ko.applyBindings(new EmployeeModal());
});
</script>
EDIT:
Here is an example of my data from the server.
[{
ID: "123",
Description: "The server x is unavailable",
Incident: "1234"
}, {
ID: "124",
Description: "The router located downtown is down",
Incident: "12345"
}, {
ID: "125",
Description: "Fiber optic cable downtown is flapping",
Incident: "123456"
}, {
ID: "126",
Description: "Network unvailable at the beaver site",
Incident: "1234567",
}];

how a javascript scope can be duplicated? by using for loop?

I just had this javascript comet call working properly, but found out i need 30 pieces to do the same function but with different value output. check out my code
<script type="text/javascript">
var Comet = Class.create();
Comet.prototype = {
timestamp: 0,
url: 'backend.php',
noerror: true,
pointname: 'GrossElectricityGeneration',
initialize: function() { },
connect: function()
{
this.ajax = new Ajax.Request(this.url, {
method: 'get',
parameters: { 'timestamp' : this.timestamp, 'pointname': this.pointname},
onSuccess: function(transport) {
// handle the server response
var response = transport.responseText.evalJSON();
this.comett.timestamp = response['timestamp'];
this.comett.handleResponse(response);
this.comett.noerror = true;
},
onComplete: function(transport) {
// send a new ajax request when this request is finished
if (!this.comett.noerror)
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){ comett.connect() }, 5000);
else
this.comett.connect();
this.comett.noerror = false;
}
});
this.ajax.comett = this;
},
disconnect: function()
{
},
handleResponse: function(response)
{
$('page1b').innerHTML = '<div>' + response['msg'] +'</div>';
$('page1c').innerHTML = '<div>' + '67'+'</div>';
},
}
var comett = new Comet();
comett.connect();
</script>
to do this, a silly way is to copy 30 pieces of ... and rename
comett to 30 different name
30 different #('page1a')#('page1b')
and point name
is there any other way that i can use for loop to duplicate 30 copies with differnet variables ?
thanks....

Categories