How to sort result in JavaScript - ajax

I'm getting success result in my ajax code and can return data in my view but i want to sort the results by their id in database,
Example
id => 3 , one
id => 5 , three
id => 2 , five
result should be:
five
one
three
Code
<script defer>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key1, value1) {
var vvvid = value1.id;
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
var my_row = $('<div class="row mt-20 ccin">');
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><input id="text_dec" name="text_dec[]" placeholder="text field" class="text_dec form-control"></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
$('div#dataaa').append(my_row);
}
});
// second data
});
}
});
}else{
$('div#dataaa').empty();
}
});
});
</script>
PS: what I need is to return vvvid part by their id in database.
Question
How can I sort my output data?

Sort your result by the id in a one-liner shameless lifted from this answer.
Then $.each() it.
success:function(result) {
result.sort(function(a,b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
});
// console.log(result);
$.each(result, function(key1, value1) {

I believe that your ID is in your object like it
{
id: 1,
title: sample
}
Make a function like it
static compare(a,b) {
if (a.id > b.id)
return -1;
if (a.id < b.id)
return 1;
return 0;
}
Using
let array = [{},{},{}];
array.sort(this.compare);
To change the order by, just reverse > and < in the function

Related

how to use the same ajax call on the created dropdown list

dears , i have one table to show the list of category and i need to add unlimited drop down list which will be nested from the parent
like
category A
Category B , if selected B it will add another dropdown and added it into data base and will add another dropdown list sub b1 , sub 2 and if user select sub 2 will do the same
can anyone help
$(document).ready(function(){
//$('.form-control').change(function(){
$('select.form-control').on('change', function () {
var selectedCategory = $(this).children("option:selected").val();
var counter = 1;
//alert( $(this).find('option:selected').text());
//var deptid = $('#category option:selected').attr("id");
var name = "Sub "+ $(this).children("option:selected").text();
if(selectedCategory!=''){
$.ajax({
url: "<?php echo base_url(); ?>category/add_new",
type: 'POST',
data: {'category_parent':selectedCategory,'category_name':name},
dataType: 'json',
async: false ,
cache:false,
success:function(data){
alert(data);
if($('#category'+data).length)
return;
else{
$("#groupd").after('<div id="sub'+data+'" class="form-group">' +
'<label>' +name +' : </label>' +
'<select class="form-control" name="dropdown' + counter + '" id="category'+data+'">' +
// Add your options here...
'<option>Please Select</option>'+
'<option value="'+data+'">'+name +'1</option>'+
'<option value="'+data+'">'+name +'2</option>'+
'</select></div>');
counter++;
}
},
error:function(){
alert('error');
}
});
}
});
});
</script>

How does Codeigniter receive the ajax post data in controller without input type text and input post

Here's code for Controller :
public function Update()
{
$id_form = $this->input->post('id_form');
$no_request = $this->input->post('no_request');
$data = {
"no_request" => $no_request,
"date_ps" => date('d M Y')
}
return $this->db->where('id_form', $id_form);
return $this->db->update('table', $data);
}
Here's code for View :
<input type="hidden" name="id_form" id="id_form"></br>
<input type="text" name"no_request" id="no_request"></br>
Edit
Here's code for Ajax :
$('#btn_update').on('click', function() {
var id_form = $('#id_form').val();
var no_request = $('#no_request').val();
var date_ps = $(date_ps).val();
$.ajax({
type: "POST",
url: "<?= site_url('Controller/Update') ?>",
dataType: "JSON",
data: {
id_form: id_form,
no_request: no_request,
date_ps: date_ps
},
success: function(data) {
console.log(date_ps);
}
})
}
But The result for date_ps is undefined, How can I get the date_ps value without having to undefined

How can I get the dynamic value to my id variable in javascript?

I have been trying to get the different values in my id variable in javascript so that I can fetch the data according to the id I hover.
I have following code inside the <script></script>
$(document).ready(function() {
$('.stambha-img').hide();
$(".stambha-cat").hover(function() {
var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value");
$.ajax({
url: '/ajaxCat.php',
type: 'POST',
data: {
id: id
},
success: function(response){
if (typeof(response) != 'object') {
response = $.parseJSON(response);
}
if (response.status.status == true) {
var html_option = ""
$.each(response.body, function(key, value) {
var newsImage = "";
if(value.image === ""){
newsImage = "<?php echo FRONT_IMAGES_URL.'shikshak.jpg' ?>";
} else {
newsImage = value.image;
}
html_option += "<div class='col-md-3'><div class='stambha-img'><img class='img-responsive' src='" + newsImage + "'></div></div>";
});
html_option += "<div>";
$('#catAjax').html(html_option);
} else if(response.status.status == false){
var amount_np = 'hello';
$('#catAjax').html('<div class="container text-center" id="c404"><div class="row"><div class="col-md-6 col-sm-12 offset-md-3 c404"><h5 style="color:#DB4729"><strong>माफ गर्नुहोस्! यस कोटीमा कुनै समाचार छैन।</strong></h5></div></div></div>');
}
}
});
$('.stambha-img').show();
}),
$(".stambha-cat").mouseenter(function() {
$(".stambha-img").show();
});
$(".stambha-cat").mouseleave(function() {
$(".stambha-img").hide();
id = "";
});
});
I want to erase the value of id when the mouseleave event occur so that when I hover to the next item I can get the id of other category.
And, I have the following code inside the list:
<li class="stambha-cat" value="<?php echo $necessary->id ?>"><a class="boldtitle" href="http://<?php echo $necessary->url ?>" target="_blank"><strong><?php echo $necessary->title ?></strong></a></li>
Update: When I hover over another category, I get the same category id. Is that because var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value"); giving the value of first category inside the class "stambha-cat"?
Replacing var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value"); with var id = $(this).attr('value'); worked for me. See the full code below:
$(document).ready(function() {
$('.stambha-img').hide();
$(".stambha-cat").hover(function() {
var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value");
$.ajax({
url: '/ajaxCat.php',
type: 'POST',
data: {
id: id
},
success: function(response){
if (typeof(response) != 'object') {
response = $.parseJSON(response);
}
if (response.status.status == true) {
var html_option = ""
$.each(response.body, function(key, value) {
var newsImage = "";
if(value.image === ""){
newsImage = "<?php echo FRONT_IMAGES_URL.'shikshak.jpg' ?>";
} else {
newsImage = value.image;
}
html_option += "<div class='col-md-3'><div class='stambha-img'><img class='img-responsive' src='" + newsImage + "'></div></div>";
});
html_option += "<div>";
$('#catAjax').html(html_option);
} else if(response.status.status == false){
var amount_np = 'hello';
$('#catAjax').html('<div class="container text-center" id="c404"><div class="row"><div class="col-md-6 col-sm-12 offset-md-3 c404"><h5 style="color:#DB4729"><strong>माफ गर्नुहोस्! यस कोटीमा कुनै समाचार छैन।</strong></h5></div></div></div>');
}
}
});
$('.stambha-img').show();
}),
$(".stambha-cat").mouseenter(function() {
$(".stambha-img").show();
});
$(".stambha-cat").mouseleave(function() {
$(".stambha-img").hide();
id = "";
});
});

How to send selected values with ajax to controller to use as parameters in stored procedure

I am trying to collect selected values from two drop down boxes with multiselect. Then send the data with ajax as strings to a controller to use in stored procedure for a partial view. I can see that the strings are being sent, but the SQL is not running. Can anyone help please, I have trawled everywhere but can't find a similar problem. Thank you.
VIEW
#Html.AntiForgeryToken()
<div class="PropLandingGrid">
<div class="PLAND_A1">
<select name="SuburbDDL" id="SuburbDDL" multiple="multiple"></select>
</div>
<div class="PLAND_A3">
<select name="AreaDDL" id="AreaDDL" multiple="multiple"></select>
</div>
<div class="PLAND_D1"><button type="button" id="btnSearch" class="btn-det15035">Show</button></div>
</div>
<div id="PropContainer"></div>
$(document).ready(function ()
{
var SuburbDDL = $('#SuburbDDL');
var AreaDDL = $('#AreaDDL');
var AreaDet = null;
var AreaQ = null;
var SuburbDet = 1;
var SuburbQ = null;
AreaDDL.multipleSelect();
// suburb
$.ajax({
url: '/tProps/GetSuburbList',
method: 'post',
dataType: 'json',
success: function (data) {
SuburbDDL.append($('<option/>', { value: -1, text: "Select Suburb" }));
$(data).each(function (PropLanding2, item) {
SuburbDDL.append($('<option/>', { value: item.SuburbID, text: item.Suburb }));
});
$('select option:contains("Hout Bay")').prop('selected', true);
SuburbDDL.multipleSelect();
SuburbDet = 1;
}
});
// area
$.ajax({
url: '/tProps/GetAreaListJS',
method: 'post',
data: { SuburbID: '1' },
dataType: 'json',
success: function (data) {
AreaDDL.empty();
AreaDDL.append($('<option/>', { value: -1, text: "Select Area" }));
AreaDDL.attr("disabled", false);
$(data).each(function (PropLanding2, item) {
AreaDDL.append($('<option/>', { value: item.AreaID, text: item.Area }));
});
AreaDDL.multipleSelect();
AreaDet = null;
}
});
SuburbDDL.change(function () {
if ($(this).val() == '-1') {
AreaDDL.empty();
AreaDDL.append($('<option/>', { value: -1, text: "Select Area" }));
AreaDDL.val('-1');
AreaDDL.attr('disabled', true);
}
else {
AreaDDL.attr("disabled", false);
$.ajax({
url: '/tProps/GetAreaListJS',
method: 'post',
data: { SuburbID: $(this).val() },
dataType: 'json',
success: function (data) {
AreaDDL.empty();
AreaDDL.append($('<option/>', { value: -1, text: "Select Area" }));
AreaDDL.attr("disabled", false);
$(data).each(function (PropLanding2, item) {
AreaDDL.append($('<option/>', { value: item.AreaID, text: item.Area }));
});
}
});
SuburbDet = SuburbDDL.multipleSelect('getSelects');
}
});
AreaDDL.change(function ()
{
if ($(this).val() == '-1') {
AreaDet = null;
}
else
{
AreaDet = AreaDDL.multipleSelect('getSelects');
}
});
$("#btnDets").click(function () {
alert("Suburb: " + SuburbDet + ", Area: " + AreaDet)
});
$("#btnSearch").click(function () {
SuburbDet1 = (String(SuburbDet).replace(/,/g, "</SuburbId></Detail><Detail><SuburbId>"));
SuburbDet2 = "<Root><Detail><SuburbId>" + SuburbDet1 + "</SuburbId></Detail></Root>"
console.log(SuburbDet2);
AreaDet1 = (String(AreaDet).replace(/,/g, "</AreaId></Detail><Detail><AreaId>"));
AreaDet2 = "<Root><Detail><AreaId>" + AreaDet1 + "</AreaId></Detail></Root>"
console.log(AreaDet2);
$.ajax({
url: '/tProps/p_PropList2',
contentType: 'application/html',
type: 'GET',
data:
{
'SuburbData': SuburbDet2, 'AreaData': AreaDet2
},
dataType: 'html',
success: function (result) {
$('#PropContainer').html(result);
alert("success");
},
error: function () {
alert("something went wrong");
}
})
});
CONTROLLER
public PartialViewResult p_PropList2(String SuburbData, String AreaData, string sortBy)
{
String StringSQL = "DECLARE #SuburbXML VARCHAR(MAX) DECLARE #AreaXML VARCHAR(MAX) SET #SuburbXML = " + SuburbData + " SET #AreaXML = " + AreaData + " EXEC spPropertyListXML #SuburbXML, #AreaXML";
var datta = db.Database.SqlQuery<spPropertyListXML_Result>(StringSQL).ToList();
return PartialView("p_PropList2", datta.ToList());
}
STORED PROCEDURE
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spPropertyListXML]
#SuburbXML XML -- sd1: defined as xml
, #AreaXML XML -- sd1: defined as xml
AS
BEGIN
SET FMTONLY OFF
SET NOCOUNT ON
BEGIN TRY
-- create temp
CREATE TABLE #TempSuburb (SuburbId INT)
CREATE TABLE #TempArea (AreaId INT)
-- load temp
INSERT INTO #TempSuburb(SUburbId)
SELECT Suburb.ID.query('SuburbId').value('.','INT')
FROM #SuburbXML.nodes('/Root/Detail') AS Suburb(ID)
INSERT INTO #TempArea(AreaId)
SELECT Area.ID.query('AreaId').value('.','INT')
FROM #AreaXML.nodes('/Root/Detail') AS Area(ID)
-- use data in temp
SELECT tArea.Area, tArea.AreaID, tSuburb.SuburbID, tSuburb.Suburb, tProp.Erf, tProp.ErfSq, tProp.Num
FROM tprop
INNER JOIN tArea ON tArea.AreaID = tprop.area
INNER JOIN tSuburb ON tSuburb.SuburbID = tarea.SuburbID
WHERE (NOT EXISTS (SELECT TOP 1 1 FROM #TempSuburb)
OR tSuburb.SuburbID IN (SELECT a.SuburbId FROM #TempSuburb a)
)
AND (NOT EXISTS (SELECT TOP 1 1 FROM #TempArea)
OR tArea.AreaID IN (SELECT a.AreaId FROM #TempArea a)
)
-- drop temp
DROP TABLE #TempSuburb
DROP TABLE #TempArea
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 ROLLBACK TRAN
DECLARE #ERROR_MESSAGE VARCHAR(MAX)
DECLARE #ERROR_SEVERITY INT
SELECT #ERROR_MESSAGE = ERROR_MESSAGE()
, #ERROR_SEVERITY = ERROR_SEVERITY()
RAISERROR(#ERROR_MESSAGE, #ERROR_SEVERITY, 1)
END CATCH
END

how to use cascading dropdownlist in mvc

am using asp.net mvc3, i have 2 tables in that i want to get data from dropdown based on this another dropdown has to perform.for example if i select country it has to show states belonging to that country,am using the following code in the controller.
ViewBag.country= new SelectList(db.country, "ID", "Name", "--Select--");
ViewBag.state= new SelectList("", "stateID", "Name");
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, "-Select-")
#Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state, "-Select-")
but by using this am able to get only the countries.
There is a good jQuery plugin that can help with this...
You don't want to refresh the whole page everytime someone changes the country drop down - an ajax call to simply update the state drop down is far more user-friendly.
Jquery Ajax is the best Option for these kind of questions.
Script Code Is Given below
<script type="text/javascript">
$(function() {
$("##Html.FieldIdFor(model => model.Country)").change(function() {
var selectedItem = $(this).val();
var ddlStates = $("##Html.FieldIdFor(model => model.state)");
$.ajax({
cache:false,
type: "GET",
url: "#(Url.Action("GetStatesByCountryId", "Country"))",
data: "countryId=" ,
success: function (data) {
ddlStates.html('');
$.each(data, function(id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));//Append all states to state dropdown through returned result
});
statesProgress.hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to retrieve states.');
statesProgress.hide();
}
});
});
});
</script>
Controller:
public ActionResult GetStatesByCountryId(string countryId)
{
// This action method gets called via an ajax request
if (String.IsNullOrEmpty(countryId))
throw new ArgumentNullException("countryId");
var country = GetCountryById(Convert.ToInt32(countryId));
var states = country != null ? GetStatesByConutryId(country.Id).ToList() : new List<StateProvince>();//Get all states by countryid
var result = (from s in states
select new { id = s.Id, name = s.Name }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Try this,
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var Id = $("#Country").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { Country: Id },
success: function (listItems) {
var STSelectBox = jQuery('#state');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
View
#Html.DropDownList("Country", (SelectList)ViewBag.country, "--Select--")
#Html.DropDownList("state", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Controller
public JsonResult GetCustomerNameWithId(string Country)
{
int _Country = 0;
int.TryParse(Country, out _Country);
var listItems = GetCustomerNameId(_Country).Select(s => new SelectListItem { Value = s.CountryID.ToString(), Text = s.CountryName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}

Resources