Executing a Cypher query on Neo4j using jQuery

ajax, javascript, jquery, neo4j, rest

Solution

In the snippet you've supplied a more complex `Accepts` header is sent that Neo4j cannot deal with. I've used the following snippets:

var request = $.ajax({
    type: "POST",
    url: "http://localhost:7474/db/data/cypher",
    accepts: { json: "application/json" },
    dataType: "json",
    contentType:"application/json",
    data: JSON.stringify({ "query" : "MATCH n RETURN n LIMIT 1", "params": {} })
 });

Omitting both, `accepts` and `dataType` seems to work as well:

var request = $.ajax({
    type: "POST",
    url: "http://localhost:7474/db/data/cypher",
    contentType:"application/json",
    data: JSON.stringify({ "query" : "MATCH n RETURN n LIMIT 1", "params": {} })
 });

Problem

I am trying to make an Ajax call with jQuery to a Neo4j Server, both on the same machine, but I keep getting errors in the response. This is how I wrote the ajax call: ``` var request = $.ajax({ type: "POST", url: "http://localhost:7474/db/data/cypher", accepts: "application/json", dataType: "json", contentType:"application/json", data: JSON.stringify({ "query" : "MATCH n RETURN n LIMIT 1", "params": {} }) }); ``` When I execute this code, in FireBug I see: ``` "NetworkError: 400 Bad Request - http://localhost:7474/db/data/cypher" ``` And in the response to the POST request I find the following body: ``` <html><head><title>Error</title></head><body><p><pre>WebApplicationException at org.neo4j.server.rest.repr.formats.HtmlFormat.serializeMapping(HtmlFormat.java:348) at org.neo4j.server.rest.repr.RepresentationFormat.serializeMapping(RepresentationFormat.java:73) at org.neo4j.server.rest.repr.MappingRepresentation.serialize(MappingRepresentation.java:39) at org.neo4j.server.rest.repr.OutputFormat.assemble(OutputFormat.java:215) at org.neo4j.server.rest.repr.OutputFormat.formatRepresentation(OutputFormat.java:147) at org.neo4j.server.rest.repr.OutputFormat.response(OutputFormat.java:130) at org.neo4j.server.rest.repr.OutputFormat.ok(OutputFormat.java:67) at org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:101) at java.lang.reflect.Method.invoke(Method.java:606) at org.neo4j.server.rest.transactional.TransactionalRequestDispatcher.dispatch(TransactionalRequestDispatcher.java:139) at org.neo4j.server.rest.security.SecurityFilter.doFilter(SecurityFilter.java:112) at java.lang.Thread.run(Thread.java:745)</pre></p></body></html> ``` These are the response headers: ``` Access-Control-Allow-Origin... * Content-Length 1065 Content-Type text/html; charset=UTF-8 Server Jetty(9.0.5.v20130815) ``` When I do the same request in Chrome's Advanced Rest Client, I do get the desired response. How can I make my ajax call so Neo4j will give me the results from the Cypher query?

Original source