Why is my form still reseting when I submit with JavaScript? - javascript

I am submitting a form with JavaScript.
Here is my form:
<form id="rolesSelectForm" class="stdform" action="" onsubmit="return submitForm()">
<p>
<label>Select User</label>
<span class="field">
<select name="selectUser" id="selectUser">
#foreach (var item in Model.Users)
{
<option value="#item.Id">#item.UserName</option>
}
</select>
</span>
</p>
<p class="stdformbutton">
<button class="submit radius2" type="submit">Save</button>
</p>
And here is my script:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
//Shows the success message
function showSuccessMessage(data) {
alert(data);
}
Now when I click the button, the page does refresh and I never get my alert.
In chrome its at least makes the ajax post request but in Firefox, it just reloads the page before the post is even made.
From what I read if I made my form return the JavaScript function, it would not reload. However this is not my case.

From what I read if I made my form return the java script function it would not reload.
No. You have to return false.
This is typically done by returning the return value of the function, and then returning false from that function. A lot of the time this will be done conditionally (since often you will be testing the user input to make sure it is OK before allowing the form to submit.)
You don't have a return statement in your function.

Please add return false in function
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
return false;
}

Related

AJAX call not working on EJS multiple forms (works just on the first form)

I have a like button on multiple posts, in EJS. Problem is, when I am clicking the first like button, the form sends and updates the View accordingly.
When I click the other buttons they all seem to send and update the first form, and they also update the first button adding the 'active' class to it.
I tried deleting the IDs and adding classes, still same result.
My guess is there is a fault in my AJAX or HTML structure because form is updating the database with no problem.
HTML:
<form id='like' action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST">
<% if (blogposts[i].liked == false) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
<% if (blogposts[i].liked == true) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts active">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
</form>
AJAX:
let likeButton = document.querySelector('.wrapperHearts');
let frm = $('#like');
function Like(){ frm.submit()}
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log("success");
console.log(data)
if (data.liked == false){
likeButton.classList.add('active')
$("#likesNumber").text(data.likes +1 + ' ' + 'Likes')
}
else{
likeButton.classList.remove('active')
$("#likesNumber").text(data.likes -1 + ' ' + 'Likes')
}
},
error: function(request, status, error) {
console.log("error")
}
});
});
In the form I am using method-override.
I have assigned the EJS dynamic ID to the rendered forms, and then I have created a function which triggered on event, gets the ID of the specific form and assigns it into the AJAX call.
HTML
<form class="likeForm" id="like<%=[i]%>" action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST" onsubmit="postData(event, this.id)">
More details
var elem = $('#'+id)[0]; // I took the HTML form element in order to assign it to the new form data as seen below
var formData = new FormData(elem)
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
//Used the find() method in order to find the specific element that I want to be updated in real time.
AJAX
function postData(event, id) {
event.preventDefault(event)
var elem = $('#'+id)[0];
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
var currentUserId = <%-JSON.stringify(currentUser._id)%>
console.log(currentUserId)
var formData = new FormData(elem)
console.log(likeButton)
console.log(likesNumber)
$.ajax({
async: true,
type: elem.getAttribute("method"),
url: elem.getAttribute("action"),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if(!data.userLikes.includes(currentUserId)){
likeButton.addClass('active')
likesNumber[0].innerHTML = data.likes + 1 + ' ' + 'Likes'
}
else{
likeButton.removeClass('active')
likesNumber[0].innerHTML = data.likes - 1 + ' ' + 'Likes'
}
}
})
}

.html() not displaying fields

I am currently trying to use .html() to display out the resident id, name and telephone number. However, there is nothing appearing on my page. When I check my console for any errors, there were none. There is no error with the php and residentid is in the localstorage.
html
<div role="main" class="ui-content" id="main-ui">
<div id="txtresidentid"></div>
<div id="txtresident_name"></div>
<div id="txtresident_telephone_home"></div>
</div>
javascript
(function () {
var residentid;
var resident_name;
var resident_telephone_home;
$(document).ready(function () {
getProfile();
});
function getProfile() {
var url = serverURL() + "/getresidentprofile.php";
var JSONObject = {
"residentid": localStorage.getItem("residentid")
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getProfileResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getProfileResult(arr) {
residentid = arr[0].residentid;
resident_name = arr[0].resident_name;
resident_telephone_home = arr[0].resident_telephone_home;
$("#txtresidentid").html("Residentid : " + residentid);
$("#txtresident_name").html("Name: " + resident_name);
$("#txtresident_telephone_home").html("Telephone(Home): " + resident_telephone_home);
}
})();
Try this:
$("#txtresidentid").append("Residentid : " + residentid);
$("#txtresident_name").append("Name: " + resident_name);
$("#txtresident_telephone_home").append("Telephone(Home): " + resident_telephone_home);

How to populate data from API and load into dropdown

I am working on MVC application that uses API and i want to call a method from the API so that it will load the data to the combo-box. I have no idea on how i can tackle this as am new this.
Thanks.
ClaimController function from the API which got this function.
[RoutePrefix("api/Claim")]
[Route("GetScheme")]
[HttpGet]
public HttpResponseMessage GetScheme()
{
try
{
using (IBusinessLogic logic = new BusinessLogic.Implementation.BusinessLogic())
{
Request.Headers.Clear();
var tmpresults = logic.GetScheme();
var results = (from x in tmpresults.Result select new { text = x.Description, value = x.Id }).ToArray();
var response = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
}
}
Views from the Client which is the UI
I want to call that function from API to load the data into the combo-box
function GetAllScheme() {
var select = $("#ddlScheme");
$.ajax({
type: "GET",
url: "http://localhost:55393/_Api/Claim",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
var serverResponse = datavalue;
contentType: "application/json";
$.each(serverResponse, function (i, serverResponse)
{
select.append("<option value='" + serverResponse.Description + "'>" + serverResponse.Description + "</option>")
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Dropdown
<select class="dropdown form-control input-xs required" id="ddlScheme" onclick="GetAllScheme()(this)">
<select
</select>
</div>
You have to append option elements into your select (dropdown) element after you get the server response. Something like this:
function GetAllScheme() {
// get the dropwdown by its id
var select = $("#ddlScheme");
$.ajax({
...
success: function (data) {
$.each(myJsonObject, function (i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description + '</td></tr>');
// for each element, add an option into the dropdown
select.append('<option>"+ mobj.Description +"</option>')
}
});
...
)}
See jsfiddle https://jsfiddle.net/n4mtj9om/
If use Chrome enter in developers tools a see how response the server put a breakpoint after server response because when use maybe
put this
function GetAllScheme() {
$.ajax({
type: "GET",
url: "http://localhost:32359/api/Claim",
dataType: "json",
success: function(data) {
$.each(data.responseJSON, function(i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description +
'</td></tr>');
});
},
error: function(xhr) {
alert(xhr.responseText);
}
});
}

Debugging jquery handlers

This question is a followup of this one. I have created a simple example to check how code is executed within the handler. For the form
<form id="calendar_id" method="post">
Insert date: <input id="date_id" type="text" name="l_date" required>
</form>
I'm trying to retrieve the fields using the following javascript:
function get_form_data_uid($form) {
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function (n, i) {
indexed_array[n['name']] = n['value'];
});
indexed_array['uid'] = 'badbfadbbfi';
return indexed_array;
}
$("#calendar_id").submit(function (e) {
var uri, method, formId, $form, form_data;
// Prevent default submit
e.preventDefault();
e.stopImmediatePropagation();
uri = "/";
method = "POST";
formId = "#calendar_id";
$form = $(formId);
form_data = get_form_data_uid($form);
alert("form_data " + form_data);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
// Setting async to false to give enough time to initialize the local storage with the "token" key
async: false,
dataType: "json",
data: form_data
};
// Make the request
$.ajax(request).done(function (data) { // Handle the response
// Attributes are retrieved as object.attribute_name
console.log("Data from change password from server: " + data);
alert(data.message);
}).fail(function (jqXHR, textStatus, errorThrown) { // Handle failure
console.log(JSON.stringify(jqXHR));
console.log("AJAX error on changing password: " + textStatus + ' : ' + errorThrown);
});
});
However, the code within the handler is not executed (the alert is not shown). Why?
Edit:
The code works jsfiddle but not in firefox.
At least, you are calling a function get_form_data_with_token() which is not defined anywhere in your posted code. Perhaps you meant to call your get_form_data_uid().
Would have just made this a comment, but apparently cannot.

Upload any file without reloading or redirecting page

I am Trying to upload file without reloading or redirecting page to other page.
I have tried...
upload.php
<form enctype='multipart/form-data' action='/' method='POST' class="AjaxSubmit" id='newwork' name='newwork'>
Choose New Work<br />
<input name='uploadednewwork' type='file' /><br />
<button id="btnFrmPost1" class="button" onclick="up()" >New Work</button>
</form>
script.js
function up() {
$('#btnFrmPost1').click(function() {
event.preventDefault();
var $form = $(this);
var url = "/subpages/upload_new_work.php";
var data = $form.serialize()
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: data,
success: function (resp) {
var jdata = eval(resp);
var $jAlrtSuccess = $('<div>' + jdata.responseText + '</div>');
$($jAlrtSuccess).dialog({modal:true});
},
error: function (xhr, status, error) {
var $jAlrtError = $('<div>' + xhr.responseText + '</div>');
$($jAlrtError).dialog({modal:true});
}
});
return false;
});
}
I have tried all this code...
but i wont get result...
can any one please tell me how to solve this problem...

Categories