I'm new to AJAX and I want to generate a password over this API. I want to use AJAX but dont know exactly how and where to specify the parameters.
$.ajax({
url: 'https://passwordwolf.com/?length=10&upper=off&lower=off&special=off&exclude=012345&repeat=5',
dataType: "text json",
type: "POST",
data: {upper: off, lower: on, special: off},
success: function(jsonObject,status) {
console.log("function() ajaxPost : " + status);
}
});
Many Thanks, Pls don't hate my programming skills!
Having a look at their API:
You should use the GET method, not POST.
The url should be https://passwordwolf.com/api/ (notice the /api at the end).
Besides, passwordwolf doesn't accept CORS, so you should probably call that service from your server side and mirror it to your frontend with the appropriate CORS headers.
See demo below (it uses cors-anywhere to circunvent the CORS problem).
It also shows how to correctly use an object to set params.
var CORS = 'https://cors-anywhere.herokuapp.com/';
$.ajax({
url: CORS + 'https://passwordwolf.com/api/',
dataType: "json",
type: "GET",
data: {
length: 10,
upper: "off",
lower: "off",
special: "off",
exclude: "012345",
repeat: 5
},
success: function(jsonObject, status) {
console.log("ajax result: " + JSON.stringify(jsonObject));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I am a problem with simple javascript web page hosted on AWS S3 that makes a HTTP POST to AWS API Gateway using ajax.
I am able to make a call using curl with success:
curl -X POST -H "Content-Type: application/json" https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta --data #data.json
data.json file:
{ "imie": "jasiu",
"ocena": "6",
"opinia": "niezle"
}
My javascript code looks like this.
<html>
<body>
<title>Ankieta</title>
<h1>Wypelnik ankiete</h1>
<button type="button" onclick="uruchom()">JSON</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function uruchom() {
var resultDiv = $("#resultDivContainer");
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: JSON.stringify(myData),
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
};
</script>
</body>
</html>
This is the error I get from web debug:
GET https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta?callback=jQuery17203000220305941388_1546897907447&{%22imie%22:%22Michal%22}&_=1546897908872 net::ERR_ABORTED 400
It looks like there is problem with callback and in the URL is altered with my data from body. In my case I don't want to check whenever the callback is fine - want to simply POST data.
Thanks for any suggestions.
POST can't be used to send a JSONP request. JSONP doesn't actually use AJAX, it works by creating a <script> tag whose src is the URL. There's no way to send POST data this way, so the data is added as URL parameters.
If this API expects the JSON in POST data, you can't use dataType: 'jsonp'. You have to use dataType: 'json'. If the API doesn't allow CORS, you'll need to use a proxy on your server to make the actual request, you can't do it directly from the browser.
Dont stringify the data object. JQuery does this for you. Just pass object.
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: myData,
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
Thanks for suggestions and answers especially in CORS direction. I was sure my API GW has CORS enabled, but didn't check AWS Lambda that is behind it and found that I was not returning "Access-Control-Allow-Origin" header back to client.
exports.handler = function(event, context, callback) {
callback(null, {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
});
};
After applying this, I can send HTTP POST.
I'm trying to convert the curl code from an API called TextRazor to jquery's AJAX because of a platform limitations. I have tried many solutions from similar questions by the community but can't seem to get any data back (through the alert dialog). If it matters
from the documentation calling the API looks like this:
curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off..." \
https://api.textrazor.com/
My current AJAX code looks like this:
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
data: {
x-textrazor-key: "YOUR_API_KEY",
extractors: "entities,entailments",
text:"Spain's stricken Bankia expects to sell..."
},
success:function(data) {
alert(JSON.stringify(data));
},error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}});
here is the link to jsfiddle if it helps: jsfiddle.net
Thanks for your support!
I think you have to pass "x-textrazor-key: YOUR_API_KEY" as additional header
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('x-textrazor-key', 'YOUR_API_KEY');},
data: {
extractors: "entities,entailments",
text:"Spain's stricken Bankia expects to sell..."
},
success:function(data) {
alert(JSON.stringify(data));
},error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}});
data: {
x-textrazor-key: "YOUR_API_KEY",
The data: bracket in jQuery means that you want to send that data as POST, while you need to send the API key as a header.
Add this field to your code (after URL or so):
headers: {"x-textrazor-key": "YOUR_API_KEY"}
This looks close to me, but you put the header into the POST body. I think it should be the below. (Note that you also need quotes around 'x-textrazor-key', since the dashes in it will otherwise be interpreted as subtraction.)
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
headers: {
'x-textrazor-key': "YOUR_API_KEY"
},
data: {
extractors: "entities,entailments",
text: "Spain's stricken Bankia expects to sell..."
},
success: function (data) {
alert(JSON.stringify(data));
},
error: function (xhr) {
alert("<some error>");
console.error(xhr.responseText);
}
});
There could of course be other issues here. (E.g. perhaps the API doesn't support cross-origin requests.) You'll want to take a look at the network tab in your browser's developer tools to see what actually happens.
I should make a json call with javascript:
var arr = { username: "user#user.com", password : "mypassword" , portfolioID : "xxxxxxxxxxxxxxxxx" };
$.ajax({
url: 'https://siam.eseye.com/login',
type: 'POST',
data: JSON.stringify(arr),
dataType: "json",
contentType: 'application/json; charset=utf-8',
async: false,
success: function(msg) {
alert(msg);
}
});
the error that comes back to me : CORS header " Access- Control-Allow -Origin " missing .
Attention, before saying that it is a double question , read here , I searched online and I did :
inserted header ( " Access- Control-Allow -Origin : * " ) ;
Wamp > Apache > Apache Modules > headers_module enabled
added the datatype
dataType: json or jsonp the error remain
after all of this evidence , it will not work the same .
Is there anything else I forgot to try?
with Postman the API work.
Thank you.
You may need to use dataType: "jsonp" which is use for cross site scripting.Check here for more about jsonp
I created this JSFIDDLE. The request semms to be served but the response have error. You can validate it console in developer's tool
I have copied my phonegap project to steroids but now my ajax commands fail to work, I have no clue at all what is causing it so any suggestion might be helpfull.
This is the code that causes the problem, it always terinates to error with request.status = 0:
$.ajax({
type: "POST",
url: serverUrl + "login.ajax",
data: { jsonLogin: JSON.stringify(loginObject), deviceInfo: JSON.stringify(deviceInfo)},
async: true,
timeout: 7000,
cache: false,
headers: { "cache-control": "no-cache" },
success: function(data) {
...
},
error: function(request, status, err) {
...
},
complete: function(){...}
});
AppGyver employee here!
In config/application.coffee, is your steroids.config.location = "http://localhost/index.html" or just index.html? Steroids serves app files via localhost (i.e. an internal web server on the phone) whereas PhoneGap uses the File protocol. Using localhost makes the WebView enforce stricter CORS rules, so you need an Access-Control-Allow-Origin header to the server response. HTML files served via the File protocol let cross-domain requests go through without CORS headers.
You can find a test project with an AJAX test at https://github.com/appgyver/steroids-runtime-tests
I think jQuery does not parse the json data becaus eyou have not specified the dataType
$.ajax({
type: "POST",
url: serverUrl + "login.ajax",
data: { jsonLogin: JSON.stringify(loginObject), deviceInfo: JSON.stringify(deviceInfo)},
dataType: json, //Specify data type
async: true,
timeout: 7000,
cache: false,
headers: { "cache-control": "no-cache" },
success: function(data) {
...
},
error: function(request, status, err) {
...
},
complete: function(){...}
});
How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];