Remove null value in javascript for $.ajax POST - javascript

I have
var pageData = {
query: null,
pageNumber: 0,
pageSize: 30};
When I make an ajax get:
$.ajax({
type: 'GET',
url: '/Ajax/GetSuggestions',
data: pageData,
success: function (response) {}
The request show in firebug: http://localhost:31198/Ajax/GetSuggestions?query=null&pageNumber=1&pageSize=30
At server side (ASP .NET MVC3), I received query = null in string, not null data(what I need).
How can I fix it without using delete method of javascript to remove null value?

If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?query=&pageNumber=1&pageSize=30
Then, you have to set query property to "" (an empty string).
If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?&pageNumber=1&pageSize=30
Then, you have to remove to remove the query property from the pageData object by either not putting it there in the first place or by using delete pageData.query to remove it.

There are multiple ways to send data "over the wire". The standard one for sending form data to the server is url encoding. A second way is to send a JSON object. (A transmission detail is that the JSON would be url-encoded. But that's only a transmission detail.) A third way is to use XML.
As #jfriend00 shows in his answer, there are multiple, hacky ways to send a "null" value via url encoding. You should use the one which your server side stack best supports.
Re: why the string "null" What's happening is that the Javascript value null needs to be converted to a value that can be sent via HTTP ("over the wire"). The default way to do that is to use the string null. The problem is that the url encoding scheme only sends things as strings. So it doesn't have an automatic way to send the value null vs teh string null. The usual work around is an empty string, "".
But this can also raise an issue on your server-side since the string "" is not equal to the value null in most computer languages. So you will need to make appropriate comparisons or conversions. Eg does "" == false in your server software?
Using JSON for the data encoding is the other technique.
JSON directly supports a null value. It is is supposed to transmit it as null. See JSON spec (not so obvious, search the page for null) and IBM docs
The way you receive null data in JSON is the bareword null. If you're using JSON, note that you do not receive the string null, you receive the JSON keyword null. Your JSON receiver/decoder should know the difference. If it doesn't, then it is faulty.

When the request string is being built in jQuery, it's using every property on the data object it can find.
All you need to do to remove a property is delete the property:
delete pageData.query;

Related

Make postman query param type of boolean

I use postman to test my api
http://localhost:3000/api/books?disabled=true
I want to set disabled=true (or false) and I expect it is a bool
But somehow
const {disabled} = req.query;
console.log(typeof disabled) //I get disabled type of string
How I set my query param boolean type?
Regardless of the format (query params, JSON body) it is the job of the backend to parse and validate the request.
So even if you send a parameter like “active=true”, it is still a string, this is how the HTTP protocol works.
For more info ---> https://community.getpostman.com/t/how-to-pass-boolean-values-using-postman/1174
let disabled = ( req.query.disabled !== 'false' )
That should do it. As explained in other answers, HTTP does not natively support any non-string or non-stream types (integers, booleans, etc.). The server is tasked with parsing the meaning from the original request format.
Alternatively, you can also do the following to become more familiar with the intricacies of parsing JSON-based requests.
let disabled = JSON.parse(req.query.disabled)
Here is the screen print of passing boolean as query param
For any reason, if the param returns false, the issues could be that I came across,
The key defined in #RequestParam has typo
The key defined in #RequestParam has space
The key defined in #RequestParam not matching with the key mentioned in postman query param list

JSON stringify adds quotes "" in the float type data

I am parsing a float data from my controller to a js function via JSON, following is the JS function:
function fetchbal(){
$.ajax({
url: "/count/ew",
dataType: "json"
}).success(function(data){
$('#bal').html(JSON.stringify(data.sum));
});
}
but I am getting an output with quotes around the figure.
I have checked the value returned by the controller, and it is not passing the quotes, so it has to do something with JSON stringify!
for cross checking this is the controller(Symfony):
$repo = $em->getRepository('SystemBundle:Admin');
$user = $repo->findOneBy(array('id'=>$session->get('id')));
$sum = $user->getWallet();
return new JsonResponse(array('sum'=>$sum));
here $sum is fetching a float val from the db (doctrine)
I have also tried this post's solution but it instead stops displaying the value on the page
I don't want quotes to be displayed around the fetched value, any suggestion for that? also ask for more elaboration if you want.
Json stringify adds the quotes, since it's intended to serialize data before sending them to server.
You probably want to invoke json.parse, or even just do nothing, as jquery will parse the json for you.

Sending special characters in Ajax POST and JSON

#SOLVED
As explained by James M. Lay, I should change my content-type from application/x-www-form-urlencoded to application/json
it implied in an error because it seems that only UrlEnconded types generates POST arrays in server side (at least in PHP). So I had to change the way I receive/deal with the request in my server script
$json = file_get_contents('php://input'); //yes. php://input
if($json) $params = json_decode($json,true);
else $params = $_POST;
I also had to make a few changes in the Javascript code to check the content-type and generate different strings. If it's JSON I just use JSON.stringify
//string to use in the 'send' method
this.getParametersString = function(){
if(this.contentType == 'application/json'){
return JSON.stringify(this.parameters);
}else{}
}
I got a question
I`m building a function that receive parameters to write a list of parameters and send it by POST
The problem is that we can't send special characters, such is +
So I tried to use the function encodeURIComponent to encode them to a URI friendly string.
There comes another problem: if the parameter received is an object, I am loop through the attributes, checking if it is another object or a string, if it is an object, loop again, otherwise encode it.
But it is returning an object of encoded strings. I have to make the object become a string to send it, and for that purpose I use JSON.stringify. It decodes the encoded string. So %2B becomes + again and It is not sent to the server via POST.
on the other hand If I use stringify first and the encodeURIComponent it generates signs like " and { } that shouldn't be encoded and the string is not a well written JSON
How do you that? Is that a way without using jQuery? Do I have to build my own stringify function?!
im using the following and i have no issues
encodeURIComponent(JSON.stringify(object_to_be_serialised))

How to preserve variable type when posting to php from javascript

When I use ajax to post data from Javascript to PHP, the php $_POST variables are always strings. Is there any way to preserve the variable type when posting. EG when posting a boolean true I want a boolean true and not a string 'true'.
You can use JSON as format and the PHP json parser will do it for you.
You can find an example here:
http://php.net/manual/en/function.json-decode.php#90790
Not possible directly: values will always be initially read as strings on the PHP side.
If you need to coerce the values into other types and cannot hardcode these types in your code you will need to arrange for "type information" to be passed to PHP (also as a string). That's how protocols that inherently provide data type support, such as SOAP, work.
As said above, you can let the JSON parser be do it for you.
You can also try it by yourself by checking the values.
Like boolean: is_bool
http://php.net/manual/en/function.is-bool.php
Like int: is_int
http://php.net/manual/en/function.is-int.php
etc.
This can be done when you have the POST values, and check for example the number field if it is a int:
<?php
$numberIsInt = is_int($_POST["number"]);
if($numberIsInt) {
//Do something
} else {
//Return error or do something else
}
?>

How do I remove the square brackets at the end of a JS variable name during AJAX calls?

I currently have the following javascript array:
var stuffs = ['a', 'b'];
I pass the above to the server code using jQuery's load:
var data = {
'stuffs': stuffs
};
$(".output").load("/my-server-code/", data, function() {
});
On the server side, if I print the content of request.POST(I'm currently using Django), I get:
'stuffs[]': [u'a', u'b']
Notice the [] at the prefix of the variable name stuffs. Is there a way to remove that [] before it reaches the server code?
This is default behavior in jQuery 1.4+...if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:
$.ajaxSetup({traditional: true});
Note this affects all requests... which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.
When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.
POST requests work in exactly the same way (unless the json is sent as one long json string).
In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.
I'm not sure how Django parses query strings.
The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django's way of telling you it is an array. You could probably implement your own print function which does not show them.

Categories