Im working on a project, where we try to exchange different parameters between the UI and a RestAPI via AJAX. The RestAPI defines how the data has to look:
I tried to solve it this way:
$(document).ready(function(){
$("#submit").click(function(){
var credentials = [
{user_name: $("#uname").val(),
password: $("#pwd").val()
}
];
alert(credentials);
$.ajax({
url:"../rest/user/login",
type:"POST",
data:JSON.stringify({credentials: credentials}),
success: function(){
window.location.href = "startrackhome.html";
},
error: function error(response){
try{
var json = JSON.parse(response.responseText);
if(typeof json.message === 'undefined'){
throw new Error("Response json has no message");
}
else{
alert(json.message);
}
}
catch(ex){
alert("unexpected error (code:" + response.status +")");
}
}
});
});
});
The alert shows this: [object Object]
And I always get an error message (error: 400), which means that I mus have made a mistake and I think the format I'm sendig is wrong but I dont know how to fix it.
I hope you can help me! :)
I made some changes to your code :
// credentials is an object
var credentials = {
user_name: $("#uname").val(),
password: $("#pwd").val()
}
alert(credentials);
$.ajax({
// check this url seems a bit off
url: "../rest/user/login",
type: "POST",
data: {
credentials: credentials
},
success: function() {
window.location.href = "startrackhome.html";
},
error: function error(response) {
try {
var json = JSON.parse(response.responseText);
if (typeof json.message === 'undefined') {
throw new Error("Response json has no message");
} else {
alert(json.message);
}
} catch (ex) {
alert("unexpected error (code:" + response.status + ")");
}
}
});
in my case it makes this request :
fetch("https://stackoverflow.com/posts/rest/user/login", {
"headers": {
"accept": "*/*",
"accept-language": "",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Linux\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://stackoverflow.com/posts/72620005/edit",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
credentials[user_name]: test
credentials[password]: test
which seems good, if the server needs a json, you can stringify the credentials, which gives this paylaod :
credentials: {"user_name":"test","password":"test"}
Related
I'm able to successfully post to the createCustomerProfile endpoint using ARC, but NOT with a simple AJAX post inside javascript. I'm using the following AJAX request:
$.ajax({
type: "POST",
crossDomain: true,
url: 'https://apitest.authorize.net/xml/v1/request.api',
dataType: "json",
data: createCustomerProfileRequest,
success: function (response) {
if (response.dataValue == "Error") {
alert(response.dataDescriptor);
} else {
alert('Successfully sumitted payment!');
}
$("#ccButton").attr("disabled", false);
},
error: function (error) {
alert('Could NOT submit payment!');
$("#ccButton").attr("disabled", false);
}
});
My data is verified to be the following:
"createCustomerProfileRequest": {
"merchantAuthentication": {
"name": "myActualApiKey",
"transactionKey": "myActualTransactionKey"
},
"profile": {
"merchantCustomerId": "Homer Simpson",
"description": "Creating Customer Profile for: Homer Simpson",
"email": "crodgers#newbenefits.com",
"paymentProfiles": {
"customerType": "individual",
"payment": {
"creditCard": {
"cardNumber": "6011000990139424",//Test credit card
"expirationDate": "2028-01"
}
}
}
}
}
}
I'm not certain what i'm doing wrong here. I know i have to have the crossDomain set to true but i keep running into the following parsing error:
"Unexpected character encountered while parsing value: c. Path '', line 0, position 0."
What is causing this to happen in the browser (i'm using Chrome) and NOT when using ARC?
I needed to stringify the JSON i was sending. This will work:
$.ajax({
type: "POST",
crossDomain: true,
url: 'https://apitest.authorize.net/xml/v1/request.api',
dataType: "json",
data: JSON.stringify(createCustomerProfileRequest),
data: createCustomerProfileRequest,
success: function (response) {
if (response.dataValue == "Error") {
alert(response.dataDescriptor);
} else {
alert('Successfully sumitted payment!');
}
$("#ccButton").attr("disabled", false);
},
error: function (error) {
alert('Could NOT submit payment!');
$("#ccButton").attr("disabled", false);
}
});
Here is the URL to which I'm making POST request:
https://www.googleapis.com/webmasters/v3/sites/http://mywebsite.com/searchAnalytics/query?key=key&startDate=2018-07-01&endDate=2018-09-01&dimensions=["country","device"]
I'm getting Not Found as response. I'm following exactly as docomunted by Google. What am I missing here.
Here is my code in Nodejs
request.post({
url: url,
auth: {
'bearer': access_token
}
}, function(err, response) {
if(err)
{
res.status(500).send({ error: "google error", data: null, message: "Oops! Please try again" });
}
else {
console.log(response);
}
});
There were many things which needed to be corrected. Here is the final code which worked.
website = stripTrailingSlash(website);
website = encodeURIComponent(website);
var url = 'https://www.googleapis.com/webmasters/v3/sites/'+website+'/searchAnalytics/query?key=yourKEY';
console.log(url);
var bearerToken = 'Bearer '+ access_token;
var options = {
url: url,
headers: {
'Authorization': bearerToken,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
json: {'startDate':'2018-02-01','endDate':'2018-09-01'}
};
request.post(options, function(err, response) {
if(err)
{
console.log(err);
res.status(500).send({ error: "google error", data: null, message: "Oops! Please try again" });
}
else {
console.log(response.body);
}
});
I have a Dojo ajax request and i am posting the data as json however the data is not reaching the server in json format. I am also not able to see the JSON tab in the browsers Net option of the console. I need the data in json format on the server.
Ajax Request
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
function SendData() {
var xhrArgs = {
url:'processData',
postData: someData,
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);
Screenshot of server details
I would like the JSON data under to appear in the following format under with the name MyData. How is this format possible on the server?
JSON
MyData [Object{id:"1",age:"44",name:"John"},
Object{ id:"2",age:"25",name:"Doe"},
Object{ id:"3",age:"30",name:"Alice"}]
SOURCE
{"MyData":[{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}]}
Actually url:'' is empty in your Ajax call. Please provide action url,
for suppose
url: "AddTrackServlet"
After playing around with the variable i saw it could be declared
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
var formData = {MyData:someData}
function SendData() {
var xhrArgs = {
url:'processData',
postData: dojo.toJson(formData),
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);
I am using Symfony2 and in my register.html.twig, I have:
var registerdata= {
"email": email,
"pwd": pwd,
"phoneNum": phoneNum
};
$.ajax({
type: 'POST',
url: "register",
data: registerdata,
success: function(msg){
alert("OK! ");
},
error: function(XmlHttpRequest,textStatus, errorThrown){
alert("Failed! ");
}
});
In my controller, after inserting those data into the database, I want to redirect to the login page, and I have code like this:
try
{
$this -> insertData($account);
return $this ->redirect($this ->generateUrl('login'));
}
catch (Exception $e)
{
return new response('Message: '. $e->getMessage());
}
It does not work, however. How should I handle the problem?
You need another more step in your jQuery code. When the server returns a redirect response, you should redirect the client using javascript:
var registerdata= {
"email": email,
"pwd": pwd,
"phoneNum": phoneNum
};
$.ajax({
type: 'POST',
url: "register",
data: registerdata,
success: function(msg){
alert("OK! ");
},
error: function(XmlHttpRequest,textStatus, errorThrown){
alert("Failed! ");
},
complete: function(xhr)
{
if (xhr.status == 302) {
location.href = xhr.getResponseHeader("Location");
}
}
});
Of course this is far from ideal.
I have a problem in my code . This is part of it:
function checkIfAvailable(username){
var url = "/checkAvail?user="+username;
var ans = $.ajax({
url: url,
type: "GET",
context: document.body,
statusCode: {
404: function() {
console.log("-1-1-1-1 WE GOT 404!");
},
200: function() {
console.log("-1-1-1-1 WE GOT 404!");
}
}
});
}
I think the response.status is 200, but I don't enter the '200' part.
So how can I print the response.status I'm getting?
success(data, textStatus, jqXHR){
var statusCode = jqXHR.status;
var statusText = jqXHR.statusText;
}
See jQuery API for more options...
function checkIfAvailable(username) {
var ans = $.ajax({
url: "/checkAvail",
type: "GET",
data: "user=" + username,
dataType: "html",//change it by the data type you get (XML...)
context: document.body,
statusCode: {
404: function() {
console.log("-1-1-1-1 WE GOT 404!");
},
200: function() {
console.log("-1-1-1-1 WE GOT 200!");
}
},
success: function() {
console.log("success");
},
error: function(e) {
alert(e);
}
});
}
Message inside console.log("-1-1-1-1 WE GOT 404!") is same for both 404 and 200. change the message for 200 like console.log("Success.....")