My Ajax call works. It sends data to the database as expected.
However, after it completes this task, it will not call the success or fail function. It just keeps running. I set the timeout for the ajax call but it didn't work.
I have a form in my html page
<form class="form-horizontal" id="signupForm" role="form" method="post" name="signupForm" action="">
<div class="form-group">
<label class="col-xs-3 control-label" for="TextBoxUsername">Username:</label>
<div class="col-xs-9"><input type="text" placeholder="username" id="TextBoxUsername" class="form-control" /></div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label" for="TextBoxPassword">Password:</label>
<div class="col-xs-9"><input type="text" placeholder="password" id="TextBoxPassword" class="form-control" /></div>
</div>
<div class="form-group">
<label class="col-xs-offset-5 control-label" for="selectImage" style="font-weight:bold;font-size:15px;">Choose Your Avatar</label>
</div>
<div class="content">
// I used the Image-Picker jQuery plugin here to create a selection of images and show them as thumbnails
<select name="selectImage" class="image-picker" id="selectImage" form="signupForm">
<option class="grid-item" data-img-src="img1.png" value="img1.png">Image 1</option>
<option class="grid-item" data-img-src="img2.png" value="img2.png">Image 2</option>
<option class="grid-item" data-img-src="img3.png" value="img3.png">Image 3</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</form>
This is my jQuery:
// this is my main jQuery function
$(function () {
// this is my form submit function
$("form").submit(function (e) {
e.preventDefault(); // this stops the form from refreshing the page
create();
});
});
// this function creates an object to be added to the database
function create() {
user = new Object();
user.Username = $("#TextBoxUsername").val();
user.Password = $("#TextBoxPassword").val();
// here I am getting the value of the selected item from <select> div
selectedImage = document.signupForm.selectImage.options[document.signupForm.selectImage.selectedIndex].value;
// this is just to convert the image to base 64 string.
var img = new Image();
img.src = selectedImage;
// draw canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0,0);
var imageURL = canvas.toDataURL();
user.Image = imageURL;
// end base 64 string conversion
$.ajax({
type: "Post",
url: "api/signup", // this url goes to a controller, it works perfectly
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
timeout: 3000, // does not do anything!
success: function () {
// this function is not being called!
$("#lblstatus").text("User was created!");
},
error: function (jqXHR, textStatus, errorThrown) {
// this function is not being called either!
errorRoutine(jqXHR);
}
});
}; // end create function
Like I said, the database is receiving the data just fine. But for some reason, this ajax call will not stop running. If I manually stop the application from the debugger, I can check the database and everything worked. I just need this ajax call to complete.
Try changing the type to button and set an id to it <button type="button" class="btn btn-default" id="submitbtn" >Sign in</button> And handle it by jquery click function $("#submitbtn").click(function () {
create();
});
by that, the page will not refresh even if you don't have the e.preventDefault();
since your using an ajax, the form is not needed anyway. So it can work even if you don't have a form tag
I found the tiny typo culprit.
it was inside the success function. I didn't add the "#" in front of "("lblstatus"). It should have been ("#lblstatus").
silly silly mistake.
Thanks for all the suggestions. It turned out to be a typo afterall.
Related
I have an Asp.net core application in which I have a form. When I click on the submit button I am using jquery ajax post to submit the form. I am facing 2 problems here,
When I press the submit button, the client side validations are not happening and the form is being submitted.
I have a Break point in the SendEmail Method, and for some reason the FormData binds all null values to the object. Please help.
Here is my form
<form name="ajax-form" id="formPostComment" enctype="multipart/form-data" method="post">
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="name" id="name" type="text" placeholder="Your Name: *" required/>
<span class="error" id="err-name">please enter name</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="email" id="email" type="text" placeholder="E-Mail: *" required/>
<span class="error" id="err-email">please enter e-mail</span>
<span class="error" id="err-emailvld">e-mail is not a valid format</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<label for="myfiles">Select file (If Any):</label>
<input name="attachment" id="attachment" type="file" />
</div>
<div class="col-sm-12 contact-form-item wow zoomIn">
<textarea name="message" id="message" placeholder="Your Message" required></textarea>
</div>
<div class="col-sm-12 contact-form-item">
<input class="send_message btn btn-main btn-theme wow fadeInUp" type="submit" id="submit" name="submit" data-lang="en" onclick="SendEmail();"></input>
</div>
<div class="clear"></div>
<div class="error text-align-center" id="err-form">There was a problem validating the form please check!</div>
<div class="error text-align-center" id="err-timedout">The connection to the server timed out!</div>
<div class="error" id="err-state"></div>
</form>
<script>
function SendEmail() {
var formData = new FormData();
formData.append("Name", $("#name").val());
formData.append("Email", $("#email").val());
formData.append("Attachment", $("#attachment")[0]);
formData.append("Message", $("#message").val());
alert($("#name").val());
$.ajax({
type: 'POST',
url: "/Home/SendEmail",
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (response) {
alert("Done");
$('#formPostComment')[0].reset();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
//}).done(function (data) {
// console.log(data);
// $("#ajaxwaiting").hide();
// $("#ajaxsuccess").show();
//});
event.preventDefault();
}
</script>
Here is my Controller action method.
[HttpPost]
public IActionResult SendEmail([Bind("Name,Email,Attachment,Message")] SingleEmailMessage message)
{
return Json(new { data = "DONE" });
}
The SingleEmailMessage class is as follows,
public class SingleEmailMessage
{
public string Name { get; set; }
public string Email { get; set; }
public IFormFile Attachment { get; set; }
public string Message { get; set; }
}
you might be sending two POSTs here... don't use onclick on the submit... instead use onsubmit on the form tag... ex:
<form ... onsubmit="SendEmail(); return false;"> Don't forget the "return false;" bit that replaces your event.preventDefault() call. It's also easier to pass the form's ID into your function... so
SendEmail("formPostComment")... then function SendEmail(id) {
...
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
On controller side get the file by using:
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
}
Not sure that the file is going to bind to your model.... get it from the raw request.
The full JS function I use is this (just for reference):
//for uploads
function PostFileFormID(id, buttonid, destURL) {
$('#' + buttonid).attr('value', "Uploading...");
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
jQuery.ajax({
type: 'POST',
url: destURL,
data: formData,
processData: false,
contentType: false,
success: function (data) {
params = convertJsonToParams(data);
url = "?" + params;
setLocation(url);
},
error: function (jqXHR, textStatus, error) {
DisplaySuperError(jqXHR, textStatus, error);
}
});
}
I have a simple modal form used to insert data; when i submit data, i correctly go to my method but the parameter still null value.
This is my Razor code:
<form id="SaveKeyForm" asp-page-handler="SaveExternalKEY" data-ajax="true" data-ajax-method="post">
<div class="modal-body">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<div class="form-group">
<label asp-for="wItem.Guid"></label>
<input asp-for="wItem.Guid" name="GUID" class="form-control" id="modalCustomerGUID" readonly required />
<span asp-validation-for="wItem.Guid" class="text-danger"></span>
</div>
<div class="form-group">
#Html.Hidden("External_Key_Type_ID", "")
<select class="custom-select mr-sm-2" asp-items="_KeyOptions" name="Selected_Key_Type_ID"><option selected>Choose</option></select>
</div>
<div class="form-group">
<label asp-for="wExternal_ID.ExternalKey"></label>
<input asp-for="wExternal_ID.ExternalKey" name="ExternalKEY" class="form-control" required/>
<span asp-validation-for="wExternal_ID.ExternalKey" class="text-danger"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="saveKey" class="btn btn-primary">Save</button>
</div>
This is my JS code:
$("#saveKey").click(function (e) {
e.preventDefault();
console.log('Ajax submit');
var form = $(this).parents('.modal').find('form');
var formAction = form.attr('action');
var fdata = form.serialize();
console.log(fdata);
var sdata = { GUID: 'fdsfas' };
$.ajax({
type: 'post',
url: formAction,
data: sdata,
dataType: "text",
processData: false,
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
statusCode: {
404: function () {
console.log("page not found");
},
200: function () {
console.log("Status Ok");
}
}
}).done(function (result) {
console.log('Result: ' + result);
});
});
and this is my method:
public IActionResult OnPostSaveExternalKEY(string GUID)
{
try
{
return new OkResult();
}
catch (Exception ex)
{
return new StatusCodeResult(404);
}
}
}
i have try to:
- pass data as 'fdata' variable: still null
- pass fixed data as 'sdata' variable: still null
- try to Json serialize: still null
If i use jquery-ajax-unobtrusive, i can pass correctly value to my method, but i cannot manage error message in modal form and url change.
Thanks for any help.
I'm having trouble passing a variable into a function in my view. I'm fairly new to MVC and not sure how I save and pass information.
#model Models.Schedule.SheduleModel
#{
Layout = null;
}
<div>
<div class="tableRow">
<p>Make a schedule reminder.</p>
</div>
<div class="tableRow tableRowHeading">
<div class="row" style="width: 210px">Name</div>
<div class="row" style="width: 210px">Number</div>
</div>
#foreach (var shedule in Model.ScheduleList)
{
<div class="tableRow">
#using (Html.BeginForm("UpdateSchedule", "Schedule", FormMethod.Post))
{
<div class="cell" style="width: 210px">
#Html.HiddenFor(model => schedule.Id)
#Html.TextBoxFor(model => schedule.Name, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => schedule.Name)
</div>
<div class="cell" style="width: 210px">
#Html.TextBoxFor(model => agent.ContactNumber, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => agent.ContactNumber)
</div>
<div class="cell">
<button name="Update" type="submit" value="Update" class="button" title="Update details">
<span class="text">Update</span>
</button>
</div>
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule();" value="Delete">
<span class="text">Delete</span>
</button>
</div>
}
</div>
}
</div>
#Scripts.Render("~/bundles/jqueryval")
<script>
function deleteFromSchedule() {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + Id,
data:
{
Id: Id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>
I'm trying to pass the schedule Id in HiddenFor into the delete function but everything I try doesn't work, i'm also curious on how to handle the information gotten from the text box in a later unwritten div, I'd like to produce text on the screen saying
User #Model.Name and number #Model.Number will be notified of schedule change but I keep displaying blank spaces. an I use the form I'm creating for this information, what would the syntax be?. My method in the schedule controller is very straight forward.
[HttpPost]
public void UpdateSchedule(int Id)
{
////do stuff here
}
The simplest way is to add your id from the schedule into the inline function call (using razor), and add an id param into your javascript delete function:
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule(#schedule.Id);" value="Delete">
<span class="text">Delete</span>
</button>
</div>
<script>
function deleteFromSchedule(id) {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + id,
data:
{
Id: id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>
I have a form html made using bootstrap in phpstorm, and I want to pass the information to a c# webservice using ajax.
Bust I have some doubts in what to put in the ajax url (represented bellow).
This is my html/bootstrap form:
<form role="form" action="" method="post" class="login-form">
<div class="form-group">
<label class="sr-only" for="form-username">Email</label>
<input type="text" name="form-username" placeholder="Email....." class="form-username form-control" id="form-email">
</div>
<div class="form-group">
<label class="sr-only" for="form-text">Type Order</label>
<input type="text" name="order" placeholder="Tipo Encomenda" class="form-text form-control" id="textbox1">
</div>
<span id="spnGetdet" style="font-size:x-large" />
<div class="form-group">
<label class="sr-only" for="form-number">Number</label>
<input type="number" min="0" max="150" name="orderQuantity" placeholder="Numero Peças" class="form-number form-control" id="form-number">
</div>
<div class="form-group">
<label class="sr-only" for="form-radio">Urgente</label>
<label class="radio-inline">
<input type="radio" name="optradio">Urgente</label>
<label class="radio-inline">
<input type="radio" name="optradio">Não Urgente
</label>
</div>
<button type="submit" class="btn btn-primary" id="submitOrder">Enviar</button>
</form>
And this is my ajax/jquery code:
<script type="text/javascript">
$("#submitOrder").click(function(){
$(document).ready(function () {
var TextBox1 = $("#textbox1");
TextBox1.change(function (e) {
var Name = TextBox1.val();
if (Name != -1) {
Getdet(Name);
}else {
<?php echo "erro"?>;
}
});
});
}
function Getdet(Name) {
$.ajax({
type: "POST",
url: "",
data: "{'Custname':'" + Name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response){
$("#spnGetdet").html(response.d);
},
failure: function (msg)
{
alert(msg);
}
});
}
</script>
And the last my c# webservice (this is a test, and i only want to collect the type of the order):
[WebMethod]
public String GetCustdet(string Custname)
{
return Custname;
}
So, if i have the project(website) made in phpstorm and webservice visual studio, what do I have to put in the url of ajax to reach the web service???
P.S: WebSite running in xampp
I'm assuming that, you are using MVC pattern I have given following url. You should replace controller name in [controller] place. You should replace localhost:5566 in or whatever in to [server-name].
option 1: [GET] http://[server-name]/[controller]/GetCustdet?Custname=Jhon
without data.
option 2: [POST] http://[server-name]/[controller]/GetCustdet
with data: '{Custname:"Jhon"}'
Otherwise, If you are using Asp.Net template to create the WebMethod then you should use the aspx page name in place the of [controller].
Alternatively, you have Route configurations to customize the URL and the data.
I have uploading images with ajax form in my ASp.Net application. I need to refresh images, so I try this:
$(function () {
$(".fileUploadForm").ajaxForm({
success: function (data, text, xhr, form) {
var tmp = jQuery(this).closest("img[class=imageResource]").attr('src');
}
});
});
Here is my image:
<img class="imageResource" alt="picture" src="#Url.Action("Picture", new { id = Model.Id })" />
How can I find and rewrite image source with the same name
Update
Here is my html:
<div class="thumbnail">
<a target="_blank" href="/Template/OriginalPicture/8b8c824b-9605-4931-9fe2-1f5979baca42">
<img class="imageResource" src="/Template/Picture/8b8c824b-9605-4931-9fe2-1f5979baca42" alt="picture">
</a>
<div class="caption">
<div style="margin-bottom: 5px;">
<form class="form-horizontal fileUploadForm" method="post" enctype="multipart/form-data" action="/Template/PictureResource?resourceId=8b8c824b-9605-4931-9fe2-1f5979baca42&configId=aa383b5a-23b2-4780-965e-ef4e95cd3fa2&pageNumber=1">
<div class="input-append">
<input type="file" name="picture">
<input class="span1" type="text" size="128" style="width: 86px;">
<button class="btn browse" type="button"> ...</button>
<button class="btn" type="submit">Upload</button>
</div>
</form>
</div>
</div>
try this code:
$(function () {
$(".fileUploadForm").ajaxForm({
success: function (data, text, xhr, form) {
var tmp = form.closest('.thumbnail').find('.imageResource').attr('src');
form.closest('.thumbnail').find('.imageResource').attr('src', tmp + "?" + (new Date()).getTime());
}
});
});
I'm not sure if jQuery(this) will return a form (do not remember what is "this" there )
(new Date()).getTime() - is just to change image URL and force brower take image not from cache. Uh. And not noticed .closest - it will search for closest parent, and not for a child element. You may use .find for that.
form - that is a current from, according to docs closest('.thumbnail') will find parent with class .thumbnail closest to a form. .find('.imageResource') will search for an elements with class imageResource only inside .thumbnail. As there is only one image tag with class imageResource inside thumbnail - code above should work fine