I am trying to model a chat application on a browser(Firefox).Here I am trying to send the char inserted into a text area on one machine to another client and update its text area.
I am trying to send the key pressed on the client using AJAX calls. Below is the function call that I have written :
function returnKeyFromCode(code)
{
//Returns char code
};
function keyPress(e)
{
var textReplace = document.getElementById("textReplace");
var keyPressed = returnKeyFromCode(e.which) ;
textReplace.innerHTML = keyPressed;
var locationReplace = document.getElementById("location");
locationReplace.innerHTML = mainDoc.selectionStart;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){};
xmlhttp.open("POST","http://localhost:5000?key=" + keyPressed + "&pos=" +mainDoc.selectionStart +"&revno=1¶m=EOS",true);
xmlhttp.send("Stuff");
};
At the client side, when the char is received the following error is displayed on the fire bug console:
'0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]' .
Before sending the data, a persistent connection is being set up between client ans server using another Ajax call.
It looks like you've edited some of your code before posting this question, so I can only speculate, but based on the error, i'd guess at some point you're sending null to this function: xmlhttp.send("Stuff");
Try doing a null check on the data before you send it, or possibly make sure whatever starts the send process is in a document ready, so that you're not trying to grab data from an undefined text element.
Related
I'm struggling to find out why TcpClient don't receive any data in server side if it has called through ajax.
However, if I put breakpoint in my server side code it works fine even if I have called it with ajax.
I also investigated to find out if my JavaScript function is asynchronous but it seems my JavaScript function is fine.
JavaScript function:
$('#btnGO').click(function () {
var url = 'Home/Command';
var data = { Location: $('#Location').val() };
$.when($.getJSON(url, data)).then(function (result) {
$('.Console').html(result);
});
});
Server side:
TcpClient tc = new TcpClient("Host Address", 23);
return Json(tc.Connected + " " + tc.Available, JsonRequestBehavior.AllowGet);
Output if I put breakpoint in serverside:
true 22
Output if I don't put breakpoint in serverside:
true 0
I think you'd want to call GetStream(), and then call Read() on the returned NetworkStream. Read() is blocking, and won't allow your action method to return prematurely. Right now, there are no blocking calls to prevent your action method from instantly returning (faster than your tcp client receives data), which is why you get 22 when you put in a break point - it doesn't instantly return. It seems awkward that your UI responsiveness depends on somebody sending data to your API via a socket though....
let me emphasize this more: It's really strange what you're doing. Your UI will be waiting for a client to send data to your API via a socket. Having said that, check out the following link: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx
I have a problem in in MobileFirst Foundation 8.0 where the parameter in a POST request is not captured in the adapter, but in a GET request the parameter is working fine.
Example for GET request
var url = "/adapters/samplePOST/unprotected/";
var resourceRequest = new WLResourceRequest(url, WLResourceRequest.GET);
resourceRequest.setQueryParameter("params","['value1','value2']");
resourceRequest.send().then(function(e){console.log(e)}, function(e){console.log(e)});
Adapter side
function unprotected(user){
return {
result:JSON.stringify(user)
};
}
Output
{\"result\":\"\"sd\"\",\"isSuccessful\":true}
Example for POST request
client side
var url = "/adapters/samplePOST/unprotected/";
var resourceRequest = new WLResourceRequest(url, WLResourceRequest.POST);
var data={"params": "['sd','ds']"};
resourceRequest.sendFormParameters(data);
resourceRequest.send().then(function(e){console.log(e)}, function(e){console.log(e)});
Adapter side
function unprotected(user){
return {
result:JSON.stringify(user)
};
}
Output
{\"isSuccessful\":true}
In POST request adapter side, the parameter is undefined.
Also, in my development console -> swagger, if I hit POST Request form query [{"params": "['sd','ds']"}] its working fine but from a cordova application the parameter can't be parsed but in same cordova application GET Request working fine.
Update: note that you should change how you're making the request to the following:
resourceRequest.sendFormParameters(data).then(
function(e) {
console.log(e)
},
function(e){
console.log(e)
}
);
sendFormParameters actually sends the request, so no need to also use send. Otherwise, you're sending the parameter - twice, which triggers this issue.
I've tried it myself and it is strange.
In Swagger I indeed get the following as the response body for a POST request as you've demonstrated:
{
"result": "\"value1\"",
"isSuccessful": true
}
But in the application the result property is missing from the response object.
Printing the param value in the adapter using MFP.Logger.info I can see the following two logger lines in the application server's messages.log file, even though I had only a single logger line:
[10/9/16 10:57:00:643 IDT] 00000ec7 MFP.Logger I ********** the param value is: sd
[10/9/16 10:57:00:646 IDT] 00000f3e MFP.Logger I ********** the param value is: undefined
One with the value and another without... I suppose the undefined one is returned to the client, which is why you get no result value(?).
the problem is you mis-used the sendFormParameters() API .
use the (asynchronous promise) JavaScript API correctly.
in your examples use either sendFormParamters() or send() but not both API. these two functions are different ways to achieve same goal.
For example:
var resourceRequest = new WLResourceRequest(url, WLResourceRequest.POST);
var data={"params": "['value1', 'value2']"};
var result = resourceRequest.sendFormParameters(data).then(
function(response){
alert ("responseText: " + response.responseText + " ** responseJSON: " + JSON.stringify(response.responseJSON));
},
function(err){
alert (JSON.stringify(err));
}
);
the later API seems to work with no issues.
A PMR is being opened for the send() API.
when using MFP v8.0 Resource request with POST and empty body : content type must be set to application/x-www-form-urlencoded
if combined with the send() API.
The Android code will fail (iOS works fine).
simple workaround: when writing the WLResourceRequest manually add an HTTP "Content-Type" header like this:
var resourceRequest = new WLResourceRequest(url, WLResourceRequest.POST);
resourceRequest.setQueryParameter("params", "['value1', 'value2']");
resourceRequest.setHeader('Content-Type','application/x-www-form-urlencoded');
resourceRequest.send().then....more code here...
My situation is like this, I have a server like this and inside I am calling another callback function which gets multiple values:
var http = require('http');
var server = http.createServer(req,resp) {
var finalVal = "";
consumer.on('message',function(message) {
finalVal = message;
console.log(finalVal);
});
resp.end(finalVal);
});
My finalVal should display all the multiple values it fetches and send it as a response, but problem is it's sending only first value where as console.log displays all the values. I do understand that by the time consumer.on ends response would have committed. Can someone please help me how to handle this scenario since I'm very new to Node.js ? Currently due to heavy deadlines I don't have time to read full information about callbacks. But defnitely I would take time to learn about callbacks.
Edit: Here consumer.on calls multiple times till it fetches all the data from backend, I need to send all those data in a final response. I am using node-kafka to consume to kafka messages.
There must be an end event or something like that which tells that consumer has finished the message, you can use that
I am not sure what is consumer here, but in most of cases we go with something like bellow
var finalVal = '';
consumer.on('message',function(message) {
finalVal += message; // So on each message you will just update the final value
console.log(finalVal);
});
consumer.on('end',function(){ // And at the end send the response
resp.end(finalVal);
});
I am trying to utilize server sent events to handle the client side of some async operations im doing server side. Scroll to the bottom to see the final question.
What I have is an web app that needs a global search. The returns can be massive and take some time as they are actually sent to a webservice and then returned as XML.
I am trying to use server sent events (javascript: EventSource) to enable this. It works great for just one event but if I want to do a bunch of different events it gets a little weird, at least for me. I am new to SSE.
so far I have done this:
var sse = new EventSource('testsse.aspx');
function init() {
sse.onopen = function (e) {
console.log(e.data);
};
sse.onmessage = function (e) {
//if data has been returned the "data:" field will not be empty so we know the server operation is complete.
if (e.data.length>0) {
$('#rgCcr').kendoGrid({
dataSource: JSON.parse(e.data)
});
sse.close();
}
console.log("message: " + e.data);
};
$(document).ready(function() {
init();
});
on the server I have an aspx page that is building the json strings. as I mentioned I have it working great if I just use the standard "data: my message\n\n" format. What I need to do is get a few more pieces of info in there.
The spec for SSE says that you can specify an event to fire. I cant get this to work so far though.
in my aspx I am building the string like this:
json = string.Format("id:{0}\n event:myEvent\n data:{1}\n\n", id, ser.Serialize(ccrData));
I have tried creating a custom event but I am not sure what to bind it to in order to catch it.
On the page I have 5 different areas that are being search as part of the global search. Each is executed as an async task on the server and as they complete they will send the data back to the client. once the client detects the event has submitted data it will close the listener and add the data results to the kendo grid.
How can I use the event field of the SSE to tell the difference between what is coming back?
Rather than using the "onmessage" function, you could try registering an event listener. That way you can choose to listen to a particular event type.
es = new EventSource('/events', withCredentials: true);
es.addEventListener("open", function (e) {
alert("Connecting...");
});
es.addEventListener("error", function (e) {
alert("Error");
});
es.addEventListener("myEvent", function (e) {
alert("MyEvent");
alert(e.data);
});
There's great documentation here:
http://html5doctor.com/server-sent-events/
i want to send the json data from client side(javascript) to server side(ASP.NET,C#) using HTML5. i am using XMLHttpRequest Object to send data to the server by using the following javascript code. i am executing this code behind the html button click.
var xhr = new XMLHttpRequest();
var jsonString = JSON.stringify(jsonObj);
xhr.open('GET', '/HTML5_Crud.aspx?obj='+jsonString, true);
xhr.send();
on server side (ASPX.cs) file i am using the following code in Page_Load method to get data from client.
if (Request.QueryString["obj"] != null)
{
jsonStr= Convert.ToString(Request.QueryString["obj"]);
lblTest.Text = "the json is: "+ jsonStr;
}
but when i run the application and clicks the button my label is not updated with the latest data. it still the same as default text i set inline. please help me how can i resolve this issue.
In the second code snippet, the value of lblTest.Text only exists within the context of the request you made from javascript. There is no magic way to update the response originally sent to the browser. If you want that to be update you have to do either:
Use a postback instead of javascript and update the page
Use javascript to read the response from the Ajax request and then update the DOM client side.
You're trying to do two different things. the XMLHttpRequest is used for an AJAX request, and what you are doing in the back-end will only update your page when it is reloaded. But because you are sending an AJAX request, the page is never refreshed.
What you need to be doing is respond in your code-behind with a string or something, and in your javascript, use the string as appropriate.
Your label will not update this way.
Instead you should return the value to your request and handle it xhr's onreadystatechange event.
Or you can wrap the label in an UpdatePanel and add a button that will store the value in a hidden field for example and cause a postback. Then you could retrieve the value from this field and the whole panel would update to the new values.