Title says it all. I submit a form, call a function in the code behind but the value for the form is always null.
I've tried quite a few scenarios, I'll post my current state to see if there is a simple fix I am missing or better solution.
I don't know if this impact things but this code lies on .ascx page.
Pertinent JS/jQuery
function forceClick() {
<%= Page.ClientScript.GetPostBackEventReference(hiddenBtn, string.Empty) %>;
}
$(document).ready(function() {
$('[id$=ImageButton2]').click(function () {
console.log($('[id$=buttontest]'));
console.log($('[id$=ImageButton2]'));
$("#modal_dialog").dialog({
title: "Delete Item",
buttons: {
Submit: function () {
forceClick();
$('#myForm').submit();
$(this).dialog('close');
},
Close: function() {
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Pertinent HTML
<div id="modal_dialog" style="display: none">
<p class="validateTips">Please enter a reason for deleting the item.</p>
<form name="myForm" id="myForm" method="POST" action="Detail.ascx">
<input type="text" id="comment" name="comment"/>
</form>
</div>
Code-behind
protected void buttontest_OnClick(object sender, EventArgs e)
{
string commentOne = Request.Form["comment"];
Session["ItemCount"] = null;
if (DeleteItem != null)
{
DeleteItem(this, e);
}
}
Related
So, I have a form that contains a textarea field and a submit button:
<form class="popupForPosting">
<textarea id="postContent" name="postContent" rows="8" cols="80" class="postContent" placeholder="What's going on, <?php echo $firstname ?>?"></textarea>
<button id="pos" class="pos" onclick="makePost()">Post</button>
</form>
When I click my submit button, the call gets sent to my AJAX as a request and my postContent (whatever is entered in the textarea field) gets shown in the URL. I don't want this to happen.
Now, I don't want to use the POST method for this form. I want to use the GET method, but still hide the parameters displayed in the URL. According to the information and details given, how can I accomplish this?
EDIT:
<script>
const makePost(form) {
const text = form.postContent.value;
function makePost() {
var postContent = $("#postContent").val();
if (postContent.length > 0) {
jQuery.ajax({
url:"yourposts.php",
data:{
postContent: postContent
},
type:"POST",
success:function(data){
if (data == "success") {
$(".textpostFormat").html(postContent);
}
}
});
}
}
};
document.querySelector(".popupForPosting").addEventListener("submit",function(e) {
e.preventDefault();
makePost(this); // passing the form
});
</script>
Simplest answer for you
Change the form tag: action="yourposts.php" method="post"
Give the submit button an name and a value and remove the click handler
move your post.php to the top of the page
add a test isset($_POST["submitButtonName"])
empty the form field before returning the page
remove all ajax related script
Now the page will save the data if the button is clicked and not if the page is just loaded. The test for content will handler the reload
Ajax answer
Using AJAX does not show the data in the URL - just
remove onclick="makePost()"
use the submit event of the form instead of the click event of a submit button and use event.preventDefault():
NOTE I have wrapped in a load event handler
$(function() { // when form is available
$(".popupForPosting").on("submit", function(e) {
e.preventDefault(); // always prevent submit
const postContent = $("#postContent").val().trim();
$('#noText').css({visibility: postContent === "" ? "visible" : "hidden" })
$("#popUp").toggle(postContent==="")
if (postContent) {
$.ajax({
url: "yourposts.php",
data: {
postContent: postContent
},
type: "POST",
success: function(data) {
console.log(data)
if (data == "success") {
$(".textpostFormat").html(postContent);
}
}
});
}
});
});
So I have a .ASP MVC Web Application project. I want to run a void method from the controller class when I press a button using AJAX. No variable input or output data needed. I just want to create a pdf file and save it on my local machine.
Right now, nothing at all happens when I click the button. I don't think the ajax script works, 0 connection.
This is my Controller method:
[HttpPost]
public void Test()
{
string dok = System.IO.File.ReadAllText("C:\\Users\\axel\\Desktop\\Repo\\Cert\\employee_regular.html");
var Renderer = new IronPdf.HtmlToPdf();
var HtmlTemplate = dok;
var Pdf = Renderer.RenderHtmlAsPdf(HtmlTemplate);
Pdf.SaveAs("C:\\Users\\axel\\Desktop\\Repo\\Cert\\Arbetsgivarintyg_vanlig_heltid.pdf");
}
This is my Index.cshtml file
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-12">
<h2>Request employement certificate</h2>
<input type="button" onclick="BtnClick()" value="Click me" />
</div>
</div>
<script>
function BtnClick() {
$ajax({
url: "/Home/Test",
method: "POST",
success: function () {
alert("ok");
},
error: function () {
alert("not ok")
}
})
}
</script>
Really happy for any help
Well there can be several reasons why your code is not working.
First Make sure you are actually able to make a call to a function, Just simply add simple alert message before calling the ajax and see if the alert triggers.
The second thing is to validate url replace the hardcoded url and add url using URL helper.
I would recommend you to make a function as JsonResult Instead of Void, because an exception can happen when creating pdf. [This change is optional but I do recommend it]
So after all the changes your code would look something like this
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-12">
<h2>Request employement certificate</h2>
<input type="button" onclick="BtnClick()" value="Click me" />
</div>
</div>
<script>
function BtnClick() {
$ajax({
alert("Funciton is working"); // change confirm function is working
url: "#Url.Action("Test","Home")", // change using Url Helper to create valid URL
method: "POST",
success: function (data) {
if (data == true)
{
alert("pdf created sucessfully ok");
}
else
{
alert("exception happend when creating pdf not ok");
}
},
error: function () {
alert("not ok")
}
})
}
</script>
Your Back End would look something like this
[HttpPost]
public JsonResult Test()
{
try {
string dok = System.IO.File.ReadAllText("C:\\Users\\axel\\Desktop\\Repo\\Cert\\employee_regular.html");
var Renderer = new IronPdf.HtmlToPdf();
var HtmlTemplate = dok;
var Pdf = Renderer.RenderHtmlAsPdf(HtmlTemplate);
Pdf.SaveAs("C:\\Users\\axel\\Desktop\\Repo\\Cert\\Arbetsgivarintyg_vanlig_heltid.pdf");
return Json(true, JsonRequestBehavior.AllowGet);
}
catch(Exception ex) {
return Json(false, JsonRequestBehavior.AllowGet);
}
}
I am using Node.js + Express.js to build a very basic search engine for a Library database. My HTML has a POST form that sends either a title or keyword to the app in order to query a MySQL database for the book/books. The search by title is working fine but the keyword is giving me a hard time. See below.
HTML
<form id="searchForm" action="" method="post">
<select class="form-control" id="searchType">
<option class="" value="0">Search by title</option>
<option class="" value="1">Search by keyword</option>
</select>
<select class="form-control" id="titles" name="titles">
<% for (var title in titles) {;%>
<option class=""><%=titles[title].TITLE%></option>
<% }; %>
</select>
<textarea class="form-control" name="keyword" contenteditable="false" id="keyword" placeholder="Enter keyword here..."></textarea> <!-- placeholder is only supported in a few browesers
(Firefox 3.7+, Chrome, Safari, IE 10). Could use
jQuery but ah-->
<input class="btn btn-default" type="submit" value="Search"></input>
</form> <!-- /searchForm -->
Express code
app.post('/getBooksByTitle', function (req, res) {
connection.getConnection(function(err, tempCon) {
if (err) {
tempCon.release();
console.log('ERROR IN SQL CONNECTION!');
}
else {
console.log('CONNECTED TO SQL');
tempCon.query('SELECT * FROM BOOKS WHERE TITLE=?', req.body.titles, function(err, rows) {
if (err) {
console.log('BAD QUERY');
}
else {
console.log(req.body.titles);
res.json(rows);
}
tempCon.release();
});
}
});
});
app.post('/getBooksByKeyword', function (req, res) {
connection.getConnection(function(err, tempCon) {
if (err) {
tempCon.release();
console.log('ERROR IN SQL CONNECTION!');
}
else {
console.log('CONNECTED TO SQL');
tempCon.query('SELECT * FROM BOOKS WHERE (AUTHOR LIKE ? || TITLE LIKE ? || GENRE LIKE ? || DESCRIPTION LIKE ?)', '%' + req.body.keyword + '%', function(err, rows) {
if (err) {
console.log('BAD QUERY');
console.log(req.body);
}
else {
res.json(rows);
console.log(req.body.keyword);
}
tempCon.release();
});
}
});
});
I am pulling the form data to node with req.body.(field_name) but it doesn't seem to gather the text box. If I console.log(req.body) I see only the title field. Where have I messed up?
EDIT: The jQuery script that handles the action and some animations.
$(document).ready(function () {
toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
//this will call our toggleFields function every time the selection value of our searchType field changes
$("#searchType").change(function () {
toggleFields();
});
});
//this toggles the visibility of our input fields depending on the current selected value of the searchType field.
//also it toggles the action of the submit form to the appropriete post call.
function toggleFields() {
if ($("#searchType").val() == 0) {
$("#searchForm").attr('action', '/getBooksByTitle');
$("#titles").slideDown();
$("#keyword").slideUp();
}
else {
$("#searchForm").attr('action', '/getBooksByKeyword');
$("#titles").slideUp();
$("#keyword").slideDown();
}
}
Thanks for the help you tried to provide. I fixed the problem by changing the <textarea> field to an <input> field. Now the post sends both my title and keyword back to the server.
I'm trying to simply allow a user to upload a file.
I have a simple begin form that contains a file element as shown below:
#using (Html.BeginForm("LoadData", "Input", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div style="width:23%; display:inline-block;">
<label>Select Type:</label>
<select name="UploadType">
<option value="First">First</option>
<option value="Second">Second</option>
</select>
</div>
<div style="width:43%; display:inline-block;">
<input type="file" name="files1" id="files1" />
</div>
<div style="width:33%; display:inline-block;">
<input type="submit" value="Upload"/>
</div>
}
The controller is :
[HttpPost]
public ActionResult LoadData(string UploadType, HttpPostedFileBase file1)
{
if(file1 != null && UploadType != null)
{
Console.WriteLine(file1.FileName);
Console.WriteLine(UploadType);
}
}
Everything displays and works on the site but when it posts back the file is null. I've looked at many google results including:
Binding HttpPostedFileBase using Ajax.BeginForm
MVC 4 Razor File Upload
http://www.aurigma.com/upload-suite/developers/aspnet-mvc/how-to-upload-files-in-aspnet-mvc
and more. they all say my stuff is correct. As long as the names match on the file input and the controller param, it should work. But it's not.
I've tried naming it file, files, and now file1 but no mater what I call it, it comes back null.
What am I doing wrong? I even tried checking the Request.Files but that says it has a count of 0.
I ended up using javascript to handle the files instead. Here's the working code:
Javascript (it allows multiple files now):
function SendData() {
var formData = new FormData(document.querySelector('UploadForm'));
for(var i = 0; i < $('#file')[0].files.length; i++)
{
formData.append('files', $('#file')[0].files[i]);
}
formData.append('samplevalue', $('#samplevalue').val());
var url = $('#baseUrl').val() + 'Input/LoadData';
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
// your logic....
},
error: function(data)
{
// logic....
}
});
}
The controller then accepts
public string LoadData(string samplevalue, HttpPostedFileBase[] files)
{
}
Of course the trick is the javascript. I still don't know why the form doesn't work normally but this works perfectly. :)
Your file input is named files1, but your action param is file1 (no s).
#using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="file" name="ImgUploader" id="ImgUploader" />
<input type="submit" value="Create" class="btn btn-default" />
}
**Your Controller**`[HttpPost]
public ActionResult Create()
{
HttpPostedFileBase file = Request.Files["ImgUploader"];
}
I have been trying to work out how I can get the list of selected checkboxes to work using an ActionLink. I think I need to do something clientside with JavaScript but cannot find the relevant code.
The following code works perfectly using a submit button, posting back the selected id's as an array of id's, but I need to have this on a page with other buttons.
// the view
#foreach (var station in Stations)
{
<input type="checkbox" name="selected" value="#station.StationId" />
}
<input type="submit" value="Save" />
//Controller stub
public ActionResult Action(string [] selected)
I have been stuck on this for hours, so maybe I am looking at this the wrong way.
PS. My first post after many many hours reading and learning here.
SomeButtons or links to post checkboxlist values
Post
//or buttons, helpers and any elements to trigger ajax post...
CheckboxList:
<div id="MyDiv">
#foreach (var station in Stations)
{
<input type="checkbox" name="selected" value="#station.StationId" />
}
</div>
Scripts:
$(document).ready(function() {
$('#someButton').click(function() {
var list = [];
$('#MyDiv input:checked').each(function() {
list.push(this.name);
});
// now names contains all of the names of checked checkboxes
// do something with it for excamle post with ajax
$.ajax({
url: '#Url.Action("Action","Contoller")',
type: 'POST',
data: { Parameters: list},
success: function (result) {
alert("success")!
},
error: function (result) {
alert("error!");
}
}); //end ajax
});
});
Controller:
public ActionResult Action(string [] Parameters)
if I got it right :)
Looks like you are not looking for AJAX post. The easiest way to tackle this is to wrap it in the form and call submit function. Here is what your code should look like:
#using(Html.BeginForm("uraction", "urcontroller", FormMethod.Post, new { id = "formId" })) {
foreach(var station in Stations) {
<input type="checkbox" name="selected" value="#station.StationId" />
}
}
Post
<script>
$(document).ready(function() {
$('#postBtn').click(function() {
$('#formId').submit();
}
}
</script>