Prevent encoding of Cypher query POSTed via JQuery - javascript

I have a Cypher query for Neo4j which looks like this:
var query = "MATCH (t:Person {name: 'Darth Vader'})-[:CHILD_OF*0..1]-child RETURN <a bunch of node properties>"
$.ajax({
url: '/wdc/query',
type: 'post',
data: query,
contentType: 'text/csv; charset=UTF-8',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Said query is POSTed to a route in a node.js app where it is executed against Neo4j. The body of the POST which I received is handled like so:
app.post('/wdc/query', function(req,res) {
console.log(req.body);
}
I can't seem to pick the correct contentType in order to avoid my string from getting heavily munged:
//contentType: "application/x-www-form-urlencoded; charset=UTF-8"
{ 'MATCH (t:Person {name: \'Darth Vader\'})-': { ':CHILD_OF*0..1': '' } }
//contentType: 'text/csv; charset=UTF-8'"
{}
//contentType: 'text/x-java-source,java; charset=UTF-8'
{}
//contentType: 'application/json; charset=utf-8'
Error: invalid json
I'm clearly shooting blanks here. Can anyone give me a push in the right direction? Do I just need to encode this whole damn string and be done with it? (unfortunately, some of the methods I see to do this don't handle characters like '[')
Thanks.
Edit
Never Mind Just used JSON to wrap the query and then passed that as JSON/application. Works well - only thing that happens is we escape the single quotes around "Darth Vader", which is expected:
var jsonObj={};
jsonObj["statement"] = match + returnClause;
query = JSON.stringify(jsonObj)

Related

On Ajax Post, getting a bad request(404)

Using Ajax Post, getting a Bad Request(404).
I tried to google but didn't help me in that.
Note: on using "contentType: 'application/json; charset=utf-8'," on post my request going as a OPTIONS
var data = JSON.stringify(dataArr);
var clientType = $("#clientType").val();
var username = $("#hidUsername").val();
var clientId = $("#clientId").val();
var apiUrl = 'http://localhost.com/WebAPI/client/PostToclient'
$.ajax({
url: apiUrl,
type: 'POST',
//contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({
'clientData': data,
'username': username,
'Id': clientId,
'clientType': clientType
}),
cache: false,
success: function(response) {
alert(response);
},
complete: function() {
},
error: function(ex) {
}
});
Not knowing your API its fairly hard to tell what going wrong. You will need to provide more information on the server side for this one ;)
One thing looks weird: the id field written in upper case 'Id', which likely to be 'id or 'clientId' if your API follow any kind of logic :p
Thanks all for ur help.
I found the problem why its is not able to call api. Now I am able to post my data using ajax call.
[WebInvoke(UriTemplate = "/client/PostToclient", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped)]
[OperationContract]
public async Task<string> PostToclient(string clientData, string username, string Id, string clientType)
{
// Create / update client data.
}
Make sure that your API is working fine, for that you can test with postman app.
And I observed that you are passing JSON content in a JSON data. i.e client Data, I think it may not work.
Please try to declare client Data properties with primary json format, so that it may solve.

How to pass double quotes in ajax

I have to make an ajax call to node.js server from jquery and the data contains some metacharacter like * and makes a regex based search. The data looks like this:
var obj = {"field": "*\"comment*" };
$.ajax({
type: 'GET',
contentType: 'application/json',
url: '/getData/'+JSON.stringify(obj),
data: JSON.stringify(obj),
timeout: 400000,
error: function () {
},
success: function (data) {
}
});
But I end up seeing an error (may be because the GET request has double quotes(") in it). How do I make it happen even with quotes in it.

JavaScript array getting encoded when posting jQuery

I'm trying to post part of my Knockout viewmodel to our server using jQuery.Ajax.
When I build the data object it looks fine in the console, but when it gets sent via the jQuery Ajax Post the array within gets encoded. The results on the other end are readable by the server, so it works, but it disturbs me greatly (the payload is bigger for one thing).
Here's the code:
var items = $.map(self.Items(), function (item) {
return item.Key() ? {
Key: item.Key(),
PromoCode: item.PromoCode,
Qty: parseInt(item.Qty(), 10)
} : undefined;
}),
data = {
"InEditMode": true,
"Items": items
};
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
success: function (order) {
<snip>
The result as seen by FireBug is this.
Here's the decoded JSON Object
InEditMode true
Items[0][Key] 2730M0ARAX1111AAAAX0
Items[0][PromoCode]
Items[0][Qty] 3
Items[1][Key] 2730M0ARCX1111AAAAX0
Items[1][PromoCode]
Items[1][Qty] 5
Here's the Raw view
InEditMode=true&
Items%5B0%5D%5BKey%5D=2730M0ARAX1111AAAAX0&
Items%5B0%5D%5BPromoCode%5D=&
Items%5B0%5D%5BQty%5D=3&
Items%5B1%5D%5BKey%5D=2730M0ARCX1111AAAAX0&
Items%5B1%5D%5BPromoCode%5D=&
Items%5B1%5D%5BQty%5D=5
Like #codenoire said in his comment, you aren't specifying the content type. Add contentType: 'application/json; charset=utf-8' to your $.ajax call, like so:
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
<snip>
I think you need to stringify your JSON object before you post it. Use JSON.stringify(data) before you post it.
I was so close! The answer is a combination of rwisch45 and Saeedses
I had already tried adding the contentType before, but that caused it to break and I hadn't pursued it any further then that.
the solution is to add the content type AND JSON.stringify it, as so.
$.ajax({
url: '/api/order/',
type: 'POST',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
Thanks all for your help!

jquery not properly serializing json in ajax call

Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});

Passing js object as json to jquery?

I have the following but it's not working, I read somewhere on the stackoverflow that it works like this but I can't seem to get it to work.. it errors... am I doing something wrong?
If I do pass data like this - it works -- so I know my service is working
//THIS WORKS
data: "{one : 'test',two: 'test2' }"
// BUT SETTING UP OBJECT doesn't work..
var saveData = {};
saveData.one = "test";
saveData.two = "tes2";
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: saveData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
I believe that code is going to call .value or .toString() on your object and then pass over the wire. You want to pass JSON.
So, include the json javascript library
http://www.json.org/js.html
And then pass...
var saveData = {};
saveData.one = "test";
saveData.two = "tes2";
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: JSON.stringify(saveData), // NOTE CHANGE HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
According to this blog post, the reason it doesn't work when you try to pass the object is that jQuery attempts to serialize it. From the post:
Instead of passing that JSON object through to the web service, jQuery will automatically serialize and send it as:
fname=dave&lname=ward
To which, the server will respond with:
Invalid JSON primitive: fname.
This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter[...]
Which is what you're doing in the example that works.
My suggestion would be to use the jquery-json plug-in and then you can just do this in your code:
...
data: $.toJSON(saveData),
...

Categories