Ajax Call to append a div not working - javascript

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.

Related

C# AJAX reloading the form

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.

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>

posting to database via ajax

I have a js function to update the database according to values from the select input fields.
This is the javascript function:
function getStatusAction()
{
var matchId = $(this).attr('match-id');
var status = jQuery('#match-status').val();
jQuery.ajax({
url:'../core/match_stat.php',
type:'POST',
data:{matchId:matchId,status:status},
success: function(data){
//alert("Ok");
},
error: function(){
alert("Error..");
},
});
}
jQuery('select[name="match-status"]').change(getStatusAction);
Part of the html:
<tr>
<td>
<select class="input" name="match-status" match-id="<?=$ActiveMatch['id'];?>" id="match-status">
<option value="3" <?= (($ActiveMatch['status'] == '3')?'selected':'')?>> </option>
<option value="1" <?= (($ActiveMatch['status'] == '1')?'selected':'');?> >won</option>
<option value="2" <?= (($ActiveMatch['status'] == '2')?'selected':'');?> >lost</option>
</select>
</td>
</tr>
The function is supposed to get the id of the match eg 1,2... and the status eg 1,2,3 for loose, win and default status respectively.
The problem is I can only update the first row of data. If I try doing so on another row of data, the values from the first call are used. For example if I update first row status to win, if I try updating second row to loose it is updated to win. The status of the previous operation.
How can I solve this?
you can try
function getStatusAction(Element) //<< add parameter here
{
var matchId = $(Element).attr('match-id'); // <<< use it here
var status = jQuery('#match-status').val();
jQuery.ajax({
url:'../core/match_stat.php',
type:'POST',
data:{matchId:matchId,status:status},
success: function(data){
//alert("Ok");
},
error: function(){
alert("Error..");
},
});
}
jQuery('select[name="match-status"]').on('change' , function(){
getStatusAction(this); // << use the function here
});
Note: id should be unique so if you have only one element with id match-status its fine .. but if your selects have the same id you need to change id="match-status" to class="match-status" and change var status = jQuery('#match-status').val(); to var status = $(Element).val();

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");
}
})
}
}

Simualating user clicks using JavaScript or JQuery

There is a website that I want to simulate user clicks on. In this website, there is the following div, let's call it div1, where there is a dropdown menu. There are actually other two similar divs (lets call them div2 and div3) following but I didn't place here for the simplicity. When you select one of the item in the dropdown menu in div1, the div2 is enabled (disabled by default in the beginning) and its menu content is fetched from database based on the item selected from the div1.
I can select the menu item using following script.
Code:
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].value== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
var number = document.getElementById('level1-option');
setSelectedValue(number, "p3");
However, when I do this, the div2 is never enabled. I tried jQuery code to emit change signal on the dropdown menu but it doesn't work. When I was debugging the below html code, I saw the button tag there and I immediately thought that it submits when there is click. However, I don't see any form. If I debug the website using chrome, I see that the code jumps different js files when I select an item in the menu. Could anyone guide me how I can find out which signal is triggered when an item is selected? Apparently they do some tricks in the website to prevent normal ways of clicking
Code:
<div data-custom-select="" class="custom-select focus">
<label for="level1-option" class="has-hidden-label label-text">Sections</label>
<span class="btn-select icon-down_thin">Choose a section</span>
<select class="categories-options" data-level="1" name="level1-option" id="level1-option" required="">
<option value="">Choose a section</option>
<option value="p1" data-href="/callback/discovery/p1/">P1</option>
<option value="p2" data-href="/callback/discovery/p2/">P2</option>
<option value="p3" data-href="/callback/discovery/p3/">P3</option>
<option value="p4" data-href="/callback/discovery/p4/">P4</option>
</select>
<span class="icon-down_thin"></span>
<button type="submit" class="category-submit ui-button-secondary ">Choose</button>
Usually you could use:
$("#level1-option").val(valueToSet).trigger("click")
or
$("#level1-option").val(valueToSet).trigger("change")
but it might depend on the rest of the code on the webpage.
Try ...
$(element).trigger('click');
... from jQuery.
Try dispatching onchange event once you have changed its value:
var number = document.getElementById('level1-option');
setSelectedValue(number, "p3");
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
number.dispatchEvent(evt);
Sorry, that I couldn't help with the overlay issue. Your markup is pretty complex.
Anyway, I coded a bit for the updating/fetching data from database. Please find below a demo of it.
The demo is also here at jsFiddle
The JSON data looks like this {"data": ["1st_1", "1st_2", "1st_3"]}
During my work I had one issue that wasn't that easy to solve, but another SO question helped here. If you'd only use the change event you can't trigger the first element to fetch your next data.
The counter trick works pretty well.
var dynamicOptions = (function () {
var url; // here you can add your url to the backend script
// urlList only required for demo because no backend available
var urlList = ['http://www.mocky.io/v2/54839e2a2f4b84a0041bba49',
'http://www.mocky.io/v2/54839e4c2f4b84a5041bba4a',
'http://www.mocky.io/v2/54839e6a2f4b84a9041bba4b'];
var cc = 0; // click counter
// e.g. $optionEl = $('#firstSelection');
// $nextOptionEl = $('#secondSelection');
function Selector($optionEl, $nextOptionEl) {
this.$optionEl = $optionEl;
this.$nextOptionEl = $nextOptionEl;
this.ajaxRequest = function (optionValue) {
return $.ajax({
type: 'GET', // later 'POST'
//data: {'data': optionValue}, // for posting
url: url,
contentType: "application/json",
dataType: 'jsonp',
context: this,
});
};
this.getData = function(value) {
url = urlList[value]; // simulating backend returns based on this value
var ajaxReq = this.ajaxRequest(value); // this.value not used in this demo
ajaxReq.success(this.jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
};
// handle click and change event. Source from here: https://stackoverflow.com/questions/11002421/jquery-event-to-fire-when-a-drop-down-is-selected-but-the-value-is-not-change
this.clickHandler = function ($element) {
//console.log($element);
var that = this;
return $element.click(function () {
//console.log('clicked');
cc++;
if (cc == 2) {
$(this).change();
cc = 0;
}
}).change(function (e) {
cc = -1; // change triggered
//console.log(this.value);
that.getData(this.value);
});
}
this.clickHandler($optionEl);
this.jsonCallback = function (json) {
var $nextEl = this.$nextOptionEl;
$nextEl.empty(); // clear selection
$nextEl.prop('disabled', false); // enable 2nd select
this.triggerChangeEvent(); // maybe a check if they really changed would be good
$.each(json.data, function (index, value) {
$('<option/>')
.val(index)
.text(value)
.appendTo($nextEl);
});
};
this.triggerChangeEvent = function () {
var event = jQuery.Event("optionsChanged");
event.context = this;
event.message = "Options changed, update other depending options";
event.time = new Date();
$.event.trigger(event);
};
}
return {
Selector: Selector
}; // make Selector public
})();
$(function () {
var $first = $('#firstSelection');
var $second = $('#secondSelection');
var $third = $('#thirdSelection');
// use our dynamic options selector class
var options12 = new dynamicOptions.Selector($first, $second);
var options23 = new dynamicOptions.Selector($second, $third);
$(document).on('optionsChanged', function (e) {
console.log("options changed", e);
var obj_id = e.context.id;
//console.log(obj_id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div>
<form role="form">
<div class="form-group">
<label>Please select first value:</label>
<select id="firstSelection" class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="form-group">
<label>Please select second value:</label>
<select id="secondSelection" class="form-control" disabled="true">
<!-- fetched from server -->
</select>
</div>
<div class="form-group">
<label>Please select third value:</label>
<select id="thirdSelection" class="form-control" disabled="true">
<!-- fetched from server -->
</select>
</div>
</form>
</div>

Categories

Resources