how to send json data headers to api - javascript

I am trying to send SMS through my web app, I bought bulk SMS from SMS supplier, trying to engage with their api.thanks in advance for your help
I post the data through postman and it works (post method, headers section), when I post data from my webpage to their URL it doesn't work,
$(document).ready(function() {
// Add event listener for opening and closing details
$('#testbut').on('click', function() {
var Username = 'xxxxxx';
var password = 'xxxxx';
var language = '1';
var sender = 'RitaFoods';
var Mobile = '2011xxxxx';
var message = 'hello from the other side';
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST",
"headers",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
dataType: "JSON",
success: function(data) {
alert("done");
alert(JSON.stringify(data));;
}
})
});
});
when I sending this data to another page on my web site, I received it with no problem , and i response with the parameters and alert it, when I sending to api url it gives no response, maybe because I need to send in headers section but I don't know how to do this.

You can set header with the beforeSend function
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
beforeSend: function(xhr){xhr.setRequestHeader('My-Custom-Header', 'My-Value');},
dataType: "JSON",
success: function (data) {
alert("done");
alert(JSON.stringify(data));;
}
});
or via the headers field
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST", "headers",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
headers: {
'My-Custom-Header': 'My-Value',
},
dataType: "JSON",
success: function (data) {
alert("done");
alert(JSON.stringify(data));;
}
});

Look at the API documentation.
It says "Post in header not in body", but as a description of what you need to do, this is wrong.
Look at the examples. They show that the data is encoded in the query string of the URL. In HTTP terms, that means it goes in the start line, not a header.
So you need to do something like:
var url = new URL("https://smsmisr.com/api/webapi/?");
url.searchParams.append("Username", Username);
url.searchParams.append("Password", password);
// etc etc
$.ajax({
url: url,
method: "POST",
dataType: "JSON",
success: function(data) {
alert("done");
alert(JSON.stringify(data));;
}
})
See this answer if you need compatibility with older browsers.
Be warned that you are likely to run into the problem described in this question.

try to add in your ajax
contentType: "application/json"
$.ajax({
type: "POST",
url: **your URL**,
data: **your DATA**,
contentType: "application/json",
});

Related

Can't sending data from View to Controller

can you help about that issue?
I am trying to pass my data to the controller. Below you can see my ajax code.
<script type="text/javascript">
$(document).on("click", "#login_button", function () {
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
if (userName !== "" && password !== "") {
$.ajax({
url: '/Home/Login',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {
'userName' : userName,
'password' : password
},
datatype: 'json',
success: function (data) {
}
})
}
else {
alert("Lütfen Alanları Doldurunuz.")
}
})
</script>
And my controller is like,
[HttpPost]
public ActionResult Login(string userName, string password)
{
return View();
}
I checked my data and it is not empty or null. How can I fix it?
Now I am getting this error =
jquery.min.js:4 POST http://localhost:59277/Home/Login 500 (Internal Server Error)
Thanks a lot.
I had the same problem today during a programming competition.
What solved it for me was using a different way of sending a GET request:
$.get("URL/to/send/request/to", function(data, status){
alert("Data: " + data + "\nStatus: " + status);//data is the actual response you get, while status is weather the request was successful
});
});
Hope it works for you too.
i thik you should use
url: 'http://stackoverflow.com/Home/Login',
instead of
Home/Login
i solve my problem changing the type of ajax as "GET" and changing my controller as "HttpGet" but when I do this for "POST" it didn't solve. Can anyone explain it to me?
$.ajax({
url: 'http://stackoverflow.com/Home/Login',
type: "POST",
dataType: 'json',
data: dataToPost,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("hi" + data);
}
});
i think it is work

Getting Pop up window to login with basic authentication using Ajax?

Here I am trying to access reed.co.uk rest webapi to fetch all related jobs, When I call the URL, its showing this popup window even though I am passing username and password. This is the alert message I am getting:
http://www.reed.co.uk is requesting your username and password.
WARNING: Your password will not be sent to the website you are
currently visiting!
Pls help me where i am doing wrong.
Here is the Ajax code
var username = "xxxxx xxxxxxxxxxxxxxx";
var password = "";
function getAuthorizationHeader(username, password) {
var authType;
var up = $.base64.encode(username + ":" + password);
authType = "Basic " + up;
console.log(authType);
return authType;
};
$.ajax({
type: "GET",
url: "http://www.reed.co.uk/api/1.0/search?keywords=Software Engineer&locationName=London&distanceFromLocation=50",
dataType: 'jsonp',
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', getAuthorizationHeader(username, password));
},
success: function (response) {
console.log(response);
}
});
I tried passing Authorization header like this also but still i am getting pop up window
headers: {
'Authorization': getAuthorizationHeader(username, password)
},
It looks like it is expecting Basic Authentication. Thus you need to supply it at url.
For example:
$.ajax({
type: "GET",
url: "http://"+username+":"+password+"#www.reed.co.uk/api/1.0/search?keywords=Software Engineer&locationName=London&distanceFromLocation=50",
dataType: 'jsonp',
async: false,
success: function (response) {
console.log(response);
}});

jQuery Ajax request turn into AngularJS $http request

I have such jQuery Ajax request. I need to turn it into an AngularJS $http request. How can I do that?
$.ajax({
type: "POST",
dataType: "jsonp",
crossDomain: false,
data:{
user: username,
pass: password
},
beforeSend: function (request){
request.setRequestHeader("Accept-Language", languageCode);
},
url: someUrl
})
.done(function (data, textStatus, jqXHR){
console.log(data);
})
.fail(function (jqXHR, textStatus){
console.log("failed");
});
My Angular Implementations
Response {"data" : "", "status" : "200", "config" : .... } Data is empty
login : function (username, password) {
return $http({
method: 'POST',
url: someUrl,
data: {
user: username,
pass: password
},
headers: {
'Accept-Language': languageCode
}
})
}
I succeeded to get data wrapped in JSON_CALLBACK with next request. But I don't know how to call that callback. It is not done automatically. Response looks like {data:"JSON_CALLBACK({mydata})"...}
login : function (username, password) {
var url = someUrl
+ '?callback=JSON_CALLBACK&user=' + username
+ '&pass=' + password;
return $http.post(url);
},
There is no such thing as a JSONP POST request. When jQuery sees dataType: jsonp, it ignores the method propery and uses a script GET request. The data is added as parameters of the URL.
In AngularJS, JSONP requests are specified with method: 'JSONP. The callback parameter needs to be JSON_CALLBACK and must be capitalized.
login : function (username, password) {
return $http({
//method: 'POST',
method: 'JSONP',
url: someUrl,
//data: {
params: {
user: username,
pass: password,
callback: "JSON_CALLBACK"
},
headers: {
'Accept-Language': languageCode
}
})
}
Be aware that since the data is sent as URL parameters, sensitive information such as passwords are vulnerable to snooping attacks.
To demonstrate on JSFiddle:
var url="//jsfiddle.net/echo/jsonp/";
var params = { user: "myUser",
pass: "123456",
callback: "JSON_CALLBACK"
};
$http.jsonp(url, { params: params} )
.then(function onSuccess(response) {
$scope.response = response;
console.log(response);
})
The DEMO on JSFiddle.
Please refer to $http documentation. but here is somewhat counterpart for that jquery request
$http({
method: 'POST',
url: '/someUrl',
data: {
user: username,
pass: password
},
headers: {
'Accept-Language':languageCode
}
}).then(function successCallback(response) {
//do something
}, function errorCallback(response) {
//do something
});
AngularJS error .success is not a function
Might have something to do with it??
What API are you working with?

Facebook Graph jQuery AJAX call to post a photo on user's behalf

I'm trying to post a photo on the users behalf. I've been searching the web for the last 4 hours and I'm out of ideas.
JS:
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})
the error function outputs the following:
[object Object]|error|Bad Request
I think there must be something wrong with the ajax request itself, but I can't figure out what it is. I've reconstructed my request using the Facebook Graph API explorer and everything works fine there. Any ideas?
Need to define the correct data type in the ajax request ( jsonp ), just try this will work :
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
dataType: "jsonp", //Just add this line ( jsonp not json ),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories