Django ajax unicode error - mysql

Hi I have a small javascript function which dynamically filters my form:
// set up a new XMLHttpRequest variable
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
// if no request then throw up an alert window
if (!request)
alert("Error initializing XMLHttpRequest!");
// this function takes the island group value and sends it to the url as a get variable
function getIslandName(lang) {
var islandGroup = document.getElementById("id_island_group").value;
if (islandGroup == '') {
// if Not Specified re-selected then set data to null and bypass updatePage()
var data = null;
update_select($('select[name=island_name]'), data);
}
else {
var url = "../collections/find_island?island_group=" + escape(islandGroup);
// alert("Ready state is: " + request.readyState);
// alert("url: " + url);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
}
// what to do when http ready state changes
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
// get response array
var data = JSON.parse(request.responseText);
update_select($('select[name=island_name]'), data);
}
// some error checking
else if (request.status == 404) {
alert("Request url does not exist");
}
else {
alert("Error: status code is " + request.status);
}
}
}
function update_select(select, data) {
// find and remove existing options
select.find('option').remove();
var optionText = document.getElementById("lang").innerHTML
select.append($('<option value>' + optionText + '</option>'));
// loop through results and append to select as options
for (var k in data) {
select.append($('<option value="'+data[k]+'">'+data[k]+'</option>'));
}
}
And my forms:
class SearchForm(forms.Form):
...
island_group = forms.ModelChoiceField(
required=False,
label=ugettext_lazy('Island Group'),
initial=None,
queryset=Localityonline.objects.values_list('islandgroup', flat=True).distinct('islandgroup').exclude(islandgroup=None).order_by('islandgroup'),
empty_label=ugettext_lazy("Not Specified"),
widget=forms.Select(attrs={"class":'searchfield', "onChange":'getIslandName()'})
)
island_name = forms.ChoiceField(
required=False,
label=ugettext_lazy('Island Name'),
initial=None,
choices=DEFAULT_CHOICES,
#queryset = Localitymayor.objects.values_list('islandname', flat=True).distinct('islandname').exclude(islandname="n/a").order_by('islandname'),
#empty_label=ugettext_lazy("Not Specified"),
)
...
The problem is, if the value of islandGroup is something like 'EspaƱola' (i.e latin characters) I get a status 500 error and the following Django error:
OperationalError: (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='")
<WSGIRequest
path:/datazone/collections/find_island/,
GET:<QueryDict: {u'island_group': [u'Espa\ufffd']}>,
POST:<QueryDict: {}>,
COOKIES:{'__utma': '173650102.812455619.1337018914.1337629222.1337641044.38',
'__utmb': '173650102.4.10.1337641044',
'__utmc': '173650102',
'__utmz': '173650102.1337613083.36.2.utmcsr=darwinfoundation.org|utmccn=(referral)|utmcmd=referral|utmcct=/datazone/galapagos-research/search/',
'csrftoken': '7cac07481c8ff5762fac33bf0b3590da',
'sessionid': '4becce44a950091a3cf7d306633427b4'},
META:{'CSRF_COOKIE': '7cac07481c8ff5762fac33bf0b3590da',
'DOCUMENT_ROOT': '/home/darwinfo/public_html',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTP_ACCEPT': '*/*',
'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
'HTTP_CONNECTION': 'close',
'HTTP_COOKIE': 'csrftoken=c297f86b353937f52abc36af8b4d595a; csrftoken=7cac07481c8ff5762fac33bf0b3590da; sessionid=4becce44a950091a3cf7d306633427b4; __utma=173650102.812455619.1337018914.1337629222.1337641044.38; __utmb=173650102.4.10.1337641044; __utmc=173650102; __utmz=173650102.1337613083.36.2.utmcsr=darwinfoundation.org|utmccn=
...
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19',
'PATH': '/sbin:/usr/sbin:/bin:/usr/bin',
'PATH_INFO': u'/collections/find_island/',
'PATH_TRANSLATED': '/home/darwinfo/public_html/collections/find_island/',
'QUERY_STRING': 'island_group=Espa%F1ola',
'REDIRECT_QUERY_STRING': 'island_group=Espa%F1ola',
'REDIRECT_STATUS': '200',
'REDIRECT_UNIQUE_ID': 'T7rLMjIWL2YAAGS3N#sAAAET',
'REDIRECT_URL': '/datazone/collections/find_island/',
'REMOTE_ADDR': '157.100.37.112',
'REMOTE_PORT': '35245',
'REQUEST_METHOD': 'GET',
'REQUEST_URI': '/datazone/collections/find_island/?island_group=Espa%F1ola',
'SCRIPT_FILENAME': '/home/darwinfo/public_html/datazone/django.fcgi',
'SCRIPT_NAME': u'/datazone',
'SERVER_ADDR': '50.22.47.102',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',,
'SERVER_SOFTWARE': 'Apache',
'UNIQUE_ID': 'T7rLMjIWL2YAAGS3N#sAAAET',
'wsgi.errors': <flup.server.fcgi_base.OutputStream object at 0x1707ab90>,
'wsgi.input': <flup.server.fcgi_base.InputStream object at 0x16f2fad0>,
'wsgi.multiprocess': False,
'wsgi.multithread': True,
'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 0)}>
Any help would be much appreciated.

Check the collation type of each table, and make sure that they have the same collation.
After that check also the collation type of each table field that you have use in operation.
I had encountered the same error, and that tricks works .

Related

native messaging host chrome-token-signing

I am trying to make an extension that will communicate with a native messaging host chrome-token-signing (https://github.com/open-eid/chrome-token-signing).
I have installed extension , but the EXE is not started. I have message log TEST: {"message":"Invalid argument","result":"invalid_argument"}
Do I need to do Something
I have installed the host in the registry like
HKEY_LOCAL_MACHINE\software\Google\Chrome\NativeMessagingHosts\ee.ria.esteid
and value C:\Users\dev\Desktop\chrome-token-signing\host-windows\ee.ria.esteid.json
The native application manifest.json:
{
"name": "ee.ria.esteid",
"description": "Give signatures with your eID on the web",
"path": "chrome-token-signing.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://ckjefchnfjhjfedoccjbhjpbncimppeg/"
]
}
manifest.json of extension
{
"name": "Token signing",
"version": "0.0.24",
"minimum_chrome_version": "40.0",
"manifest_version": 2,
"description": "Use your eID smart card on the web",
"icons": {
"48": "icon48.png",
"128": "icon128.png"
},
"content_scripts": [{
"matches": ["*://*/*", "file:///*"],
"exclude_matches": ["*://www.overdrive.com/*"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": true
}],
"background": {
"scripts": ["background.js"]
},
"permissions": ["nativeMessaging"],
"applications": {
"gecko": {
"id": "{443830f0-1fff-4f9a-aa1e-444bafbc7319}"
}
}
}
background.js
var NO_NATIVE_URL = "https://open-eid.github.io/chrome-token-signing/missing.html";
var HELLO_URL = "https://open-eid.github.io/chrome-token-signing/hello.html";
var DEVELOPER_URL = "https://github.com/open-eid/chrome-token- signing/wiki/DeveloperTips";
var NATIVE_HOST = "ee.ria.esteid";
var K_SRC = "src";
var K_ORIGIN = "origin";
var K_NONCE = "nonce";
var K_RESULT = "result";
var K_TAB = "tab";
var K_EXTENSION = "extension";
// Stores the longrunning ports per tab
// Used to route all request from a tab to the same host instance
var ports = {};
// Probed to false if host component is OK.
var missing = true;
console.log("Background page activated");
// XXX: probe test, because connectNative() does not allow to check the presence
// of native component for some reason
typeof chrome.runtime.onStartup !== 'undefined' && chrome.runtime.onStartup.addListener(function() {
// Also probed for in onInstalled()
_testNativeComponent().then(function(result) {
if (result === "ok") {
missing = false;
}
});
});
// Force kill of native process
// Becasue Port.disconnect() does not work
function _killPort(tab) {
if (tab in ports) {
console.log("KILL " + tab);
// Force killing with an empty message
ports[tab].postMessage({});
}
}
// Check if native implementation is OK resolves with "ok", "missing" or "forbidden"
function _testNativeComponent() {
return new Promise(function(resolve, reject) {
chrome.runtime.sendNativeMessage(NATIVE_HOST, {}, function(response) {
if (!response) {
console.log("TEST: ERROR " + JSON.stringify(chrome.runtime.lastError));
// Try to be smart and do some string matching
var permissions = "Access to the specified native messaging host is forbidden.";
var missing = "Specified native messaging host not found.";
if (chrome.runtime.lastError.message === permissions) {
resolve("forbidden")
} else if (chrome.runtime.lastError.message === missing) {
resolve("missing");
} else {
resolve("missing");
}
} else {
console.log("TEST: " + JSON.stringify(response));
if (response["result"] === "invalid_argument") {
resolve("ok");
} else {
resolve("missing"); // TODO: something better here
}
}
});
});
}
// When extension is installed, check for native component or direct to helping page
typeof chrome.runtime.onInstalled !== 'undefined' && chrome.runtime.onInstalled.addListener(function(details) {
if (details.reason === "install" || details.reason === "update") {
_testNativeComponent().then(function(result) {
var url = null;
if (result === "ok" && details.reason === "install") {
// Also set the flag, onStartup() shall be called only
// on next startup
missing = false;
// TODO: Add back HELLO page on install
// once there is a nice tutorial
url = HELLO_URL;
} else if (result === "forbidden") {
url = DEVELOPER_URL;
} else if (result === "missing"){
url = NO_NATIVE_URL;
}
if (url) {
chrome.tabs.create({'url': url + "?" + details.reason});
}
});
}
});
// When message is received from page send it to native
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(sender.id !== chrome.runtime.id && sender.extensionId !== chrome.runtime.id) {
console.log('WARNING: Ignoring message not from our extension');
// Not our extension, do nothing
return;
}
if (sender.tab) {
// Check if page is DONE and close the native component without doing anything else
if (request["type"] === "DONE") {
console.log("DONE " + sender.tab.id);
if (sender.tab.id in ports) {
// FIXME: would want to use Port.disconnect() here
_killPort(sender.tab.id);
}
} else {
request[K_TAB] = sender.tab.id;
if (missing) {
_testNativeComponent().then(function(result) {
if (result === "ok") {
missing = false;
_forward(request);
} else {
return _fail_with (request, "no_implementation");
}
});
} else {
// TODO: Check if the URL is in allowed list or not
// Either way forward to native currently
_forward(request);
}
}
}
});
// Send the message back to the originating tab
function _reply(tab, msg) {
msg[K_SRC] = "background.js";
msg[K_EXTENSION] = chrome.runtime.getManifest().version;
chrome.tabs.sendMessage(tab, msg);
}
// Fail an incoming message if the underlying implementation is not
// present
function _fail_with(msg, result) {
var resp = {};
resp[K_NONCE] = msg[K_NONCE];
resp[K_RESULT] = result;
_reply(msg[K_TAB], resp);
}
// Forward a message to the native component
function _forward(message) {
var tabid = message[K_TAB];
console.log("SEND " + tabid + ": " + JSON.stringify(message));
// Open a port if necessary
if(!ports[tabid]) {
// For some reason there does not seem to be a way to detect missing components from longrunning ports
// So we probe before opening a new port.
console.log("OPEN " + tabid + ": " + NATIVE_HOST);
// create a new port
var port = chrome.runtime.connectNative(NATIVE_HOST);
// XXX: does not indicate anything for some reason.
if (!port) {
console.log("OPEN ERROR: " + JSON.stringify(chrome.runtime.lastError));
}
port.onMessage.addListener(function(response) {
if (response) {
console.log("RECV "+tabid+": " + JSON.stringify(response));
_reply(tabid, response);
} else {
console.log("ERROR "+tabid+": " + JSON.stringify(chrome.runtime.lastError));
_fail_with(message, "technical_error");
}
});
port.onDisconnect.addListener(function() {
console.log("QUIT " + tabid);
delete ports[tabid];
// TODO: reject all pending promises for tab, if any
});
ports[tabid] = port;
ports[tabid].postMessage(message);
} else {
// Port already open
ports[tabid].postMessage(message);
}
}
The native app is started and it replies to you that the arguments you give it are invalid.
You need to check with native app documentation and see what arguments are valid for that particular app and use them in the messages you send it from the extension. Your request will look like:
chrome.runtime.sendNativeMessage(NATIVE_HOST, {text: "some_valid_argument"}, function(response){
........

Ajax Internal Server Error in Yii2

View urlCreate code
$ajaxSaveTestGrid = Yii::$app->urlManager->createUrl('testgrid/ajaxsave');
This Is My View Ajax Code
function saveRow(id, index) {
if(id == 'tbl_testGrid') {
save(id, index);
}
}
function save(id, index) {
var testGrid_name = $('#testGrid_name' + index).val();
var testGrid_qty = $('#testGrid_qty' + index).val();
var testGrid_price = $('#testGrid_price' + index).val();
var url = '$ajaxSaveTestGrid';
// alert(testGrid_name+testGrid_qty+testGrid_price);
$.ajax({
type: 'GET',
url: url,
data: {
testGrid_name:testGrid_name,
testGrid_qty:testGrid_qty,
testGrid_price:testGrid_price
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
if(response == 'error') {
alert('Fail to save! Please try again');
} else {
$('#testGrid_name' + index).attr(\"disabled\",true);
$('#testGrid_qty' + index).attr(\"disabled\",true);
$('#testGrid_price' + index).attr(\"disabled\", true);
$('#testGrid_save_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_delete_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_edit_button' + index).attr(\"class\", \"show\");
$('#hid_testGrid_id' + index).val(response[0].testgrid.id);
$('html,body').animate({scrollTop: $('#btn_testGrid').offset().top});
}
}
});
}
This is my Controller
public function actionAjaxsave() {
$result = array();
$testGrid_name = $_GET['testGrid_name'];
$testGrid_qty = $_GET['testGrid_qty'];
$testGrid_price = $_GET['testGrid_price'];
$model = new Testgrid();
$model->name = $testGrid_name;
$model->price = $testGrid_price;
$model->qty = $testGrid_qty;
if ($model->save()) {
array_push($result, ['testgrid' => $model]);
$result = Json::encode($result);
echo $result;
} else {
echo 'error';
}
}
It occurring Internal Server Error
I want to save json Data to model.
Internal Server Error means that your code has fatal errors and error displaying is turned off. If you want to see the error itself, you must enable error displaying.
Check out the following question with its answers: How do I get PHP errors to display?
After you see the error, you can fix it.
PS:
$testGrid_name = $_GET['testGrid_name'];
This is not a recommended way to access GET variables. Use Yii::$app->request->get('testGrid_name') instead

Setting data in viewModel knockoutjs from html5 websocket

I am trying to create knockout.js component that is getting data from HTML5 Websocket. Websocket code is in separate script e.g. util.js. I am able to connect and get data from socket, but dont know how correctly to set corresponding property in component`s ViewModel.
Websocket - util.js:
var options = {
server: '127.0.0.1',
port: '12345'
};
var socket, loadedFlag;
var timeout = 2000;
var clearTimer = -1;
var data = {};
function handleErrors(sError, sURL, iLine)
{
return true;
};
function getSocketState()
{
return (socket != null) ? socket.readyState : 0;
}
function onMessage(e)
{
data=$.parseJSON(e.data);
// ???? Is it possible to have here something like
// ???? viewModel.getDataWS1(data);
}
function onError()
{
clearInterval(clearTimer);
socket.onclose = function () {
loadedFlag = false;
};
clearTimer = setInterval("connectWebSocket()", timeout);
}
function onClose()
{
loadedFlag = false;
clearInterval(clearTimer);
clearTimer = setInterval("connectWebSocket()", timeout);
}
function onOpen()
{
clearInterval(clearTimer);
console.log("open" + getSocketState());
}
function connectWebSocket()
{
if ("WebSocket" in window)
{
if (getSocketState() === 1)
{
socket.onopen = onOpen;
clearInterval(clearTimer);
console.log(getSocketState());
}
else
{
try
{
host = "ws://" + options.server + ":" + options.port;
socket = new WebSocket(host);
socket.onopen = onOpen;
socket.onmessage = function (e) {
onMessage(e);
};
socket.onerror = onError;
socket.onclose = onClose;
}
catch (exeption)
{
console.log(exeption);
}
}
}
}
Component (productDisplay.js) - creating so that is can be used on multiple pages:
define([
'jquery',
'app/models/productDisplayModel',
'knockout',
'mapping',
'socket'
],
function ($, model, ko, mapping) {
ko.components.register('product', {
viewModel: {require: 'app/models/productModel'},
template: {require: 'text!app/views/product.html'}
});
});
Product ViewModel (productModel.js) - where I struggle to set viewModel property to data from websocket:
var viewModel = {};
define(['knockout', 'mapping', 'jquery'], function (ko, mapping, $) {
function Product(name, rating) {
this.name = name;
this.userRating = ko.observable(rating || null);
}
function MyViewModel() {
this.products = ko.observableArray(); // Start empty
}
MyViewModel.prototype.getDataWS1 = function () {
//Websocket has not connected and returned data yet, so data object is empty
// ???? Is there anyway I can add something like promise so that the value is set once socket is connected?
this.products(data);
};
// apply binding on page load
$(document).ready(function () {
connectToServer1();
viewModel = new MyViewModel();
ko.applyBindings(viewModel);
viewModel.getDataWS1();
});
});
Thank you for any ideas.
You can update an observable when you get a message in the following manner:
util.js
function onMessage(e) {
var productData = $.parseJSON(e.data);
viewModel.addNewProduct(productData);
}
productModel.js
function Product(name, rating) {
this.name = name;
this.userRating = ko.observable(rating || null);
}
function MyViewModel() {
this.products = ko.observableArray(); // Start empty
}
MyViewModel.prototype.addNewProduct(product) {
var newProduct = new Product(product.name, product.rating);
this.products.push(newProduct);
}
Basically the idea is that when you get a message (in onMessage function), you will parse the data and call a function in your viewmodel to add the message data to the viewmodel properties (observables, observableArrays, etc.)

Unable to dynamically load Json Arrays from JSP to a Jstree

I was trying to make a simple LDAP client to just retrieve the data from an LDAP server. I am returning array of JSON objects from the JSP. On click of any value I will get some data from online server. I am able to load the first set of array into a tree. The arrays got in the next step dont get attached to the JSTree. My codes:
function getGroupsStructure(id) {
console.log("in getGroupsStructure-->");
var paramId = "";
if(id == '') {
console.log("in if-->");
paramId = "c=de";
} else {
console.log("in else-->");
paramId = id;
}
var params = {
"DN" : paramId,
};
console.log("params-->",params);
var getGroupsStructureForUserService = service(webURL + "sendingValues/getGroupsStructureForUser",params,"POST");
getGroupsStructureForUserService.success(function(data) {
console.log("in success-->dta-->",data);
if(data.errorCode == '0') {
console.log("in error code 0-->dta-->",data.treeData);
$('.treeNode').jstree({
'core': {
'data': function (obj, cb) {
cb.call(this,
data.treeData);
}
}
});
console.log("Tree Created...");
} else {
console.log("error code not 0--data-->",data);
}
$(document).off('click').on('click', '.treeNode a', function() {
console.log("on click of a-->");
var id = $(this).parent().attr('id');
console.log("id-->",id);
getGroupsStructure(id);
console.log("after getGroupsStructure");
});
});
getGroupsStructureForUserService.error(function(data) {
console.log(" empty error");
// console.log(err);
});
}
The JSP Code is
def NextLevelLDAP(String DN) {
// println "Next Level===>"
assert ldap!=null
def responseArray=[]
def results=ldap.search('objectClass=*',DN,SearchScope.ONE) //Will be triggered when + is pressed in GUI to get next level of tree
// assert results==null
if(DN.startsWith("c="))
{
JSONObject responseJson1=new JSONObject()
responseJson1.put("id", initialDN )
responseJson1.put("parent", "#")
responseJson1.put("text","Parent")
responseArray.add(responseJson1)
for(entry in results) {
// println entry
// println "In NextLevel Using InitialDN"
JSONObject responseJson=new JSONObject()
responseJson.put("id", entry.dn)
responseJson.put("parent", DN)
String tempResDN=entry.dn.toString()
def tempLength=tempResDN.length() - DN.length()
// println tempResDN
String tempName=tempResDN.substring(2,tempLength-1)
// println tempName
responseJson.put("text",tempName)
responseArray.add(responseJson)
// println entry
println responseJson.toString()
}
return responseArray
}
if(results.size!=0)
{
for(entry in results) {
println entry
JSONObject responseJson=new JSONObject()
responseJson.put("id", entry.dn)
responseJson.put("parent", DN)
String tempResDN=entry.dn.toString()
def tempLength=tempResDN.length() - DN.length()
// println tempResDN
String tempName=tempResDN.substring(2,tempLength-1)
println tempName
responseJson.put("text",tempName)
responseArray.add(responseJson)
// println entry
}
return responseArray
}
}
Please Ignore the way of getting the Parent ID. Its Something COmplicated.
Please help me out how do I get The tree nodes created dynamically. I am just getting the fist level of the tree. The data on click for other levels is being shown in the console but not getting attached to the tree.
Thank you.
You have it the other way around - you need to create the tree and have it make the request for you, so instead of this:
'data': function (obj, cb) {
cb.call(this, data.treeData);
}
Use something like this:
'data': function (obj, cb) {
// you probably need to pass the obj.id as a parameter to the service
// keep in mind if obj.id is "#" you need to return the root nodes
service(...).success(function (data) {
cb.call(this, data.treeData);
});
}
This way you do not need to detach and reattach click handlers every time and it will work out of the box for opening nodes. If you want to open a node on click, you can use this:
$('#tree').on('select_node.jstree', function (e, data) {
data.instance.open_node(data.node);
});
So your whole code should look something like this:
function load(id) {
var params = {
"DN" : id && id !== '#' ? id : "c=de"
};
return service(webURL + "sendingValues/getGroupsStructureForUser", params, "POST");
}
$('#tree')
.jstree({
'core' : {
'data': function (obj, cb) {
load(obj.id).success(function (data) {
cb.(data.treeData);
});
}
}
})
.on('select_node.jstree', function (e, data) {
data.instance.open_node(data.node);
});
Just make sure you mark the nodes your return as having children (set their children property to boolean true).

Using MongoJs and Node.JS to store data

I have successfully connected to MongoDb and used a form to send some data. I would now like to store the data in a json document with a collection. So my current output is:
{
"_id": "53be957007d2c838083046a6",
"subscriberinfo": "X",
"grouporpolicynumber": "X",
"title": "X",
"clientnumber": "X",
"xnumber": "X",
"postedOn": "2014-07-10T13:30:24.499Z"
}
I would like it to look like:
{
"_id": "53be957007d2c838083046a6",
"ReferenceInfo": {
"subscriberinfo": "00003",
"grouporpolicynumber": "Direct",
"title": "SNP",
"clientnumber": "VG00003M",
"HICnumber": "264134187C"
}
"postedOn": "2014-07-10T13:30:24.499Z"
}
Current code looks like this:
function postNewJob(req , res , next){
var job = {};
job.subscriberinfo = req.params.subscriberinfo;
job.grouporpolicynumber = req.params.grouporpolicynumber;
job.title = req.params.clientreportingcategory;
job.clientnumber = req.params.clientnumber;
job.HICnumber = req.params.hicnumber;
job.postedOn = new Date();
res.setHeader('Access-Control-Allow-Origin','*');
memberInfo.save(job , function(err , success){
console.log('Response success '+success);
console.log('Response error '+err);
if(success){
res.send(201 , job);
return next();
}else{
return next(err);
}
});
}
Have you tried something like this?
function postNewJob(req , res , next){
var job = {
referenceInfo: {
subscriberinfo : req.params.subscriberinfo,
grouporpolicynumber : req.params.grouporpolicynumber,
title : req.params.clientreportingcategory,
clientnumber : req.params.clientnumber,
HICnumber : req.params.hicnumber
},
postedOn: new Date();
};
res.setHeader('Access-Control-Allow-Origin','*');
memberInfo.save(job, function(err, job){
if(err) {
console.error('Response error ' + err);
next(err);
} else {
console.log('Response success ' + job);
res.send(201, job);
next(req, res);
}
});
}
On another note, I changed around your callback function that's passed in to save. Mongo will call the function, passing in error and data (data in this case being job) which allows you to conditionally log error or success depending on the status of the save. Also, because those are asynchronous functions, returning the call of next() will not actually impact the code. Also, when calling next(), it is advisable to pass along the req and res from before, so that more actions can be taken from that data.
Hope that helps!