Search code examples
jqueryscalafinagle

jQuery Ajax call to Twitter Finagle server


I'm struggling getting the JSON string that was sent from a web page to my server.

In the web page, I do the following:

  $.ajax({
     type: "POST",
     url: url,
     data: JSON.stringify(formData),
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function(msg) {
       // TODO: Listen for server ok.
       alert(msg);
       }

On the server side, my Scala code looks as follows:

import com.twitter.finagle.Service
import com.twitter.finagle.builder.Server
import com.twitter.finagle.builder.ServerBuilder
import com.twitter.finagle.http._
import com.twitter.util.Future
import java.lang.String
import java.net.InetSocketAddress
import org.jboss.netty.buffer.ChannelBuffers
import org.jboss.netty.util.CharsetUtil.UTF_8

/**
 *
 */
object HttpServerExample {
  def main(args: Array[String]) {

    class EchoService extends Service[Request, Response] {
      def apply(request: Request) = {
        println(request.getContent());

        val response = Response()
        response.setContentType(MediaType.Html, UTF_8.name)
        val responseContent: String = "Thanks"
        response.setContent(ChannelBuffers.copiedBuffer(responseContent, UTF_8))
        Future.value(response)
      }
    }

    val echoServer: Server = ServerBuilder()
      .codec(RichHttp[Request](Http()))
      .bindTo(new InetSocketAddress("127.0.0.1",8080))
      .name("EchoServer")
      .build(new EchoService())

   }
}

For some reason the request content is empty.

If I change the ajax call to:

 $.ajax({
     type: "POST",
     url: url,
     data: formData,
      success: function(msg) {
       // TODO: Listen for server ok.
       alert(msg);
       }

Then I can get the data as parameters.

How do I get the JSON string on the server? Am I sending it wrong, or receiving it wrong?


Solution

  • Instead of:

     $.ajax({
         type: "POST",
         url: url,
         data: JSON.stringify(formData),
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function(msg) {
           // TODO: Listen for server ok.
           alert(msg);
           }
    

    I'm now using:

       $.post(url,
          JSON.stringify(formData),
          function(msg) {
             // TODO: Listen for server ok. If this is successfull.... clear the form
             alert(msg);
          },
          "json");