Not wrapping my brain around this concept at all. I've got a backbone marionette app that has a chat component. All working well.
Each time a user hits the send button on a message, SignalR delivers it. All that is good. I also want to, however, after the message is delivered, submit the message to a web service written in asp.net VB by another developer. That web service persists the message to his SQL server db. I get that backbone models and asp.net Web API's are a natural fit. But the other app is a standard asp.net webforms app, not a Web API.
My old Adobe Flex chat app talked to this web service very easily. Was cake. As I rewrite this Flex app as a backbone marionette app I'm missing how, conceptually, to post the chat messages to the persistence service. When I search for something like "asp.net ajax post web service" I get lots of stuff on the server-side control, ScriptManager. Not applicable in a backbone app I would think.
I thought something like below might work, but I get an error deep inside jQuery, "Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable."
What is the conceptual misunderstanding I'm having here?
var url = "http://mydomain.com/thesevice.asmx/theoperation";
var formData = {userid: userid, message: msg};
$.ajax({
url: url,
type: "POST",
data: formData,
success: function (data, textStatus, jqXHR) {
//data - response from server
console.log("Successfully posted chat msg to service...");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("theoperation error: " + textStatus);
}
});
Conceptual misunderstanding is that you don't post the messages to the service from the client. The service in question is on another domain. There are cross domain issues when posting from the browser. Should post from the server side code that is handling the chat routing.
Related
So I'm creating a basic jackpot betting site for fun and it allows users to put money into a pot and then based on the percentage of money each user puts in it randomly picks a winner. It's working fine at the moment but I feel like the way I'm updating the jackpot page with ajax is really bad. At the moment I have javascript that makes an ajax request each second to get the pot info (size of the pot, players, etc..). I feel like there is a much better way to do this. Is it possible to only make an ajax call when the database is updated? Thanks!
My javascript at the moment:
setInterval(update, 1000);
function update() {
getPotID();
$.ajax({
type: "POST",
url: "/jackpot/update/" + potID,
complete: function(response) {
$('.live-jackpot').html(response.responseText);
getPotInfo();
},
error: function(xhr, status,error) {
console.log("Error");
}
});
}
as said from 7urkm3n, ActionCable has great advantage for this functionality.
Right now you are writing Javascript code that is executed on the client side. Every user that will start a GET http request to your site, will load that javascript files. They will start performing POST request every second to your backend server.
ActionCable is a websocket preinstalled in Rails 5. This means that to configure the notifications with ActionCable and Rails 5, you already have installed everything in your app (if you are using rails 5), you just need to install Redis on your local machine for testing the app in development.
I am not an expert, my understanding is that you use a specific database called redis to store the information about the subscription. I quote a useful article
So PubSub is this concept that Redis and Postgres and a few other things supports, and basically you have this ability to have Channels and the ability to subscribe (and receive those messages) and publish to those channels and anyone listening will then receive those messages.
An example of this is a ChatroomChannel, you could have people publishing messages to the ChatroomChannel and anyone who was subscribed to the ChatroomChannel would receive the broadcast from the channel with the websocket.
This is something you are missing, this way you could only find which users are actually on the playing page and which users are just browsing around, based on this ActionCable creates a channel to communicate between server and client and then creates a subscription to distinguish users that are actually on the playing page and those that left and should not be anymore notified
I quote another useful article
Before we dive into some code, let's take a closer look at how Action Cable opens and maintains the WebSocket connection inside our Rails 5 application.
Action Cable uses the Rack socket hijacking API to take over control of connections from the application server.
For every instance of your application that spins up, an instance of Action Cable is created, using Rack to open and maintain a persistent connection, and using a channel mounted on a sub-URI of your main application to stream from certain areas of your application and broadcast to other areas.
so every user that connects, ActionCable creates a channel that uses a specific url localhost:3000/cable to communicate between server and client (browser)
Action Cable offers server-side code to broadcast certain content (think new messages or notifications) over the channel, to a subscriber. The subscriber is instantiated on the client-side with a handy JavaScript function that uses jQuery to append new content to the DOM.
This means that the server can call the client with parameters and change the page with jquery functions. For ex. appending a div, with a new message.
In my app https://sprachspiel.xyz I do the following in the MessagesController#create
ActionCable.server.broadcast 'messages',
message: message.content,
user: message.user.name,
chatroom_id: message.chatroom_id,
lastuser: chatroom.messages.last(2)[0].user.name
head :ok
so basically, I have my message in my controller and I can update the client by using the ActionCable.server.broadcast function
then in my asset pipeline file /app/assets/javascripts/channels/messages.js I have the following code that trigger the change in the browser adding the message
App.messages = App.cable.subscriptions.create('MessagesChannel', {
received: function(data) {
$('#messages').append(this.renderMessage(data));
},
renderMessage: function(data) {
return "<br><p> <strong>" + data.user + ": </strong>" + data.message + "</p>";
}
});
I build an app called https://sprachspiel.xyz that is an actioncable app, this is the github page for the project, on my portfolio you can read more info about my app, so please ask me anything, I'll be happy to look into it!
Good luck
Fabrizio
I was looking to get some opinions on something I am trying to achieve. I have built an API which essentially comprises of GET requests that returns data. A third party have built a frontend that utilizes my API. I am hosting the frontend and backend but they sit on seperate servers. The frontend has no access to the server besides via the API.
Now on a third level, I need to implement some tracking. Essentially, if a button is clicked on the frontend I want to record this. So I thought that I could add a database table to my API database for this. I can then provide a route to record the information I need. With the API set up, I have created my own script which essentially looks something like this
$( ".button" ).click(function(e) {
e.preventDefault();
$.ajax({
url: "https://someurl.com/tracking",
type: "POST",
data: {
"Element" : "Button Click",
"id": someID
},
success: function (data) {
alert(data)
},
error: function(xhr, ajaxOptions, thrownError){
alert("ERROR")
}
});
});
So if any element with the class button is clicked, an AJAX request is made to my API and then the API can put the data into the table.
Now in thoery the above approach should work. I did have a couple of questions however.
I now essentially have a frontend on server A, a backend on server B, and a seperate tracking script which I will place on server A and simply load in the frontend. I am expecting a lot of visitors to this application, so would this tracking and all of the requests it will make cause any issues?
My main question however is this. Is there any way I can implement this tracking without interfering with the application itself, almost making it unobtrusive. Essentially, if something goes wrong with the tracking, I do not want it to have any impact on the application (frontend and backend) itself. Are there any safeguards I can implement to ensure this?
Any advice appreciated.
Thanks
Which javascript files must be available either in client-side or server-side for you to be able to send and receive json data in your BlackBerry phonegap application.
I see this often omitted in all the solutions to json-related questions that have been posted.
I am completely new to phonegap and jQuery and so I need help also I am trying to send form details (like firstName and lastName) to a php file on the server-side.
So that the data would be processed by the php and the record would be stored on my database.
Can some one work me through how to send the data using json?
You can get detail on Json integration in phonegap from this blog.
this blog will explain through a simple example how you can use JSON to ease the client-server data transmission.
Don't bother about server site, server team (PHP/Java) will take care of it.
In phonegap app every logic is buid in javascript, so in your case if you want to send some information to server, you need to create json object and append it to $.ajax function and same function to receive the response from server:
$.ajax({
url:'stringURL',
beforeSend: function(x) {
x.setRequestHeader('Authorization','username/pwd');
},
dataType:"json",
contentType:'application/json',
timeout:10000,
type:'POST',
data : {
//append json data here if you want to send some data to server
},
success:function(data) {
alert(data); // here you will get json data on success, parse it like key-value mechanism in js
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
alert("Error status :"+textStatus);
alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
}
});
Please have a look at this blog to write php-web service or share with you server team.
I have a web app served by cherrypy. Within this app, I would like to fetch some data from a couchdb server, preferably using jquery. I am having trouble to authenticate into the server. When using:
$.couch.login({
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
It sends the login request to the cherrypy server, not the couchdb. According to this, I can use jquery.ajax settings and therefore I have tried using:
$.couch.login({
url: 'http://127.0.0.1:5984',
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
but it does not seem to work.
Any ideas? In addition, can anybody point me to good tutorial or simple web app developed in a similar fashion, i.e. a "standard" web page (not a couchapp), which contains jquery that gets info from couch.
What you are currently doing is telling jquery.couch.js to login against that url. (It needs to POST to /_session)
I believe you need to set up the urlPrefix property on $.couch.
$.couch.urlPrefix = "http://localhost:5984/"; // run this before anything else with $.couch
Don't forget that inside a browser, JavaScript enforces the same origin policy. Since the HTML page is presumably not being loaded from port 5984, you'll have figure out some clever way around it, such as CORS or mod_proxy.
I'm currently developing a web-site for the public transportation system based on the Trafikanten API (http://reis.trafikanten.no/topp2009/topp2009ws.asmx)
The site has several functionalities though it's Web-Services. It is implemented done in .NET framework with SOAP format. But we need to consume it's functionalities in client side language like JavaScript to be able to display the information in web-page. Can anybody suggest some easy way to cope this scenario?
Provided you're using a LAMP stack:
I would write a PHP script using the nusoap (http://sourceforge.net/projects/nusoap/) libarary to consume the SOAP web service and return JSON to your JavaScript via an AJAX call.
Edit
It's even easier in .NET. Just right click on your project and choose Add a web service. Then you can access methods of the web service just as you would any other object. As far as using it in JS, you could implement create an ASP page that outputs the results in JSON format and then consume that using jQuery as you would with a LAMP stack. Although, with the post back abilities of ASP, you might be better off letting it do the heavy lifting in JS and consume the web services directly in your code file behind your view.
Hope that helps.
If the service doesn't support JSONP, which it probably doesn't as an ASMX service, you'll need to create a service proxy to run on your local web server. Then, use that local service to act as an intermediary that circumvents the browser's cross-domain limitation.
If you added a service reference to Top2009WS in your ASP.NET project, something like this could act as a server-side proxy for GetLines() for example:
[WebMethod]
public Line[] GetLines(int ID) {
var client = new Topp2009WS.Topp2009WSSoapClient();
client.open();
return client.GetLines(ID);
}
Then, you could call through the proxy like this on the client-side:
$.ajax({
url: 'Service.asmx/GetLines',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: '{"ID":' + 12345 + '}',
success: function(response) {
// Alerts the first result's "LineName"
alert(response.d[0].LineName);
}
});
See this post for more information on using jQuery to call the web service.
I've done it in the past as Jesse says but with .NET. I build an "composed service" or adapter service which then calls the other services. The composed service would communicate SOAP with the .NET services while your application would communicate JSON with your composed service.