javascript json request with some parameters - javascript

So a simple question:
JavaScript needs to send to server that request:
myserver/scipt.php?LANG=EN&AGENT={"Login":{"name":"user","pass":"user"}}
How I need to form url and data in Ajax?
Is this right?
var formData = {
"login":$("#field1").val(),
"pass":$("#field2").val()
};
$.ajax({
url:'http://myserver/scipt.php?LANG=EN&',
type:'GET',
data:'AGENT=' + $.toJSON(formData),
success: function(res) {
alert(res);
}
});
Thank you!

I'd recommend sending JSON via POST instead of GET. GET has some limitations that you want to avoid.
A part from that, yes, your code seems ok.
EDIT:
Sorry, your code is not ok.
Change the data line to:
data: $.toJSON(formData),

You need to send the data to the server in the form of a map ..
Your data is already in json format.. You need not do $.toJSON again
Instead of
data:'AGENT=' + $.toJSON(formData),
send it this way
data:{ 'AGENT' : {'Login' : formData } },

You need to URL encode any strings you want to pass through Ajax.
If jQuery works anything like a normal form, you also need to put all your query string data into data to avoid the existing query string being destroyed.
url:'http://myserver/scipt.php',
type:'GET',
data: {
"AGENT": $.toJSON(formData),
"LANG": "EN"
},
Note, you should use POST requests if you are transmitting user credentials. You don't want them cached or stored in server access.log files.

Related

why i cant send data to .json format file by ajax

I'm making a simple server to send data to a .json file and receive that data from another page but I have problem how to store data in .json file
I used following code but it didn't work
<script src="jquery/jquery-3.4.1.min.js"></script>
<script>
var _lname = "x";
var _fname = "y";
var _mname = "x";
$.ajax({
type: "POST",
url: "data.json",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
}
});
</script>
Simply POSTing data to a JSON file won't work, as sending a POST request requires the server to listen for requests and do something with the payload you sent. You could make a simple NodeJS or PHP script (or any other server-side language for that matter) that could handle saving the payload to a JSON-file.
When you make a POST request, you send data to a web server.
The web server can do something with the data in the POST request.
By default, it does nothing. Imagine the problems that would be caused if anybody could make a POST request to anyone else's web server and write a new file to it. Google's homepage would be defaced every other second.
If you want to store the results of a POST request, then you need to write server-side code to do it (and you almost certainly will want to perform authentication and authorisation when you do so).
Note that the value of data: in your example code will never be valid JSON. Don't try to write JSON by mashing strings together. Use a library function like JSON.stringify.

How to make such a structure in javascript

I'm new to JS. And have a basic silly doubt. Please bear with me.I want to send a request of the form:
{"user":{"username":"myuser","password":"mypass","role":"myrole"}, "organization":"org_name"}
such that the user object can be access by req.body.user and organisation can be accessed by req.body.organization.
But when I'm sending this request:
it translates to-
{
"user[username]": "myuser",
"user[password]": "mypass",
"user[role]": "myrole",
"organization": "org_name"
}
When I just send
{"user":{"username":"myuser","password":"mypass","role":"myrole"}}
then I can access using req.body.user, but not the way mentioned above. Why is this so?
How can I send the request now such that I can access the request.body.user and req.body.organization properly?
EDIT:
This is how the request is sent. Front end: ember, backend node/express:
Ember.$.post("http://"+window.location.hostname+":3000/api/organizations/customer",{"user":{"username":"myuser","password":"mypass","role":"myrole"}, "organization":"org_name"},function(data){
console.log(JSON.stringify(data),null, " ");
});
Receiving side:
console.log(JSON.stringify(req.body,null," "));
I am trying to create the user but req.body.user is undefined. Though I can use user[username] and proceed, but that s now how I want to do
You aren't sending JSON to the server. Passing an object in as data doesn't send it as an object; it simply gets converted to a query string [source]. If you want to send JSON, you need to use JSON.stringify on the data that you send, not the data you receive.
Ember.$.post("http://"+window.location.hostname+":3000/api/organizations/customer",JSON.stringify({"user":{"username":"myuser","password":"mypass","role":"myrole"}, "organization":"org_name"}),function(data){
console.log(data);
});
With the help of Christian Varga's answer to this post, I could further dive in. Though the problem was still not solved, but it gave some insight of how can that be solved.
This is what I did next for such a structure. As per his suggestion, I used JSON.stringify but at a different place:
Ember.$.post("http://"+window.location.hostname+":3000/api/organizations/customer",{"user":JSON.stringify({"username":"myuser","password":"mypass","role":"myrole"}), "organization":"org_name"},function(data){
console.log(data);
});
On the backend server side I could then receive req.body.user. But the req.body.user was stringified JSON. To further access this inner JSON, I had to use JSON.parse.
Though this worked, but I was looking for more better solution, since this backend change worked for my front end implementation, but was failing for RESTClient.
I understood I need to pass the contentType of the data to be sent in the post request. I could not find $.post argument for contentType. So then I used $.ajax call.
Ember.$.ajax({
url: "http://"+window.location.hostname+":3000/api/organizations/customer",
type:"POST",
data: JSON.stringify({user:{username:username,password:password,role:role}, organization_id:organization_id}),
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function(data){
console.log(JSON.stringify(data),null, " ");
}
});
where the username, password, role, organization_id are already assigned variables.

Implementing Ajax calls for a REST API

I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});

How do I send brackets "%5B" "%5D" as params on an Ajax Request using GET as method?

Using Ajax and the method GET, I am trying to send an url with brackets, but I am not getting the right encoding of them:
Request URL:http://myurl/search.html?_dc=1382510050331&search%5Bpostcode%5D=96231
instead of:
Request URL:http://myurl/search.html?_dc=1382510050331&search[postcode]=96231
Error:
Status Code:502 Host not found
Here is a snippet of my code:
Ext.Ajax.request({
url: 'http://myulr.lan/fpsearchjson.html',
method: 'GET',
params: {
"geosearch[postcode]":91111
},
success: function(response){
console.log("success");
},
failure: function(response){
console.log("failure");
}
});
Any help will be appreciated!
%5B and %5D are the url-encoded values of [ and ]. This should be encoded like it is in your example.
The problem seems to be that you are unable to reach the server. Try to reach the server in any way. Maybe open the URL in your favorite browser or telnet to it: telnet my.server.com 80
You need to convert your Get request though ajax should first convert to ASCII, same problem happen to me I solve it though convert my GET request into ASCII and again decode for use :)
You can use escape function to encode ,decode your url and parameter. On other side you can easily get that value in original format
for example
escape("It's me!") // result: It%27s%20me%21

Ajax message best practices

Say I need to use ajax to asynchronously ask the server for an xml file containing relevant data. What is the best practice on what this message should look like? Should it be a string like get_data or something similar? Should it be xml? I don't really need long polling since its a one-time (or close to it) request.
Thanks.
You can use standard a HTTP Post or Get to send the request to your server. If you don't need to specify any parameters to your server side script ( user_id, etc ) then simply appending get_data as a url parameter will work fine.
http://www.domain.com/script?get_data
If you need to send any parameters to the server in order to retrieve data it is best to encode the parameters in JSON or XML and send them as the data portion of your AJAX request. With JQuery and JSON data:
$.ajax({
type: "GET",
url: "http://www.domain.com/script",
data: { key: "value", key2: "value2" },
async: true,
dataType: "json",
success: function( data, textStatus ) {
someCallbackFucntion( data );
}
});
The message should be the url.
For example: http://www.example.com/get_data could return the data you need in the format you need (xml, json).
If you need some other data, use an other url. http://www.example.com/someotherdata
It really depends on the purpose, if everything else is XML, go for XML. Personally I perfer JSON (for the client-side at least).
In a recent implementation I made, I used a simple POST request where the key represented the type of data and the value contained the time-interval it should return.
Which could be (jQuery):
$.ajax({
type: "POST",
url: "http://www.domain.com/script",
data: { stock_value: "last_30_min", group_activity: "last_20" },
async: true,
dataType: "json",
success: function( data, textStatus ) {
someCallbackFucntion( data );
}
});
A server-side controller would then handle the request appropriately and the client-side would know what data to expect when it returned. Also the key and value would be humanly readable from both client- and server-side. Of course the time-intervals could be a timestamp or otherwise, whatever fits the need.

Categories

Resources