Retrieve messages on Page load Strophe js - javascript

I am trying to retrieve the messages whenever Uses logs in and the page loads. Right now I can able to retrieve the messages whenever the User sends the message to other User i.e., with the onMessage function.
Here is my code:
var archive = [];
// Retrives the messages whenever User sends the messages to Other User.
// TODO: Should be better when User logins and page loads
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0]),
avatar:'images/default_avatar_image.png'
};
archive.val(archive.val() + msg_data.from + ":" + msg_data.message + "\n" + msg_data.to + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q,data:data,response:response});
}
};
console.log('xmpp.history.start',{query:q});
function onMessage(msg) {
// Calls whenever User receives the messages
// and shows the received message in messagebox
var fromJid = msg.getAttribute("from"),
bareFromJid = Strophe.getBareJidFromJid(fromJid),
type = msg.getAttribute("type"),
elems = msg.getElementsByTagName("body");
if (type == "chat" && elems.length > 0) {
var body = elems[0],
message = Strophe.getText(body);
showMessage(bareFromJid + ": " + message);
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}
return true;
}
function send() {
// Calls whenever User sends the messages
// and shows the message in messagebox
var to = $('#to-jid').get(0).value,
myBareJid = Strophe.getBareJidFromJid(connection.jid);
message = $('#message').val(),
reply = $msg({to: to, type: 'chat'})
.c("body")
.t(message);
connection.send(reply.tree());
showMessage(myBareJid + ": " + message);
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
archive = $("#archive-messages");
archive.val("");
connection.rawInput = function (data) { log('RECV: ' + data); };
connection.rawOutput = function (data) { log('SEND: ' + data); };
Strophe.log = function (level, msg) { log('LOG: ' + msg); };
$("#send").bind('click', send);
});
So what happens in my code is whenever User receives the message, then all the messages be retrieved between those two Users.
How can I retrieve the messages in the chat box when I clicked on the particular User??

There were two issues in this. One is when I perform auto login with login() method when scripts loads, it at least takes 800ms to login and perform other actions. At this point I was facing the issue and also bit jQuery part.
Here is my code:
// Retrives the messages between two particular users.
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0])
};
var login_user = connection.jid.split('#')[0];
var username = msg_data.from.split('#')[0];
if(login_user == username) {
archive.val(archive.val() + "me:".capitalizeFirstLetter() + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
else {
archive.val(archive.val() + username.capitalizeFirstLetter() + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q, response:response});
}
};
$("#to-jid").change(function() {
$("#archive-messages").val("");
var to = {"with": $(this).val()};
$.extend(q, to);
// It takes around 800ms to login. So after this timeout we have to retrieve the messages of particular User.
setTimeout(function(){
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}, 1000);
});

Related

Word Web-Addin: getSliceAsync() only return First Slice of data

I am developing an office 365 word web addin, wherein I need to upload the currently opened document to my server. For which I am trying to get the file data using following code.
The method getSliceAsync() is returning only first slice of data.
On debugging it gives "Addin Error: Sorry, we had to restart because this addin wasn't responding" while getting second slice.
I am using this link for reference : [https://learn.microsoft.com/en-us/office/dev/add-ins/word/get-the-whole-document-from-an-add-in-for-word][1]
Here is my code:
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 }, function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then result.value will return a valid File Object
var myFile = result.value;
var filename1 = myFile.name;
console.log(filename1);
var sliceCount = myFile.sliceCount;
var slicesReceived = 0, isAllSlicesSuccess = true, docdataSlices = [];
// document.getElementById("result").innerText = "File size:" + myFile.size + "#Slices: " + sliceCount;
console.log(" File size:" + myFile.size + " #Slices: " + sliceCount, "");
makeProgress(20);
// Iterate over the file slices
for (var i = 0; i < sliceCount && isAllSlicesSuccess; i++) {
var diffPercent = ((i / sliceCount) * 100);
myFile.getSliceAsync(i, function (sliceResult) {
if (sliceResult.status == "succeeded") {
if (!isAllSlicesSuccess) { // Some slice has failed to get, no need to continue
console.log("Error", "One slice failed to get");
return;
console.log(sliceResult);
}
console.log('sliceResult', sliceResult);
console.log("Success", "i: " + i);
console.log("++slicesReceived ",slicesReceived );
console.log(" sliceCount",sliceCount );
console.log("++slicesReceived == sliceCount",slicesReceived == sliceCount);
// One chunk was got, store it in a temporal array
// ++slicesReceived;
// or you can do something with the chunk, such as sent it to a third party server
docdataSlices[sliceResult.value.index] = sliceResult.value.data;
if (++slicesReceived == sliceCount) {
getAllSlicesTime = Date.now();
var performance = (getAllSlicesTime - startTime) / 1000.0;
console.log("Success", "All slices has been get, Seconds: " + performance);
// All slices have been received
myFile.closeAsync(function (closeRes) {
if (closeRes.status == "succeeded") {
console.log("Close Success", "Success");
// DUClick();
}
else {
console.log("Close Error", closeRes.error.message);
}
});
onGetAllSlicesSucceeded(docdataSlices, false);
}
}
else {
isAllSlicesSuccess = false;
myFile.closeAsync(function (closeRes) {
if (closeRes.status == "succeeded") {
console.log("Close Success", "Success");
// DUClick();
}
else {
console.log("Close Error", closeRes.error.message);
}
});
console.log("Get Slice Error:", sliceResult.error.message);
}
});
}
}
else {
getFileTime = Date.now();
var performance = (getFileTime - startTime) / 1000.0;
console.log('Get File Error:', "Seconds: " + performance + " " + result.error.message);
}
});
Please suggest! Thanks in advance!
[1]: https://learn.microsoft.com/en-us/office/dev/add-ins/word/get-the-whole-document-from-an-add-in-for-word

Confused with the callback

I have got a node js program as below.
msg = "Generate a number......";
sessionAttributes = {};
console.log("Session arreubs are :" + sessionAttributes);
console.log("end of flow");
callback(close(intentRequest.sessionAttributes, "Fulfilled", buildMessage(msg)));
here is my close callback
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: "Close",
fulfillmentState,
message,
},
};
}
when I run this, I get the output as Generate a number....... But now I need to integrate this with an API call. and the updated code is as below.
var service = require("./service.js");
service.createIncident(enterpriseID, shortDesc,
function (incidentNo) {
if (incidentNo) {
console.log("Index.js ServiceNow Incident:" + incidentNo);
msg = "Thank you! Your " + TicketType + " Number is " + incidentNo;
console.log("end of flow");
callback(close(intentRequest.sessionAttributes, "Fulfilled", buildMessage(msg)));
} else {
console.log("Index.js ServiceNow Incident:" + incidentNo);
msg = "Err";
console.log("end of flow");
callback(close(intentRequest.sessionAttributes, "Fulfilled", buildMessage(msg)));
}
});
console.log("process is done");
my service.js
var request = require("request");
var servicenow = require("./configfile.json");
var snowURL = servicenow.url;
var snowUsername = servicenow.username;
var snowPassword = servicenow.password;
var ticketNo = "00000";
console.log("Service Now URL:" + snowURL + " Username:" + snowUsername + " Password:" + snowPassword);
module.exports.createIncident = function (caller_id, short_description, callback) {
var snowdetails = {
uri: snowURL,
method: "POST",
"content-type": "application/json",
"auth": {
"username": snowUsername,
"password": snowPassword
}
};
request(snowdetails, function (error, resp, body) {
console.log("Status code " + resp.statusCode);
if (!error && (resp.statusCode == 200 || resp.statusCode == 201)) {
if (body) {
var data = JSON.parse(body);
ticketNo = data.result.number;
console.log("Service Now Incident No:" + ticketNo);
callback(ticketNo);
return;
} else {
console.log("I am unable to authenticate you. please disable the skill and re link your account");
callback("I am unable to authenticate you. please disable the skill and re link your account");
}
} else {
console.log(error);
callback(error);
}
});
};
Here when I run this, I get the output as
process is done
Service Now Incident No:INC0010035
Index.js ServiceNow Incident:INC0010035
Thank you! Your incident Number is INC0010035
and in my window, earlier, when there was no callback, it used to print the msg content, i.e. Generating ticket......, but now it is not printing anything.
Where am I going wrong and how can I fix it?

Strophe MAM how to display the messages?

I have managed to use Strophe MAM to get the archived messages into the RAWInput, and display the last message(but only the last one). How do i display all the messages from the RAWInput?? But not just the last one?
And how do i extract who the message is from?
I have limited the messages to the last 5.
connection.mam.query("test3#macbook-pro.local", {
"with": "test4#macbook-pro.local","before": '',"max":"5",
onMessage: function(message) {
console.log( $(message).text());
},
onComplete: function(response) {
console.log("Got all the messages");
}
});
You can get all the messages using the `strophe.mam.js plugin
Here is my working code:
// Retrives the messages between two particular users.
var archive = [];
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0])
};
archive.val(archive.val() + msg_data.from + ":" + msg_data.message + "\n" + msg_data.to + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q, response:response});
}
};
$(document).ready(function)(){
archive = $("#archive-messages");
archive.val("");
$("#to-jid").change(function() {
$("#archive-messages").val("");
var to = {"with": $(this).val()};
$.extend(q, to, before, max);
// It takes around 800ms to auto login. So after this timeout we have to retrieve the messages of particular User.
setTimeout(function(){
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}, 1000);
});
});
connection.mam.query("Your_Id", {
"with": "partner_id","before": '',"max":'',
onMessage: function(message) {
console.log("Message from ", $(message).find("forwarded message").attr("from"),
": ", $(message).find("forwarded message body").text());
return true;
},
onComplete: function(response) {
console.log("Got all the messages");
}
});
This will fetch all History for a user. If you want to limit, then provide max value.
Don't download strophe.mam.js(https://github.com/metajack/strophejs-plugins/tree/master/mam) from github. Its not working. Please copy below strophe.mam.js file.
**strophe.mam.js**
/* XEP-0313: Message Archive Management
* Copyright (C) 2012 Kim Alvefur
*
* This file is MIT/X11 licensed. Please see the
* LICENSE.txt file in the source package for more information.
*
* TODO:
* Get RSM from the reply
* Clean remove onMessage handler afterwards
* queryid?
*
*/
Strophe.addConnectionPlugin('mam', {
_c: null,
_p: [ "with", "start", "end" ],
init: function (conn) {
this._c = conn;
Strophe.addNamespace('MAM', 'urn:xmpp:mam:0');
},
query: function (jid, options) {
var _p = this._p;
var attr = {
type:"set",
id:jid
};
var mamAttr = {xmlns: Strophe.NS.MAM};
var iq = $iq(attr).c("query", mamAttr).c('x',{xmlns:'jabber:x:data'});
iq.c('field',{var:"FORM_TYPE"}).c('value').t("urn:xmpp:mam:0").up().up();
for (i = 0; i < this._p.length; i++) {
var pn = _p[i];
var p = options[pn];
delete options[pn];
if (!!p) {
var f
iq.c('field',{var:pn}).c('value').t(p).up().up();
}
}
iq.up();
var onMessage = options["onMessage"];
delete options['onMessage'];
var onComplete = options["onComplete"];
delete options['onComplete'];
iq.cnode(new Strophe.RSM(options).toXML());
this._c.addHandler(onMessage, Strophe.NS.MAM, "message", null);
return this._c.sendIQ(iq, onComplete);
}
});
The easiest way to retrieve all the messages is to include this line at the end of the onMessage() function:
return true;
I think the reason is that if a handler does not return true, it will be destroyed after the first time it is called.

How can we send big objects from the background to the active tab in CrossRider?

We are using CrossRider to develop an extension for Internet Explorer. Our extension has code that sends a message to the background, and the background sends a reply and calls a callback function. This works in my computer with Internet Explorer 11, but in my Friend Tom's computer (also with Internet Explorer 11) it doesn't work - the callback is not called in his computer. What is the problem and how do we fix it to work in any computer? Here is the relevant code:
_base.js:
alert("[ContentBase::getData] >>>>>"); // This happens in any computer.
var request = {command: 'get', webmail: thisObj.mContentType, param: param, type: type, contentType: contentType};
thisObj.sendRequest(request, function(response) {
alert("[ContentBase::getData] received data >>>>>"); // This doesn't happen in Tom's computer.
if (typeof(callback) === 'function') {
callback(response);
}
});
utils.js:
this.sendRequest = function(request, callback) {
if (typeof(callback) !== 'function') {
callback = function(response) {};
}
switch (Sys.platform) {
case 'crossrider':
var message = {request: request, message_id: Math.floor((Math.random() * 900000000000000) + 100000000000000)};
if (typeof thisObj.mCallbackMap === 'undefined') {
thisObj.mCallbackMap = {};
appAPI.message.addListener({channel: "message_from_background"}, function(message) {
if (typeof thisObj.mCallbackMap[message.message_id] === 'function') {
thisObj.mCallbackMap[message.message_id](message.response);
delete thisObj.mCallbackMap[message.message_id];
}
});
}
(function(callback_inner) {
thisObj.mCallbackMap[message.message_id] = function(response) {
if (typeof(callback_inner) === 'function') {
callback_inner(response);
}
};
})(callback);
appAPI.message.toBackground(message, {channel: "message_to_background"});
break;
}
};
background.js:
appAPI.message.addListener({channel: "message_to_background"}, function(params) {
MsgHandler.handle(params.request, undefined, function(responseParams) {
appAPI.message.toActiveTab({'message_id': params.message_id, 'response': responseParams}, {channel: "message_from_background"});
});
});
msgHandler.js:
this.handle = function(request, sender, callback_out) {
function callback(response) {
if (typeof(callback_out) === 'function') {
callback_out(response);
}
}
switch (request.command) {
case "get":
switch (request.type) {
case "all":
var data = Controller.getData();
alert("[MsgHandler::handle] get / all, data.length = " + JSON.stringify(data).length + ", data = " + JSON.stringify(data)); // This happens in any computer.
callback({data: data});
break;
}
break;
}
return true; //this return is needed for chrome in order to execute callbacks
};
Sys.platform is always equal to 'crossrider'.
Update: When JSON.stringify(data).length was 5981 bytes the message was received, but when it was 10157 bytes the message was not received by the active tab (with appAPI.message.toActiveTab). What is the limit on the size of objects sent from the background and how do we send big objects to the tabs (up to 100KB)?
Our Extension ID is 43889. I'm using Internet Explorer 11 but this extension should work on all versions of Internet Explorer.
By the way, other calls from the background work, only this specific call doesn't work. We tried several times in Tom's computer and it never works.
Edit: I created a simple extension with the same problem, Extension ID is 67708. Here is the code of the simple extension:
extension.js:
appAPI.ready(function($) {
alert("appAPI.platform = " + appAPI.platform);
if (appAPI.platform === 'IE') {
appAPI.message.addListener({channel: "message_from_background"}, function(message) {
alert("message_from_background received, message_id = " + message.message_id + ", message.length = " + JSON.stringify(message).length + ", message = " + JSON.stringify(message));
});
appAPI.message.toBackground({}, {channel: "init_background"});
}
});
background.js:
appAPI.ready(function($) {
alert("appAPI.platform = " + appAPI.platform);
if (appAPI.platform === 'IE') {
var ready = false;
appAPI.message.addListener({channel: "init_background"}, function(params) {
if (ready === false) {
alert('init_background, ready = ' + ready);
ready = true;
var message_id = 9999;
var responseParams = {'a': 1, 'b': 2, 'c': 3};
alert('sending message to active tab, message_id = ' + message_id + ', responseParams.length = ' + JSON.stringify(responseParams).length);
appAPI.message.toActiveTab({'message_id': message_id, 'response': responseParams}, {channel: "message_from_background"});
var message_id = 9998;
var responseParams = {
// a big object
};
alert('sending message to active tab, message_id = ' + message_id + ', responseParams.length = ' + JSON.stringify(responseParams).length);
appAPI.message.toActiveTab({'message_id': message_id, 'response': responseParams}, {channel: "message_from_background"});
alert(appAPI.platform);
}
});
}
});
When JSON.stringify(responseParams).length is 19 bytes, the message is received by the active tab, but when it's 10576 bytes, the message is not received.
#Uri Thanks for the updated question.
In light of the new information, I would draw your attention to the note in the docs (appAP.message) about Internet Explorer limitations:
Messages are converted to JSON strings before they are sent. Due to a
limitation in Internet Explorer, the maximum length of the JSON string
is 8000 bytes (8Kb).
You can work around the issue by saving the data in the local database and sending a short message to the active tab to trigger it to read the data. The following is a simplified example of the flow:
background.js:
appAPI.ready(function($) {
appAPI.db.async.set(
'my-data',
myData,
appAPI.time.minutesFromNow(1),
function() {
appAPI.message.toActiveTab({type: 'get-data'});
}
);
});
extension.js:
appAPI.ready(function($) {
appAPI.message.addListener(function(msg) {
if (msg.type === 'get-data') {
appAPI.db.async.get('my-data', function(data) {
// do something with data
});
}
});
});
[Disclosure: I am a Crossrider employee]
OK, since the size of objects in the messages is limited to 8000 bytes, I divided the objects to packets of size up to 5000 bytes. Here is the code of my extension:
utils.js:
this.sendRequest = function(request, callback) {
if (typeof(callback) !== 'function') {
callback = function(response) {};
}
switch (Sys.platform) {
case 'crossrider':
var message = {request: request, message_id: Math.floor((Math.random() * 900000000000000) + 100000000000000)};
if (typeof thisObj.mCallbackMap === 'undefined') {
thisObj.mCallbackMap = {};
thisObj.mResponseObject = {};
appAPI.message.addListener({channel: "message_from_background"}, function(message) {
alert("[Utils::sendRequest] got response, message_id = " + message.message_id + ", checking message...");
if ((typeof(message) === 'object') && (!(message === null)) && (typeof(message['divided_object_length']) === 'number')) {
if (typeof thisObj.mResponseObject[message.message_id] === 'undefined') {
thisObj.mResponseObject[message.message_id] = {}
}
var limit = message['divided_object_length'];
var packet_id = message['packet_id'];
var packet = message['packet'];
alert("[Utils::sendRequest] got response, message_id = " + message.message_id + ", limit = " + limit + ", packet_id = " + packet_id + "...");
thisObj.mResponseObject[message.message_id]['packet_' + packet_id] = packet;
var message_is_ready = true;
for (var packet_id = 0; packet_id < limit; packet_id++) {
if (typeof thisObj.mResponseObject[message.message_id]['packet_' + packet_id] === 'undefined') {
var message_is_ready = false;
}
}
if (message_is_ready) {
delete message['divided_object_length'];
delete message['packet_id'];
delete message['packet'];
var s = '';
for (var packet_id = 0; packet_id < limit; packet_id++) {
s += thisObj.mResponseObject[message.message_id]['packet_' + packet_id];
}
message.response = JSON.parse(s);
delete thisObj.mResponseObject[message.message_id];
}
} else {
var message_is_ready = true;
}
alert("[Utils::sendRequest] got response, message_id = " + message.message_id + ", message_is_ready = " + message_is_ready + "...");
if (message_is_ready) {
if (typeof thisObj.mCallbackMap[message.message_id] === 'function') {
alert("[Utils::sendRequest] got response, message_id = " + message.message_id + ", calling function...");
thisObj.mCallbackMap[message.message_id](message.response);
delete thisObj.mCallbackMap[message.message_id];
}
}
});
}
(function(callback_inner) {
thisObj.mCallbackMap[message.message_id] = function(response) {
alert("[Utils::sendRequest] got response, message_id = " + message.message_id + ", checking inner function...");
if (typeof(callback_inner) === 'function') {
alert("[Utils::sendRequest] got response, message_id = " + message.message_id + ", calling inner function...");
callback_inner(response);
}
};
})(callback);
appAPI.message.toBackground(message, {channel: "message_to_background"});
break;
}
};
background.js:
appAPI.message.addListener({channel: "message_to_background"}, function(params) {
alert("background.js :: message received, params = " + JSON.stringify(params));
MsgHandler.handle(params.request, undefined, function(responseParams) {
alert("background.js :: message received callback, message_id = " + params.message_id + ", sending response.");
var s = JSON.stringify(responseParams);
if ((typeof(s) === "string") && (s.length > 5000)) {
var limit = Math.floor((s.length - 1) / 5000) + 1;
alert("background.js :: message received callback, message_id = " + params.message_id + ", sending response, s.length = " + s.length + ", limit = " + limit + ".");
for (var packet_id = 0; packet_id < limit; packet_id++) {
var message = {};
message['divided_object_length'] = limit;
message['message_id'] = params.message_id;
message['packet_id'] = packet_id;
message['packet'] = s.substr(packet_id * 5000, 5000);
appAPI.message.toActiveTab(message, {channel: "message_from_background"});
}
} else {
appAPI.message.toActiveTab({'message_id': params.message_id, 'response': responseParams}, {channel: "message_from_background"});
}
});
});
The rest of the code is the same like in my question (the alerts are just for debugging, we remove them in production).

why my textbox doesnot return any proper value in jquery?

I have created this controller for for getting existing value by searching id. this is my controller for searching data by id. this code is running well but result is not acceptable. i am new in jquery that's why i am explaining this very helpfully..
public string Search(string id=null)
{
string[] ci = new string[9];
//return "Artistry";
string cn = null;
cn = Request.QueryString["id"];
if (cn != null)
{
ClientInfo c = db.SingleOrDefault<ClientInfo>("where CId='" + cn + "'");
if (c != null)
{
// ci[0] = c.CId.ToString();
ci[1] = c.CName;
ci[2] = c.CCName;
ci[3] = c.PhoneNo.ToString();
ci[4] = c.Fax;
ci[5] = c.Email;
ci[6] = c.Address;
ci[7] = c.PostalCode.ToString();
ci[8] = c.Country;
return ci[5];
}
else
return null;
}
else
return null;
//*/
}
My view page script for showing my data..
<script type="text/javascript">
$(document).ready(function () {
$('#CId').blur(function () {
var v = $('#CId').val();
var url = "/Clients/Search/" + v;
// alert("Test : " + url);
$.get(url, function (data, status) {
$("#CName").val(1);
$("#CCName").val(2);
$("#PhoneNo").val(3);
$("#Fax").val(4);
$("#Email").val(5);
$("#Address").val(6);
$("#PostalCode").val(7);
$("#Country").val(8);
alert("Test : " + data + " Status :" + status);
});
});
});
</script>
And finally my sql server database for showing data in views are..
SELECT TOP 1000 [CId]
,[CName]
,[CCName]
,[PhoneNo]
,[Fax]
,[Email]
,[Address]
,[PostalCode]
,[Country]
FROM [test].[dbo].[ClientInfo]
I think you should return json type data like so:
public JsonResult Search(string id=null)
{
// view code
return Json(new {info=ci[5]});
}
And client code:
$.get(url, function (data, status) {
alert("Test : " + data.info + " Status :" + status);
});

Categories