Use AJAX to submit data from HTML form to WebMethod - asp.net

So I'm taking in data from an HTML form and then using AJAX to send the data to a web method to then be sent to a sqlite database, but my AJAX call is failing. What did I mess up? Am I doing it correctly?
HTML Form
<form id="addForm" >
<input type="text" name="playername" id="playername" placeholder="Player"/>
<input type="text" name="points" id="points" placeholder="Points" />
<input type="text" name="steals" id="steals" placeholder="Steals" />
<input type="text" name="blocks" id="blocks" placeholder="Blocks" />
<input type="text" name="assists" id="assists" placeholder="Assists" />
<input type="text" name="mpg" id="mpg" placeholder="MPG" />
<input type="text" name="shotpct" id="shotpct" placeholder="Shot %" />
<input type="text" name="threepct" id="3pct" placeholder="3 %" />
<input type="button" value="add player" id="addbtn" name="addbtn" />
</form>
AJAX
$("#addbtn").click(function () {
var form = $("#addForm").serializeArray();
$.ajax({
type: 'POST',
url: "players.aspx/addRow",
data: JSON.stringify(form),
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
and the web method(not finished, was just testing to see if I was getting data)
[WebMethod]
public static void addRow(object form)
{
var stuff = form;
}
I'm still learning how to use a lot of this stuff so any help will be greatly appreciated.

Replace
type: 'POST',
with
method: 'POST',
dataType: 'json'
is not needed since you're not receiving data back. The data returned from the server, is formatted according to the dataType parameter.
Also remove JSON.stringify(form),this is already done with the .serialize();

replace
JSON.stringify(form)
with
$('form').serializeArray()
So you will have:
$("#addbtn").click(function () {
var form = $("form").serializeArray();
$.ajax({
type: 'POST',
url: "players.aspx/addRow",
data: form,
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
If you still get error. there might be a server side problem in the page you are calling. to make sure of that I suggest you use the 'Advanced REST client' witch is a Google Chrome extension and you can test posting values with it and see the result.

Related

Large file streaming confusion

I want to handle large files in my application and microsoft documentation about File Uploads looks so bizarre. Why would I need MultipartReader whereas I would simply achieve what I want with the following:
#model SampleVM
<form method="post" enctype="multipart/form-data">
<input asp-for="Prop1" />
<input asp-for="Prop2" />
<input type="button" value="Ok" onclick="post();"/>
</form>
#section Scripts{
<script>
function post() {
var formData = new FormData();
formData.append('Prop1', $('#Prop1').val());
formData.append('Prop2', $('#Prop2')[0].files[0]);
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
processData: false,
contentType: false,
data: formData
});
}
</script>
}
and in the controller I can simply get the stream with
var stream = vm.Prop2.OpenReadStream()
and do whatever I want. What does Microsoft documentation achieve with that spaghetti code that I don't with this simple sample?

Fetch data from HTTP POST with CURL

i'm new with curl
I want to try fetch simple text from html input using curl and send it to another website using simple JSON
this is the simple html code i make
<form action="http:test.com" method="post">
<input type="text" id="text">
<input type="submit" value="submit">
</form>
is there a way to do it?
Thank you!
Since you need to fetch the data from Slack, the nice way is to use AJAX to post the data. The following JS codes are modified based on achavez's gist: Post to Slack using javascript and use jQuery.ajax.
<form action="http:test.com" method="post" id="the-form">
<input type="text" id="text">
<input type="submit" value="submit">
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$('#the-form').submit(function(e) {
e.preventDefault();
var url = "http:test.com"; // Webhook URL
var text = $('#text').text(); // Text to post, get from your form
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
}).done(function(data) {
// do whatever you want with `data`, `data` is the response
});;
});
</script>

Files are not received when sending form data to the server

I am trying to send form data to my server (Asp.net server), but when debugging the server only the typed information is received, but the files are not there.
This is my html page: (http://pastebin.com/KZERsepn)
<template>
<ai-dialog>
<ai-dialog-body>
<div>
<span>character name</span>
<input type="text" value.bind="user.name" />
</div>
<div>
<span>Youtube url:</span>
<input type="text" value.bind="user.YoutubeUrl" />
</div>
<div>
<span>ProfileImage:</span>
<input type="file" file.bind="user.ProfileImage" />
</div>
<div>
<span>CoverImage:</span>
<input type="file" file.bind="user.CoverImage" />
</div>
</ai-dialog-body>
<ai-dialog-footer>
<button click.trigger="controller.cancel()">Cancel</button>
<button click.trigger="controller.ok(user)">Ok</button>
</ai-dialog-footer>
</ai-dialog>
and this is how i am posting the data:(http://pastebin.com/7bVHZthE)
createUser(user) {
let model = new FormData();
model.append('Name', user.Name);
model.append('YoutubeUrl', user.YoutubeUrl);
model.append('ProfileImage', user.ProfileImage);
model.append('CoverImage', user.CoverImage);
return this.client.fetch('/api/createUser', {
method: "post",
body: model,
headers: {
'Access-Controll-Allow-Origin': '*',
'Accept': 'application/json'
}
});
}
But only the user.name and user.youtubeurl properties are sent to the server.
To post files, you must use a multipart/form-data
The trick to posting a multipart/form-data is (rather unintuitively) to force the content-type header to false. So try this:
return this.client.fetch('/api/createUser', {
method: "post",
body: model,
headers: {
'Content-type': '', // this is where the magic happens
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json'
}
});

How to pass one (or more) parameter(s) through a button

First of all ASP.NET MVC is very new to me (+- one month).
In my view I've got this code
First block
<label for="from">Data Inicio</label>
<input id="from" name="from" type="text" />
<label for="to">Data Fim</label>
<input id="to" name="to" type="text" />
Second block
<div class="btn-group">
<button type="button" class="btn btn-primary" onclick="listaC006()">Pesquisa Normal</button>
<button type="button" class="btn btn-primary" onclick="flistaC006()">Pesquisa com filtro</button>
</div>
and also
function list() {
$.ajax(
{
type: 'POST',
url: '/Inscricao/_Lista',
dataType: 'html',
cache: false,
async: true,
success: function (data) {
$('#lista').html(data);
}
});
}
in order to fill this "<div id="lista"></div>" dynamically.
It's possible to pass the values (datepicker) of "from" and "to" in the onclick event in order to use those values to perform a query?
To pass parameters on your post add the data argument to your post call:
function list() {
$.ajax(
{
type: 'POST',
url: '/Inscricao/_Lista',
dataType: 'html',
cache: false,
async: true,
data: "{'from': '" + $("#from").val() + "', 'to': '" + $("#to").val() + "' }",
success: function (data) {
$('#lista').html(data);
}
});
}

How to read arrays generated by EditorFor using jQuery

I am quite confused with technique that I am using. I am using EditorFor to display values.
The code for the values to be generated are as follows:
<tr>
<td>#Html.HiddenFor(m => m.ID)#Html.CheckBoxFor(m => m.Authorized)</td>
<td>#Html.DisplayFor(m => m.ID)</td>
<td>#Html.DisplayFor(m=>m.UserName) </td>
</tr>
My aim here is upon the Checkbox is being checked, I need to post the ID value as follows:
$("input:checkbox").live('click', function () {
if ($(this).attr('checked')) {
var ID = $(this).parent().parent().find('#ID').val();
$.ajax({
type: "POST",
url: '<%=Url.Action("Edit","Employee") %>',
data: JSON.stringify(ID),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function () {
},
error: function (request, status, error) {
alert("Error: " & request.responseText);
}
});
} });
However, var ID = $(this).parent().parent().find('#ID').val(); is undefined. How can I he read the ID value from the following generated HTML:
<td><input id="Employee_0__ID" name="Employee[0].ID" type="hidden" value="1100" /><input id="Employee_0__Authorized" name="Employee[0].Authorized" type="checkbox" value="true" /><input name="Employee[0].Authorized" type="hidden" value="false" /></td>
<td>user </td>
Not sure I understand what value you looking for?
Would this.
var ID = $(this).parent().parent().find('#ID').attr('value');
or this
var ID = $(this).parent().parent().find('#ID').attr('id');
work?
For the HTML specified this should suffice as the hidden element is the previous sibling of the checkbox in the DOM
var ID = $(this).prev().val();

Resources