Jquery ajax displays [object Object] - javascript

I basically have 2 drop-down lists and 2 labels.
The first drop-down list is the category selection and the second list loads dynamically the items based on the category.
All is good until now.
At the labels I am trying to display the ItemName and the ItemDescription.
ItemName displays fine but when it comes to ItemDescription for some reason it shows [object Object].
I noticed in console that ItemDescription information is posted correctly, can you please help me find the way to display it correctly?
Jquery:
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").text(this.ItemDescription));
});
}
});
});
</script>
Json:
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId && s.ItemActive == true
select new { Value = s.ItemName, ItemsID = s.ItemId ,ItemDescription = s.ItemDescription };
return Json(data);
}

$("#ItemsID option:selected").text(this.ItemDescription); changes the text and returns the element as an object. You can save the description of each item as data with jquery data() function. Then use it in change event..
try changing to this.
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
options.data('description','');
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
options.data('description',this.ItemDescription);
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").data('description'));
});
}
});
});
</script>

I did some play around and I found the solution :
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
options.data('description', '');
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value).data('ItemDescription', this.ItemDescription));
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").data('ItemDescription'));
});
}
});
});
</script>
Also many thanks to Sampath Liyanage for leading me to the right direction :)

Related

Display one item of my choice rather than the whole list items in ajax upon success

I've got an AJAX code, that does POST reqeusts and displays results upon success. The displayed results are in JSON format and from a different website. The result displays all of the list items, but now I want to display only one item of my choice at the same time, instead of displaying all the items. I've been trying to use the each() and slice() functions, but I think I'm not using them correctly or I don't have any idea of how to deal with the problem. Please help, I'm new to AJAX and JQuery.
This is the code I have:
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
/**The code below will display all the items under a div="product_dispay"*/
jQuery('#product_display').append(jsonData.product_display);
//I want a code that will display one item of my choice at this section.
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
You can access the contents of the #product_display element with jQuery. The API returns HTML data so you can render it in the page, then using jQuery find the data within the HTML and do whatever you want with it.
I have added this code into your original code.
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
This is the final code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {user: user};
jQuery.ajax({
async: false,
url: "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type: "post",
dataType: "jsonp",
jsonp: "jsoncallback",
success: function (jsonData) {
console.log(jsonData);
if (jsonData.product_display !== '') {
jQuery('#product_display').append(jsonData.product_display);
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
} else {
alert(jsonData.error);
}
},
error: function () {
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeIn('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "block");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeOut('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "none");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function () {
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
</body>
</html>
I hope it helps.
This is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {
user: user
};
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
jQuery('#product_display').append(jsonData.product_display);
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeIn('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","block");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeOut('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","none");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
The result displayed upon success is in html format.
jsonData.product_display[i]
has not worked.

Select2 ajax is executed 2 times

I have a script that get's some data from the backend and populates the select2 dropdown. The problem is that the ajax call is called 2 times always and it should not be like this. I am not sure what I am doing wrong... any help would be apreciated.
this is my code:
var select2Element = $('select').select2({
theme: "classic",
escapeMarkup: function (markup) { return markup; },
});
select2Element.on('select2:opening', function(event) {
var clicked = $(this);
var route = "{{ path('get_attribute_list', {'articleId': 'ARTICLEID', 'attributeGroupId': 'ATTRIBUTEGROUPID'}) }}"
var url = route.replace("ARTICLEID", $(this).attr('data-articleId')).replace('ATTRIBUTEGROUPID', $(this).attr("data-attributeGroupId"));
$.ajax ({
url: url,
dataType: 'json',
async: false,
type: "GET",
}).then(function (data) {
//#TODO get out elements already inserted
for (var d = 0; d < data.length; d++)
{
var item = data[d];
// Create the DOM option that is pre-selected by default
var option = new Option(item.text, item.id, true, true);
// Append it to the select
clicked.append(option);
}
// Update the selected options that are displayed
clicked.trigger('change');
});
});
var inputResult = [];
select2Element.on('select2:select', function(e) {
var jsonValue = {
"articleId": $(this).attr("data-articleId"),
"attributeGroupId": $(this).attr("data-attributeGroupId"),
"attributeId": e.params.data.id
}
inputResult.push(jsonValue);
$('#addAttributes').val(JSON.stringify(inputResult));
});
select2Element.on('select2:close', function() {
$(this).html('');
});
Seems there is a bug in 'select2:open' and 'select2:opening'. There is a fix for this but not published.
Anyway who has this problem until it is fixed can see more details here:
https://github.com/select2/select2/issues/3503
and the fix for this here:
https://github.com/select2/select2/commit/c5a54ed70644598529a4071672cca4a22b148806

How can I pass the value and corresponding name of a checkbox when checked using javascript in ASP.NET?

I'm very new to ajax/javascript so I will try my best to explain my problem. Here's what I have so far:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).val());
console.log($(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default.aspx",
type: "post",
dataType: "json",
data: { UpdateQuery: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
Every time a checkbox is checked, ajax passes the data onto the server. Here is an example of some checkbox values after a few have been checked in the data form obtained from the Developer's Console:
You can try the following code:
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());

Getting error on remove var data

I'm making hover card on click for every users so i did for one and its working but i want this to work on every user like i have given them unique title and based on that the server will get the data of that particular users but the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong) so i tried to do this on ajax cache: false but didn't help then i tried return false;, return data; still not use.
So, here is the users links example :
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
Ajax :
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
var data = 'vall=' + get_val + '';
$.ajax({
type: 'POST',
url: 'xx.php',
data: data,
success: function (data) {
box.dialog({
message: data
});
return false;
}
});
});
});
I would do it this way.
HTML
<div class='links'>
<a title="user101" href="#">John</a>
<a title="user102" href="#">Tonya</a>
</div>
JS
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.links').on('click', 'a', function (event) {
event.preventDefault();
var get_val = $(this).prop('title');
$.ajax({
type: 'POST',
url: 'xx.php',
data: {vall: get_val},
success: function (data) {
box.dialog({
message: data
});
}
});
});
});
the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong)
you are wrong.. only 1 links is working beacuse you have same id for multiple elements.. each elements should have unique id.
use class instead
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
and a class selector and return false after ajax success callback function , at the end
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
....
$.ajax({
....
success:function(){
....
}
});
return false;
..
or simply use preventDefault() instead of return false
$('.hover').click(function (e) {
e.preventDefault();
var get_val = $('.hover').attr('title');
.....

ASP.NET MVC - Javascript array always passed to controller as null

I'm having some problem with passing a javascript array to the controller. I have several checkboxes on my View, when a checkbox is checked, its ID will be saved to an array and then I need to use that array in the controller. Here are the code:
VIEW:
<script type="text/javascript">
var selectedSearchUsers = new Array();
$(document).ready(function () {
$("#userSearch").click(function () {
selectedSearchUsers.length = 0;
ShowLoading();
$.ajax({
type: "POST",
url: '/manage/searchusers',
dataType: "json",
data: $("#userSearchForm").serialize(),
success: function (result) { UserSearchSuccess(result); },
cache: false,
complete: function () { HideLoading(); }
});
});
$(".userSearchOption").live("change", function () {
var box = $(this);
var id = box.attr("dataId");
var checked = box.attr("checked");
if (checked) {
selectedSearchUsers.push(id);
}
else {
selectedSearchUsers.splice(selectedSearchUsers.indexOf(id), 1);
}
});
$("#Send").click(function () {
var postUserIDs = { values: selectedSearchUsers };
ShowLoading();
$.post("/Manage/ComposeMessage",
postUserIDs,
function (data) { }, "json");
});
});
</script>
When the "Send" button is clicked, I want to pass the selectedSearchUsers to the "ComposeMessage" action. Here is the Action code:
public JsonResult ComposeMessage(List<String> values)
{
//int count = selectedSearchUsers.Length;
string count = values.Count.ToString();
return Json(count);
}
However, the List values is always null. Any idea why?
Thank you very much.
You might try changing the controller's action method to this:
[HttpPost]
public JsonResult ComposeMessage(string values)
{
JavaScriptSerializer jass = new JavaScriptSerializer;
AnyClass myobj = jass.Deserialize<AnyClass>((string)values);
...
...
}
I believe that you have to take the JSON data in as a string and do the conversion
manually. Hope it helps. Cheers.

Categories