How to pass double quotes in ajax - javascript

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.

Related

Ajax Request: Json Data Not Being Passed to Controller

I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});

Jquery $.ajax not posting a string of data in ASP.NET MVC

I have a situation where I am building the json data to post dynamically. so I create it in a for loop and then attempt to use the $.ajax command, but on the server side the model is null. If I hard code the data section as would be normal, it works fine. I tried the same process with a simple model just to check and the same happens.
So this works:
$.ajax({
url: '#Url.Action("SetupQuestions", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: {SharedSecret: 'Bob'},
success: function (data, status, xhr) {
$('#divMFAQuestion').html(data).fadeIn('slow');
},
error: function (xhr, status, error) {
alert("MFA Challenge Error (b): " + error);
}
});
But this doesn't:
var datastring = '{SharedSecret: Bob}';
$.ajax({
url: '#Url.Action("SetupQuestions", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
processData: false,
data: JSON.stringify(datastring),
success: function (data, status, xhr) {
$('#divMFAQuestion').html(data).fadeIn('slow');
},
error: function (xhr, status, error) {
alert("MFA Challenge Error (b): " + error);
}
});
Nor this:
var datastring = 'SharedSecret: Bob';
Any thoughts?
You have quotes around your entire JSON data structure:
var datastring = '{SharedSecret: Bob}';
JSON.stringify expects a JSON structure, so the quotes should only be around the string part for JSON.stringify to work:
var datastring = {SharedSecret: 'Bob'};
However, the reason that your AJAX call is not working is that the data parameter accepts a JSON data structure. JSON.stringify will serialize it as a string, which data does not expect. So you need to just pass the fixed datastring without JSON.stringify.
data: datastring

Prevent encoding of Cypher query POSTed via JQuery

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)

How to run another JS method from longPolling?

How in method with longPolling:
function getNewMessagesLong() {
pollingFishingStarts();
$request = $.ajax({
type: 'POST',
url: "listenMessageLong",
data: lastIncomingMessageLongJson,
dataType: 'json',
success: function(data) {
}, complete: getNewMessagesLong})
}
on complete to run another method?:
function pollingFishingEnds() {
document.getElementById("fishing-end").src = "resources/img/fishing-end.png";
document.getElementById("fishing-start").src = "resources/img/fishing-start-empty.png";
}
With the example you posted, you could simply do something like this, adding an anonymous function that calls your "ends" method AND restarts your polling method:
function getNewMessagesLong() {
pollingFishingStarts();
$request = $.ajax({
type: 'POST',
url: "listenMessageLong",
data: lastIncomingMessageLongJson,
dataType: 'json',
success: function(data) {
},
complete: function() {
getNewMessagesLong();
pollingFishingEnds();
}
});
}
You could also change up to a window.setInterval() long-polling paradigm that would allow you to use your complete option to set your actual end method, rather than hijacking it for long-polling.
I'm assuming here that you want to call the "end" state code after the first round completion. Otherwise, there's literally no end to your polling, unless you have some server message to terminate, in which case you need to post that code for additional information.

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) {
});

Categories