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.
Related
I have an application that is written on the top of ASP.NET MVC 5 framework. For one page, I am using this awesome jQuery-QueryBuilder plugin to let the user create filters to narrow down the results of the dataset.
When the user submits the form "by clicking the submit button" I want to call a function builder.queryBuilder('getRules') provided by jQuery-QueryBuilder which returns and object that needs to be sent to the server. I don't want the request to be sent as string. Also I don't want to sent it as ajax request.
Here is what I have done. The following code is not working. When the server receives the request the rules are always null.
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$('#QueryBuilder_Rules').val(rules);
btn.closest('form').submit();
}
});
I tried to use AJAX to send the post request to the server like the code below shows. The code below worked fine. However, I don't want to use AJAX, I want to do the same thing using regular form post request
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$.ajax({
type: "POST",
url: url,
data: {Rules: rules}
});
}
});
How can I correctly send the rules object as an object not a string to the server using standard post request?
What is the problem in using Ajax?
You may consider doing the following:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({Rules: rules}),
dataType: "json",
contentType: "application/json",
success: function (json) {
}
[HTTPPost]
public void Rules(YourClass[] array){...}
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);
});
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
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...
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;