C# AJAX reloading the form - javascript

I'm learning C# MVC and now creating a project.
I have a problem with understanding AJAX - I can't understand why it doesn't work. After clicking the save button the form is reloading (?). After the second click, the code goes to SearchRouts(). But then - just nothing happens. Neither code from success, nor from error block (I set simple alerts to check it). It looks like the form just reloads (?). I can't figure out what's happening.
I think it is something with the end of SearchRoutes() - should I send the response in another way?
Thank you for your help.
Here is my code:
Index.cs.html:
<form id="search_form" method="post">
<label class="search__header">Długość: </label></br>
<div class="search__options">
<select class="search__select" name="search_len" id="search_len" multiple>
<option value="len1">0-100 km</option>
<option value="len2">100-150 km</option>
<option value="len3">150-300 km</option>
<option value="len4">+300 km</option>
</select>
</div>
<label class="search__header">Difficulty: </label></br>
<div class="search__options">
<select class="search__select" name="search_dif" id="search_dif" multiple>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</select>
</div>
<label class="search__header">Pavement: </label></br>
<div class="search__options">
<select class="search__select" name="search_pav" id="search_pav" multiple>
<option value="asphalt">Asphalt</option>
<option value="forest">Forest</option>
<option value="mix">Mix</option>
</select>
</div>
<div class="search_options search__options--submit">
<img class="search__img" src="img/compass.png">
<button class="panel__button panel__button--submit" id="search_submit" type="submit">Search</button>
</div>
</form>
search.js:
$("#search_submit").on("click", function () {
console.log("SUBMIT CLICKED!");
var search_obj = {}
search_obj.Length = $("#search_len").val()[0];
search_obj.Difficulty = $('#search_dif').val()[0];
search_obj.Pavement = $('#search_pav').val()[0];
console.log(search_obj);
alert("ALERT!");
$.ajax({
type: "POST",
url: '/User/SearchRoutes',
data: JSON.stringify(search_obj),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Success!");
console.log(response);
},
error: function (response) {
alert("Error. Try again.");
}
});
});
UserController.cs:
public ActionResult SearchRoutes([FromBody] JsonSearch search)
{
double min = 0;
double max = 1000;
if(search.Length=="len1")
{
max = 100;
}
else if(search.Length=="len2") {
min = 100;
max = 150;
}
else if(search.Length=="len3")
{
min = 150;
max = 300;
}
else
{
min = 300;
}
var list = _userService.FindRoutes(min, max, search.Difficulty, search.Pavement); // returns C# list of routes objects from database
var json = JsonSerializer.Serialize(list);
return Json(json);
}

In the javascript function call use
$("#search_submit").on("click", function (e) {
console.log("SUBMIT CLICKED!");
e.preventDefault();
...
To skip the reload event after submit is pressed.

Related

JS+ASP Net Core Get data from controller

the question arose: How to get data from the controller in asp net core using js?
I tried to send a post request head-on, but it seems to me there is a more elegant solution
At the same time, I need this to happen when the html of the Select element changes
I wrote a script that changes the field when the select changes
function Change_Aud() {
var x = document.getElementById("Levelid").value;
document.getElementById("Hardware_La").value = x ;
}
Controller example
public async Task<IActionResult> Get_Hardware_Unit(int id)
{
Level level = _context.Levels.Where(p => p.Number == id.ToString()).First();
return Content(level.Public_Hardware.ToString());
}
Test page code in cshtml:
#{
ViewData["Title"] = "Home Page";
int count = 5;
}
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
function myFunction(selectObject) {
var value = selectObject.value;
$("#selectnum").html(value);
backendfunc(value);
}
function backendfunc(value) {
$.ajax({
url: "/Test/Get_Hardware_Unit",
type: "GET",
data: { id: value },
success: function (res) {
$("#convertnum").html(res);
},
error: function (hata, ajaxoptions, throwerror) {
$("#convertnum").html("convert failed");
}
});
}
</script>
<div>
<select name="num" id="num-select" onchange="myFunction(this)">
<option value="">--Please choose an option--</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<br />
<br />
<div>
You select value is : <span id="selectnum"></span>
</div>
<br />
<br />
<div>
After backend converted, here is : <span id="convertnum"></span>
</div>
My function in Controller:
public async Task<IActionResult> Get_Hardware_Unit(int id) {
string result = string.Empty;
if (id == 1) {
result = "①";
}
if (id == 2)
{
result = "②";
}
if (id == 3)
{
result = "③";
}
return Content(result);
}
Test Result

Get selected value from a dropdown to use it in another dropdown Laravel

In my view, I have two dropdowns, the first dropdown have items and the second dropdown don't have item. It looks like this:
<form action="http://localhost/AutoFill/public/handle-form" method="POST">
<div>
City:<br>
<select name="city">
<option value="">Choose Place</option>
<option value="0">HCM</option>
<option value="1">HN</option>
</select>
</div>
<br>
<div>
Ward:<br>
<select name="ward">
<option value="">---</option>
</select>
</div>
<br>
</form>
Now I want to get the value of the first dropdown to fill data into the second dropdown. I create a function in my controller for returned second dropdown data:
public function getSecondEnumData(Request $request)
{
$firstEnumSelected = $request->city;
$client = new Client();
if ($firstEnumSelected === 0) {
$enumValueResponse = $client->request('GET', 'https://api.myjson.com/bins/zcyj2');
} else {
$enumValueResponse = $client->request('GET', 'https://api.myjson.com/bins/1bx7e6');
}
return json_decode($enumValueResponse->getBody(), true);
}
I searched some post in here, and I think I should write some JavaScript code in my view to do this but I'm not familiar with it so can you help me?
Route
Route::get('/', 'RestController#getFirstEnumData');
You can try like this, My Answer will not give you 100% soluton of your problem as I am little bit confused about your controller function. But I hope it will help you.
First of all your route need to be POST as you are taking Request data in the function.
Route::POST('getFirstEnumData', 'RestController#getSecondEnumData');
add csrf in the meta
<meta name="csrf-token" content="{{ csrf_token() }}" />
And then
<form action="http://localhost/AutoFill/public/handle-form" method="POST">
<div>
City:<br>
<select name="city" id="city">
<option value="">Choose Place</option>
<option value="0">HCM</option>
<option value="1">HN</option>
</select>
</div>
<br>
<div>
Ward:<br>
<select name="ward" id="ward">
<option value="">---</option>
</select>
</div>
<br>
</form>
$("#city").change(function() {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var city = $( "#city" ).val();
$.ajax({ //create an ajax request to get tour list
type: "POST",
url: "/getFirstEnumData",
data : ({
_token: CSRF_TOKEN,
city : city
}),
success: function(response){
var responseData = JSON.parse(response);
var dataLength = responseData.length;
$("#ward").empty();
$("#ward").append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = responseData[i].id;
var name = responseData[i].name;
$("#ward").append("<option value='"+id+"'>" + name + "(" + name+")"+"
</option>");
}
}
});
});
Place the following code just above your </body> tag, change the success according to your reponse data, also url according to your url
<script>
let origin = document.querySelector(select[name='city'])
let target = document.querySelector(select[name='ward'])
origin.addEventListener('change', function(){
$.ajax({
url: '{{ url('/') }}',
method: 'POST',
data:{ city: origin.value, _token: '{{ csrf_token() }}' },
success: function(response){
response.forEach((opt) => {
target.innerHTML += `<option value=${opt.id}>${opt.value}</option>` //this varies according to your response data
})
}
})
})
</script>

Pass onlyedited form fields for AJAX PUT request from REST API

I have a form with several fields in it, on Save button click it will a trigger an AJAX request to update my data. Currently its only working if I fill all of the fields in the form for update because I'm passing the $('#field').val(), but what if I want to only update one of the field? How can I do it without requiring the rest of the field because I'm using this for multiple editing based on which row(s) of data I've selected to update
below is my code :
HTML :
<form id="create_project" method="POST" enctype="multipart/form-data">{% csrf_token %}
<div>
<label>Priority:</label>
<select id="priority_field">
<option selected="selected">Select Your Priority</option>
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
<option value="Critical">Critical</option>
</select><br>
<label>Assign To: </label>
<select id="assign_to_field" onchange="filter_by_users();">
<option selected="selected">Select Your User</option>
<option value="None">None</option>
{% for user in selected_project.user.all %}
<option value="{{ user }}">{{ user }}</option>
{% endfor %}
</select>
<br>
<label> Start Date:</label>
<input type="date" class="form-control" id="start_date_field"><br>
<label>Duration:</label>
<input type="number" class="form-control" id="duration_field"><br>
</div>
<div class="modal-footer modal_styling">
<button type="button" class="btn btn-primary" onclick="editForm()">Edit
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel
</button>
</div>
</form>
javascript :
// TASK MULTI EDIT
function editForm(){
var selected_task = gantt.getSelectedTasks();
for(var i = 0; i < selected_task.length; i++){
var task = selected_task[i];
var data = gantt.getTask(task);
$.ajax({
type: 'PUT',
url: '/api/dashboard/workorder_detail/' + data.workorder_id + '/',
data: { "id" : data.workorder_id,
"priority": $('#priority_field').val(),
"assign_to": $('#assign_to_field').val(),
"start_date": $('#start_date_field').val(),
"duration": $('#duration_field').val(),
},
success: function () {
location.reload();
},
error: function (err) {
alert("Failed");
}
})
}
}
Any help is much appreciated, thanks.
First You should handle it which fields is changed then you can select for sending as parameter on ajax request.
This is listener for which field has changed and add class name of 'has-changed'
function changeEvent() {
if(!$(this).hasClass('has-changed'))
$(this).addClass('has-changed');
}
This is set event for inputs
$('#create_project input,select').on('change',changeEvent);
Then you can select changed fields with below code
var postData = {};
$('#create_project .has-changed').each(function (i,e) {
var id = $(e).attr('id');
var value = $(e).val();
postData[id]=value;
});
after then you add the postData in your ajax 'data' properties like this
$.ajax({
type: 'PUT',
url: '/api/dashboard/workorder_detail/' + data.workorder_id + '/',
data: postData,
success: function () {
location.reload();
},
error: function (err) {
alert("Failed");
}
})
EDIT :
you should use below code before "editForm" function because this code didn't read from browser before click edit button, you can see it works after click and change any form item and click second time edit button in your code.
function changeEvent() {
if(!$(this).hasClass('has-changed'))
$(this).addClass('has-changed');
}
$('#edit_form input,select').on('change',changeEvent);
// TASK MULTI EDIT
function editForm(){
var selected_task = gantt.getSelectedTasks();
var postData = {};
$('#edit_form .has-changed').each(function (i,e) {
var id = $(e).attr('id');
var value = $(e).val();
postData[id]=value;
});
for(var i = 0; i < selected_task.length; i++){
var task = selected_task[i];
var data = gantt.getTask(task);
$.ajax({
type: 'PUT',
url: '/api/dashboard/workorder_detail/' + data.workorder_id + '/',
data: postData,
success: function () {
// location.reload();
console.log(postData);
},
error: function (err) {
alert("Failed");
}
})
}
}

Ajax Call to append a div not working

I'm actually new to ajax and jquery, and I've started working on it only a few days ago. I have a jsp code like this :
<label>Choose the type of procedure you want :</label>
<select id="proc-type" name="proc-type">
<option value="selection">Select</option>
<option value="with-param">With parameters</option>
<option value="without-param">Without parameters</option>
</select>
<div class="drop" id="dropdown">
<label> Select Procedure (with parameters) : </label>
<select id="combobox" name="combobox">
<option>Proc1</option
<option>Proc2</option>
...
...
</select>
</div>
<div class="drop" id="drop">
<label> Select Procedure (without parameters) : </label>
<select id="combobox2" name="combobox2">
<option>Proc a</option
<option>Proc b</option>
...
...
</select>
</div>
<div id="response"></div>
Now, these values are sent to a servlet and a html response is generated. The ajax call I used is :
if first dropdown changes :
document.getElementById("combobox").onchange = function(){
var proc_type = document.getElementById("proc-type").value ;
var username = document.getElementById("combo").value ;
var proc_name1 = document.getElementById("combobox").value ;
var proc_name2 = document.getElementById("combobox2").value ;
console.log("before calling servlet ");
$.ajax({
url : "DBConnectServlet?user="+username+"&proc-type="+proc_type+"&combobox="+proc_name1+"&combobox2="+proc_name2,
type : "GET",
dataType:"text/html",
success: function (data) {
console.log("in ajax "+ data);
$('#response').html(data);
}
});
};
if second dropdown changes :
document.getElementById("combobox2").onchange = function(){
var proc_type = document.getElementById("proc-type").value ;
var username = document.getElementById("combo").value ;
var proc_name1 = document.getElementById("combobox").value ;
var proc_name2 = document.getElementById("combobox2").value ;
console.log("before calling servlet ");
$.ajax({
url : "DBConnectServlet?user="+username+"&proc-type="+proc_type+"&combobox="+proc_name1+"&combobox2="+proc_name2,
type : "GET",
dataType:"text/html",
success: function(data) {
console.log("in ajax "+ data);
$('#response').html(data);
}
});
};
But problem is, the response is generated fine, but the div is not getting appended. Can anybody help ?
Even if there is some other way to do it, please suggest.
Try changing dataType to "text" or "html".There is no "text/html" in jquery manual about ajax on dataType.Good luck.

Validate select field

I'm validating a form, but I'm having problems with this particular select validation.
<div class="control-group" id="sukupuoli">
<label class="control-label">Sukupuoli</label>
<div class="controls">
<select name="sukupuoli">
<option value="Valitse">Valitse</option>
<option value="Naaras">Naaras</option>
<option value="Uros">Uros</option>
</select>
</div>
</div>
Here's the JS for the validation:
$('#ilmoittuminen').submit(function(){
var Sukupuoli = $('input[name=sukupuoli]').val()
if(Sukupuoli == "Valitse"){
$('.control-group#sukupuoli').addClass("error");
$('select[name=sukupuoli]').focus();
return false;
}
var ilmoittautumisdata = $('#ilmoittuminen').serialize();
$.ajax({
url: "",
data: ilmoittautumisdata,
type: "POST"})
.done(function () {
})
.error(function () {
$('.control-group').addClass("alert");
});
return false;
});
It doesn't submit, but it doesn't add the class error either. A fiddle.
You should be using select here:
var Sukupuoli = $('select[name=sukupuoli]').val()
Example: http://jsfiddle.net/HV7sn/1/
You don't need to use $('.control-group#sukupuoli').addClass("error"); just select it by the id only:
$('#sukupuoli').addClass("error");

Categories

Resources