How to send data to a web Service Using Winj.xhr - javascript

I am new in Winjs coding I have data in a list .
and i want to send that data to my json Web Service .
I have a success to call to web service and i have the response so the web service is
working but the data doesn't seem to be sent. I dont know how to declare the data.
I have many data to sent like(username,first_name,last_name,password) to my Register.json
The Register.json have this response after the execution:
{
"format":
"json",
"success":
false,
"errors":
["User name is empty"],
"result":
null
}
so i m sure that data doesnt be sent
function Register() {
var dataArray = [
{
username: "Marley",
first_name: "dog",
last_name: "ded",
password: "pdre4252d"
}];
WinJS.xhr({
url: "my_Base_URL/Register.json",
type: "post",
headers: { "Content-type": "application /x-www-form-urlencoded" },
data: dataArray
// data:JSON.stringify(dataArray)
}).done(
function complete(result) {
if (result.status === 200) {
console.log("Success: Response Text: " + result.responseText);
}
else {
console.log("Fail:Response Text: " + result.responseText);
}
},
function error(error) {
console.log("error");
},
function progress(result) {
}
);
}
I will be thinkful if someone give me some help.

The WinJS.xhr() is a promise wrapper around XMLHttpRequest, which means it delegates your parameters to an XMLHttpRequest object and returns a WinJS.Promise object. The parameters may not be delegated correctly so play with adding and empty string for a username and such. Otherwise you can mimic the same functionality by creating your own WinJS.Promise with an XMLHttpRequest inside.

Related

Passing a string array from JS to C# controller

I have an array in JS ( var selectedEmails = []; )
After I collect the selected Emails from a grid, I call a GET to C# controller:
$.ajax({
type: 'GET',
url: '#Url.Action("SendEmailBatchs", "account")',
data: { emails: selectedEmails },
contentType: 'application/json',
success: (data) => {
console.log("data", data);
}
})
When called, the parameter in C# gets no data. I've checked in JS, and the emails are in the array. Using breakpoints, I've confirmed the Controller's method is getting called:
Controller:
[HttpGet("sendemailbatchs")]
public async Task<ActionResult> SendEmailBatchs(string[] emails)
{
...
foreach (ApplicationUser user in users)
{
await SendEmailConfirmation(user);
}
return Ok;
}
Changing the data to data: { emails: JSON.stringify(selectedEmails) }, will pass an array with 1 element only, containing a stringified list of emails "[\"loes.vea#phanc.com\",\"MaAlonso.Mfizer.com\",\"cech#mll-int.cm\",\"jier.aris#si.com\"]"
What would be the correct parameter from JS so that I get a string ARRAY where each email is an element of the array?
emails = [0]: "loes.vea#phanc.com\",
[1]: \"MaAlonso.Mfizer.com\", ...
There is a gap between what you are expecting in the controller and what you are sending through ajax call.
public async Task<ActionResult> SendEmailBatchs(string[] emails)
Let's understand the parameter of the above function, you are expecting an array of strings and will refer to it as emails in the function body. So, you will have to pass an array of strings in the request body.
PFB my simple controller and corresponding ajax call:
[HttpGet("api/test")]
public ActionResult<int> RecieveData(string[] emails)
{
return emails.Count();
}
Call from UI like this:
var settings = {
"url": "https://localhost:5000/api/test",
"method": "GET",
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify([
"john#example.com",
"jane#example.com"
]),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
so, after following Devesh's suggestions I ended up with
var settings = {
"url": '#Url.Action("SendEmailBatchs", "account")',
"method": "GET",
"headers": {
"Content-Type": "application/json"
},
"data": {
emails: JSON.stringify(selectedEmails)},
};
the issue persisted, because I needed to DESERIALIZE the result, in C#:
public async Task<ActionResult> SendEmailBatchs(string emails)
{
var selectedEmails = JsonConvert.DeserializeObject<string[]>(emails);
//DO STUFF
}
Thx

rescuegroup/Petfinder jQuery API requests

I am currently trying to get API responses from the two following API's. All of the sample code on their website is in PHP and asks for a token and token SSH, while they only give you an API key. Very lost trying to get requests to pull. The closest I've gotten is an error that says the following:
{status: "error", message: "Unable to read your data; it might not be in json format."}
here is my JS:
jQuery.get({
url: 'https://api.rescuegroups.org/http/v2.json',
type: 'post',
contentType: 'application/json',
data: {
apikey: 'XXXXXXX',
objectType:'animals',
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Any help is greatly appreciated. Really want to avoid having to learn PHP as I'm still very new to JS.
the problem is that you are not passing it as json.
this is json format.
let dataObject = {
data: {
apiKey: "xxxx"
}
};
let data = JSON.stringify(dataObject);
{
"data": {
"apikey": "xxx"
}
}
then pass data as your data.
After trying it with Postman the request went through.
Obviously I don't have the api key
{
"status": "error",
"message": "Error with your login credentials",
"messages": {
"generalMessages": [
{
"messageID": "1101",
"messageCriticality": "error",
"messageText": "Error with your login credentials."
}
],
"recordMessages": []
}
}

Ajax wont call MVC controller method

I have an AJAX function in my javascript to call my controller method. When I run the AJAX function (on a button click) it doesn't hit my break points in my method. It all runs both the success: and error:. What do I need to change to make it actually send the value from $CSV.text to my controller method?
JAVASCRIPT:
// Convert JSON to CSV & Display CSV
$CSV.text(ConvertToCSV(JSON.stringify(data)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value : $CSV.text() },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});
CONTROLLER:
[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText = "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var obj = new
{
success = false,
responseText = "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
RESULT
You should change the data you POST to your controller and the Action you POST to:
data: { value = $CSV.text() }
url: '#Url.Action("EditFence", "Configuration")'
The $CSV is possible a jquery Object related to an html element. You need to read it's text property and pass this as data, instead of the jQuery object.
Doing the above changes you would achieve to make the correct POST. However, there is another issue, regarding your Controller. You Controller does not respond to the AJAX call after doing his work but issues a redirection.
Update
it would be helpful for you to tell me how the ActionResult should
look, in terms of a return that doesn't leave the current view but
rather just passes back that it was successful.
The Action to which you POST should be refactored like below. As you see we use a try/catch, in order to capture any exception. If not any exception is thrown, we assume that everything went ok. Otherwise, something wrong happened. In the happy case we return a response with a successful message, while in the bad case we return a response with a failure message.
[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText= "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
catch(Exception ex)
{
// log the Exception...
var obj = new
{
success = false,
responseText= "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
}
Doing this refactor, you can utilize it in the client as below:
$CSV.text(ConvertToCSV(JSON.stringify(data)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value = JSON.stringify($CSV.text()) },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});
If your javascript is actually in a JS file and not a CSHTML file, then this will be emitted as a string literal:
#Url.Action("EditFile", "Configuration")
Html Helpers don't work in JS files... so you'll need to point to an actual url, like '/configuration/editfile'
Also, it looks like you're posting to a method called EditFile, but the name of your method in the controller code snippet is EditFence, so that will obviously be an issue too.
you dont need to add contentType the default application/x-www-form-urlencoded will work because it looks like you have a large csv string. So your code should be like this example
$(document).ready(function() {
// Create Object
var items = [
{ name: "Item 1", color: "Green", size: "X-Large" },
{ name: "Item 2", color: "Green", size: "X-Large" },
{ name: "Item 3", color: "Green", size: "X-Large" }
];
// Convert Object to JSON
var $CSV = $('#csv');
$CSV.text(ConvertToCSV(JSON.stringify(items)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
data: {value:$CSV.text()},
success: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
Your problem is on these lines:
success: alert("Zones have been saved."),
error: alert("Zone save encountered a problem.")
This effectively running both functions immediately and sets the return values of these functions to the success and error properties. Try using an anonymous callback function.
success: function() {
alert("Zones have been saved.");
},
error: function() {
alert("Zone save encountered a problem.")
}

Jquery ajax POST inconsistent with Hapijs server inject

Here is what my Ajax post looks like:
$.ajax({
type: "POST",
url: "/create",
data: {
"question": $('#question').val(),
"options": options
},
success: function() { window.location.href="/view"; }
});
Fairly simple. options is an array of string charachters. The problem is, when I receive on the server end with Hapijs, the request payload shows this object received:
{
question: "..etc..",
"options[]": [..etc...]
}
Why does it add a [] to the options variable name? Normally this wouldn't be a problem for me, but when I do the same thing and simulate a server request in my lab test like this:
var test = [..etc..]
// Simulate POST request
var serverOptions = {
method: 'POST',
url: '/create',
payload: {
question: 'Question',
options: test
}
};
It shows that the variable name received is just "options", not "options[]". How can I get jquery to stop adding the [] to the variable name when POSTing? Thanks

EWS - A token was not recognized in the JSON content

I try to send an email via EWS using Javascript and the REST API.
The OAuth is not the problem so far.
The problem is, if I try to send the email, the Server sends this response:
"{"error":{"code":"RequestBodyRead","message":"Invalid JSON. A token was not recognized in the JSON content."}" (taken from Chrome Debug Console).
Here my Javascript, where the error occurs:
function mailIsRaus(token) {
var gottenParam = JSON.stringify(token);
var jsonObj = JSON.parse(gottenParam);
var leToken = jsonObj['access_token'];
//This is the Token from Active Directory
leToken = "Bearer " + leToken;
var Message = {
"Message": {
"Subject": "TESTING REST API EWS",
"Body": {
"ContentType": "Text",
"Content": "IT WORKED. The EWS is working my friend."
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "johndoe#something.com"
}
}
]
},
"SaveToSentItems": "true"
};
//eMailData = JSON.stringify(eMailData);
$.ajax({
type: 'POST',
beforeSend: function (request) {
request.setRequestHeader("Authorization", leToken);
request.setRequestHeader("Content-Type", "application/json");
},
data: Message,
url: 'https://outlook.office.com/api/v2.0/me/sendmail',
success: function (e) {
console.log('Email sent');
console.log(e);
},
error: function (message) {
console.log(message);
}
});
}
I strictly sticked to MSDN and now, I have no clue, why this error occurs.
If I comment out the "setRequestHeader" I get an error 401 unauthorized.
The token ist correct.
The scope is also correct.
Maybe I made an simple mistake in the "var Massage" or something...
I found the solution by myself.
I had to uncomment the following line of code to:
eMailData = JSON.stringify(eMailData);
Now it is working fine.

Categories

Resources