Capture JSON at VB.NET REST - json

I have 2 checkboxes. I need to capture the checkboxes clicked and send it to REST SERVICE, I am able to capture checkboxes clicked at fnt end but I don't know how to capture it in the REST (VB.Net).
Below is the front end file:
<form>
<input type="checkbox" class = "checkBoxProp" id = "1" name="checkBoxProp" value="1">Graph1<br>
<input type="checkbox" class = "checkBoxProp" id = "2" name="checkBoxProp" value="2">Graph4<br>
<input id="btnGetResponse" type="button" value="ClickMe!"/>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnGetResponse").click(function()
{
var ids = $('.checkBoxProp:checked').map(function() {
return this.value;
}).get();
console.log(JSON.stringify(ids.join()));
$.ajax({
type: "POST",
url: "http://localhost:51349/SMS_Rest.svc/v1/usercheckboxes",
data: {ids: ids} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
alert('success');
},
failure: function(response)
{
alert('fail');
}
});
});
So how to capture JSON at REST.
Public Function CheckBoxDetails(ByVal requestData As **WHAT TO WRITE HERE**) As String Implements iSMS_Rest.CheckBoxDetails
// SOME LOGIC
End Function

Your method at server-side should be a POST and you should capture the data from body of the request instead of querystring. So, the argument list should have [FromBody] attribute and it would be abetter way if you can create a input model class with similar structure as the input data and have similar properties, use that object as the parameter to the POST method.

Related

AJAX JSON array to single JSON object

I'm using AJAX to send JSON data from a form to my server, however it's sending it as an array of JSON values, rather than just a single JSON object - how can I modify this script to send it as a single object?
function send() {
$.ajax({
method: "POST",
url: "http://localhost:1323/submitted",
contentType: "application/json",
dataType: "json",
data: JSON.stringify($("#myform").serializeArray())
});
}
For example, instead of sending it as:
[{"name":"name","value":"boris"},{"name":"password","value":"password123"}]
I'd like to send it as:
{"name":"boris", "password":"password123"}
You can use .each loop to iterate through all inputs and push name and value inside JSON Object.
Demo code:
function send() {
var json_object = {};
//loop through inputs
$("#myform input").each(function(i, v) {
json_object[$(this).attr("name")] = $(this).val() //get values
})
console.log(json_object)
//or
var json_object1 = {}
$($("#myform").serializeArray()).each(function(i, v) {
json_object1[v.name] = v.value
})
console.log(json_object1)
//send this..
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input name="name" type="text">
<input name="password" type="text">
<button type="button" onclick="send()">Send</button>
</form>

How to refresh an html page using ajax in Django?

I know this question has been asked several times, but I cannot find a solution.
I cannot connect the method output in views with html page.
views
def save_form(request):
if request.method == 'POST' and 'save' in request.POST:
lsection = [5]
print("calculate method runs...")
return JsonResponse({'lsection':lsection})
"calculate method runs..." is printed only when I do not use ajax.
html
<form method="post" name="nameForm" id="idForm"
action = "/project/save/" enctype="multipart/form-data">
{% csrf_token %}
...
<input type="submit" name="save" value="Save">
</form>
ajax
var frm = $('#idForm');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('save_form'),
url: frm.attr('/project/save/'),
//data: frm.serialize(), // I tried this as well
data: {},
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
},
});
});
Question:
I do not get lsection list on html, I try alert(data) I get an empty html.
How can I get lsection on html?
You need attribute's values:
type: frm.attr('method'),
url: frm.attr('action'),
Correct code:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
}
});
.attr
While receiving JSON response in ajax success you used data.
to show the lsection.
alert(data.lsection)
update alert like above

How do I get input from an HTML form and find data?

I have a form like this;
<div id="employeeinfo" style="padding:40px" class="employee-body">
<form id="employeeform" title="" method="post">
<label class="title">First Name</label>
<input type="text" id="fname" name="first_name" >
<label class="title">Last Name</label>
<input type="text" id="lname" name="last_name" >
<input type="submit" id="submitButton" onclick="formSubmit()" name="submitButton" value="Submit">
</form>
</div>
I have a json url: "app.employee.com/employeedata"
I need to get fname and lname from html form and search through the json in above url and display it in
so far i have this:
<script type='text/javascript'>
function formSubmit(){
var formData = JSON.stringify($("#employeeform").serializeArray());
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
}
</script>
How to proceed with this? I'm doing this in shopify.
You can start with use of the getElementById method.
function formSubmit(){
...
var fname=document.getElementById("fname").value;
var lname=document.getElementById("lname").value;
}
try this way
function formSubmit(){
var fname=$('#fname').val();
console.log('fname',fname);
var lname=$('#lname').val();
console.log('lname',lname);
}
The success function in your ajax call returns data from the server:
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
Source: jQuery.ajax docs
So what you can do is:
<script type='text/javascript'>
function formSubmit(){
var formData = JSON.stringify($("#employeeform").serializeArray());
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(responseData){
// responseData contains the json from the server. You can search this for the firstname and lastname from the form.
},
dataType: "json",
contentType : "application/json"
});
}
</script>
In your case your serializeArray only will fetch all the form data and will return like
[
{
name: "fname",
value: "zydexo"
},
{
name: "lname",
value: "test"
}
]
Then in your back end file you can read the post data.
If you want to get each element value by your own then you need to use:
var fname=document.getElementById("fname").value;
or
var fname=$('#fname').val();
Then
function formSubmit(){
var fname= $("#fname").val();
var lname= $("#lname").val();
$.ajax({
type: "POST",
url: "serverUrl",
data: {fname:fname,lname:lname},
success: function(data){
//
},
dataType: "json",
contentType : "application/json"
});
}

How can I use JSON to link my html form to update a sharepoint list?

At the moment I'm just trying to add name to the list. I'll add more when I get that working.
I'm currently getting errors in the debugger with the following :
var siteurl = _spPageContextInfo.webAbsoluteUrl;
Also, I've more than one column in the list, could that be it?
What I have:
$('#submitdata').click(function () {
//this gets the value from your name input
var name = $('#name').val();
var data = {
__metadata: { 'type': 'SP.Data.ProjectsListItem' },
"name": name,
};
$.ajax({
var siteurl = _spPageContextInfo.webAbsoluteUrl;
$.ajax({
url: siteurl + "/mysite/Lists/getbytitle('ChangeOfAddressList')/items",
method: "POST",
data: JSON.stringify(data),
headers: { "Accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('Item added successfully');
},
error: function (error) {
alert("Error: "+ JSON.stringify(error));
}
});
});
HTML:
<body>
<form id="COA_Form" name="myForm" method="post" action="" >
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit' />
</form>
</body>
To test your code, change the line
var siteurl = _spPageContextInfo.webAbsoluteUrl;
to
var siteurl = 'https://spsitedomain';.
Of course you would want to use your actual SharePoint site domain instead of 'spsitedomain'.
You can open the console and see what the _spPageContextInfo object yields. In my browser, I either get undefined or I get an object that does not have a webAbsoluteUrl property (depending on the page I am viewing), so your mileage may vary when using this object.

How to convert the returned XML to HTML?

I created a simple web service in ASP.net that does some operations:
[WebMethod]
public int Area(int l, int b)
{
return l * b;
}
[WebMethod]
public int Perimeter(int l, int b)
{
return 2 * (l +b);
}
and i called it in HTML file, like:
<html>
<head>
<title>WebService Call using HTTP POST</title>
<body>
<form action="http://localhost:56472/WebSite2/Service.asmx/Area" method="POST">
<input name="l">
<input name="b">
<input type="submit" value="Click for Area">
</form>
<form action="http://localhost:56472/WebSite2/Service.asmx/Perimeter" method="POST">
<input name="l">
<input name="b">
<input type="submit" value="Click for Perimeter">
</form>
</body>
</head>
</html>
put this when i click for the result it will be returned as XML:
<?xml version="1.0" encoding="UTF-8"?>
<int xmlns="http://tempuri.org/">30</int>
And what I want is i want the result in HTML not XML, how to do this?
Can someone help, please?
Thank You :)!
You'll need to call the service via ajax call and use the response to populate the required tag in the HTML.
Check the code below, it's simple jQuery AJAX call,
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
method:"post",
data: {
l: "custom value",
b: "custom value",
}
success: function (data) {
console.log(data.length);
var xmlDoc = $.parseXML(data);
var jXml = $(xmlDoc);
var value = jXml.find("int").text();
$("#result").text(value);
},
failure: function (err) {
console.log("could not call the service : " + err);
}
});
Couple of things to keep in mind
Form submission will take you to next page and destroy Javascript context, that's why we need AJAX call which will just bring us the result from teh service without navigating away from the page.
As server is returning data in XML you'll have to parse it either as XML document or as plain string to get the required values.
***Edited to add
Check out the complete example below.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
<!-- create the function to call on click of a button -->
function getData() {
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
type: 'GET',
dataType: "xml",
data: {
l: "custom value",
b: "custom value"
},
success: function(data) {
console.log("success " + data);
console.log(data.getElementsByTagName("int"));
var xmlDoc = data;
if(typeof(data) === "string") {
xmlDoc = $.parseXML(data);
}
var value = xmlDoc.getElementsByTagName("int")[0].textContent;
$("#result").text(value);
},
error: function(err) {
console.log("error " + JSON.stringify(arguments));
}
});
}
</script>
</head>
<body>
<!-- see the onclick attribute, you have to call your Javascript function in it's value -->
<button onclick="getData();">click to get data</button>
<!-- tag where it result will be displayed -->
<h1 id="result">No result yet</h1>
</body>
</html>