Implementing Ajax calls for a REST API - javascript

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

Related

How to hide an api key in AJAX request

I would like to done an ajax request directly done by client on desktop.
Problem is my ajax request need a "secret api Key". I don't want the client has an access to this api key.
Here my currently js code:
var url = 'myurl';
var obj = new Object();
obj.api_key = "myKeyIwantToHide";
$.ajax({ url: url,
type: 'post',
dataType: 'json',
data: obj,
cache: false,
success: function(result){
alert(result);
}
});
It is possible to hide information to client with javascript in order to done my ajax request.
Thx,
Christophe
You cannot hide the api key completely from client. But if your client is non technical. You can make it hard for him/her to find api key. If you are using MVC you can set the api key when the first request is sent to the Index method and on return you can set it to a javascript variable. In this way user wont be able to see hardcoded value unlike in the code you have shown. If you are using ASP.NET then you can easily use ViewBag to set value to javascript variable using razor syntax.

Trying to understand JQuery/Ajax Get/POST calls

Correct me if I'm wrong but it was my understanding that a POST was to be used if I was changing data, and a GET was to be used if I want to retrieve data.
Based on that assumption.
I have (MVC5) app.
My JavaScript
function MyLoadData(myValue) {
$.ajax({
method: 'POST',
url: '/Home/GetMyData',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ "MyValue": myValue}),
success: function (data) {
// Do Stuff
}
});
and my controller.
public JsonResult GetMyData(string myValue)
{ // Do Stuff }
This only works if I set the method: 'POST', if I set it to 'GET' it will still make the server call but not pass the myValue to the controller.
Also of note there is no data annotation on the GetMyData method.
In this scenario shouldn't I be using GET to get my data from the controller?
UPDATED based on comments:
function MyLoadData(myValue) {
$.ajax({
method: 'POST',
url: '/Home/GetMyData',
dataType: 'json',
data: { "MyValue": myValue},
success: function (data) {
// Do Stuff
}
});
Both POST and GET methods can pass the myValue to the controller.
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
The primary difference between a GET and a POST is that the POST will also submit the form data. In your example, you can use a GET by appending ?MyValue=<myValue> to your URL and WebAPI will assign the value to the Action's parameter.
If the GET request needs to work then use this code block:
function MyLoadData(myValue) {
$.ajax({
method: 'GET',
url: '/Home/GetMyData?myValue=test',
success: function (data) {
// Do Stuff
}
});
Basically, you can use GET or POST to get the data. but in GET, the data is passed through query string. In POST it can be passed both through query string as well as body.
One real world scenario when to use POST-Suppose your method expects Customer parameter and you need to send Customer object as parameter, then you can send the json representation of Customer object through body.but its not possible through GET.
One more reason is security,if you use GET, your method can be called through browser.but if you use POST, the method can't be directly called.
These were the important difference.For more differences see this link - http://www.diffen.com/difference/GET_(HTTP)_vs_POST_(HTTP)

jquery mobile web application developement( need help)

Can any one please tell me how to send data to web service using jquery and receive data from web service?
If we are using web service should we need to use url to get records?
$j.ajax({
type: "GET",
url: "testing.json",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
$j.each(data, function(index,element){
$j('#json').append("<li class='ui-li ui-li-static ui-btn-up-c ui-corner-top ui-corner-bottom ui-li-last'>"+element+"</li>");
});
}
})
});
I am developing web application using jQuery mobile.
Can any one please tell me how to send data to web service using jquery
Put it in a data property on the object you pass as the first argument to ajax().
How you format the data will depend on the particular web service.
Your existing code claims that it will be JSON so the data you pass to data should be a string representation of a JSON Text.
You will need to change the type to POST in order to do this though. The content-type request header describes the request body and you don't get one of those with a GET request.
(If the web service does not expect to receive JSON data then you will need to change the code to represent whatever it does expect).
and receive data from web service?
Read it from the first argument to the callback function you pass to the success function.
If it is in a known data format (XML, HTML or JSON), then jQuery should automatically parse it. Note that you have dataType: 'json' which will override whatever the server says it is sending back and try to parse it as JSON data regardless.
If we are using web service should we need to use url to get records?
Yes. URLs are how web server end points are identified.
a liitle example to get data from a web service using jquery ajax call
function GetData() {
$.ajax({
type: "POST",
url: "Members.asmx/GetMemberDetails",//your webservice call
data: "{'MemberNumber': '" + $("#txt_id").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnGetMemberSuccess,
error: OnGetMemberError
});
}
function OnGetMemberSuccess(data, status) {
//jQuery code will go here...
}
function OnGetMemberError(request, status, error) {
//jQuery code will go here...
}
Example: Introduction to using jQuery with Web Services

How do I do an ajax call to a database using Javascript, a URL and a key

I have been given a url of type xxxx.xxxxx.com as well as a key of type FGHyehgvc787vbhj
in order to gain read-only access to an sql database and retrieve data from it using javascript.
I have no prior experience with databases and maybe my question will sound completely stupid but I was wondering how can I combine the above information in order to get access to the database (e.g. do an ajax call and retrieve data from it..)
I'm familiar with doing ajax calls to a webpage and getting data from it using jQuery, as in :
$.ajax(/*url of website*/, function (data)
{
var dataRetrieved = $(data);
// do something with the data retrieved...
});
so I was wondering whether there is something equivalent to the above when it comes to making an ajax call to a database, using however a key.
Thank you for any help, and please delete this post if you find it completely pointless and excuse me in advance for that by the way.
It is usually very bad design to allow client side code to interact with your database in any way. This can be a huge security issue. Generally you will want your server side code to do this (e.g PHP, node, etc.). You would send a request to your server with client side code, and the server side code would do the actual work of updating the database.
you can create a wcf service and call that service through ajax, that wont be huge security issue.
try this
$.ajax({
cache: false,
type: "GET",
async: false,
data: {},
url: http:xxxxxxxxxxxx.svc/webBinding/Result?metaTag=" + meta,
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
success:function(result){},
error: function(){alert(err);}
});
Use this
$.ajax({
url: 'path/to/server-side/script.php', /*url*/
data: '', /* post data e.g name=christian&hobbie=loving */
type: '', /* POST|GET */
complete: function(d) {
var data= d.responseTXT;
/* Here you can use the data as you like */
$('#elementid').html(data);
}
});
Hope this helps...

How can I send an javascript object/array as key-value pairs via an AJAX post with easyXDM?

Recently I realized that I needed to use easyXDM instead of jQuery's $.ajax in order to make a cross domain post request. After getting easyXDM set up I see that the functions line up fairly closely:
jQuery:
$.ajax({
url: "/ajax/",
method: "POST",
data: myData
});
easyXDM:
xhr.request({
url: "/ajax/",
method: "POST",
dataType: 'json', // I added this trying to fix the problem, didn't work
data: myData
});
myData is setup something like:
myData = {};
myData[1] = 'hello';
myData[2] = 'goodbye';
myData[3] = {};
myData[3][1] = 'sub1';
myData[3][2] = 'sub2';
myData[3][3] = 'sub3';
When I make the request with jQuery it handles the sub fields properly, but not with easyXDM.
Here is how the POST request comes into the server with jQuery:
screenshot-with-shadow.png http://img37.imageshack.us/img37/4526/screenshotwithshadow.png
And here is how it comes in with easyXDM:
screenshot-with-shadow.png http://img204.imageshack.us/img204/4526/screenshotwithshadow.png
How can I send an javascript object/array of key-value pairs via an easyXDM / XHR request like jQuery does?
In light of the limitations of easyXDM discussed in the comments, the only way you can use it would be to serialize your data manually when passing it to .request i.e.
xhr.request({
url: "/ajax/",
method: "POST",
data: {jsonData: JSON.stringify(myData)}
});
Alternatively you could create your own postMessage solution but you will be excluding IE7 and below.
I think you are mistaken about sending a request cross-domain via AJAX. You CAN indeed send a request cross-domain via AJAX regardless of the JavaScript API. However, in order to receive a response cross-domain, the response needs to be of data type JSONP.
JSONP is simply JSON with padding, for example:
JSON:
{ Key: "Hello", Value: "World" }
JSONP:
callback({ Key: "Hello", Value: "World" })
It is a subtle difference but JSONP by-passes browser same-origin policy and allows you to consume JSON data served by another server.
To consume JSON data coming from another server via jQuery AJAX try this:
$.ajax({
url: "http://mydomain.com/Service.svc/GetJSONP?callback=callback",
dataType: "jsonp",
data: myData,
success: function(data) {
alert(data);
}
});
For this to work you must make sure that your web service is returning results as JSONP and not JSON.
As easyXDM can't serialize properly you need to serialize data manually:
JSON.stringify(myData)
Since the request will now contain a json string rather than object then Index.html should not parse the properties to create json structure. Go to index.html that comes with easyXDM and locate the following code:
var pairs = [];
for (var key in config.data) {
if (config.data.hasOwnProperty(key)) {
pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(config.data[key]));
}
}
data = pairs.join("&");
Don't execute this code in a case of POST request. Just assign config.data to data:
data = config.data;

Categories

Resources