Json not work in asp.net mvc - javascript

I wanna to use this json to my sites shopping cart .it works well in visual studio 2017 but in visual studio 2013 it does not work. please help me to solve it.
function AddtoCart() {
$.ajax({
url: '/Home/AddToCart',
type: 'POST',
dataType: 'Json',
data: {
ProductID: #Model.product.id,
count: My_Count.value
},
error: function(err) {
alert(err.status);
}
}).done(function(data) {
$('#Total_Cost').text(data.Total_Price)
var Text = "";
$.each(data.lst_ShoppingCart, function(index, val) {
Text += "<tr><td class='col-sm-8 col-md-6' ><span id='Product_Name'>" + val.Product_Name + "</span></td ><td class='col-sm-1 col-md-1' style='text-align: center'><input type='text' class='form-control' id='exampleInputEmail1' value='" + val.Count + "'></td><td class='col-sm-1 col-md-1 text-center'><span id='Product_Cost'>" + val.Single_Price + "</span></td><td class='col-sm-1 col-md-1 text-center'><span id='Total_ProCost'>" + val.Price + "</span></td><td class='col-sm-1 col-md-1'><button type='button' onclick='RemoveCart(" + val.ID + ")' class='btn btn-danger'>Remove</button></td></tr>";
})
$('#Pro_Cart').html(Text);
});
}
also I know that this part of code not working:
url: '/Home/AddToCart',
type: 'POST',
dataType: 'Json',
data: {
ProductID: #Model.product.id,
count: My_Count.value
},

Related

jQuery - Getting Correct UserID - AJAX

so I am at a bit of a bind here. So I have 2 jQuery scripts that handle a simple database row update (per the user ID, session), this lets the user send a "Gift" that adds value to the users database row column "bonus".
I got this working practically perfect, but the problem is: It will only get the first ID of the results when gifting, not any other user ID. I suspect this is a fault in the looping logic.
RequestBin tells me I have my correct ID for myself, and the user ID is stuck with the first iterated userid (we cant send to any other user ID). We need to be able to gift any result (user ID).
We use a dialog to trigger the AJAX call with Yes / No. Yes firing the AJAX event, no closing model.
The AJAX JS - Sends value to database
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function () {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
var sender = $('input[name=sender]').val();
var receiver = $('input[name=receiver]').val();
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function () {
$('#gift-bonus-status').text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function (response) {
$('#gift-bonus-status').text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function () {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
function fetchTopTransfers() {
$(function () {});
$.ajax({
url: '/ajax/ajax_user_list.php',
method: 'GET',
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
$('input[name=receiver]').val(item.user_id);
html_to_append +=
'<div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
formatBytesProduct(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\')" id="gift-bonus-status">Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div></div><div style="clear:both"></div><input type="hidden" name="sender" value="<?=$account->getId()?>" /><input type="hidden" name="receiver" value="' +
item.user_id + '" />';
});
$("#top-transfers").html(html_to_append);
}
});
}
fetchTopTransfers();
setInterval(function () {
fetchTopTransfers()
}, 5000);
AJAX responce:
What is happening here???
Any help is much appreciated
As there many inputs with name receiver that's why you are not able to pass correct values. So, inside your ConfirmDialog function pass this as well it will refer to current element which is clicked. Then , inside your function to get required values you can use $(this).closest(".outer").find(..)...
Demo Code :
//just for demo..
var data = [{
"user_id": 1,
"product_id": 12,
"username": "acc",
"name": "swi",
"progress": "20",
"speed": 15
}, {
"user_id": 2,
"product_id": 12,
"username": "acc",
"name": "swi22",
"progress": "10",
"speed": 12
}]
var html_to_append = "";
$.each(data, function(i, item) {
//give outer div.. also pass `this` inside your function
html_to_append +=
'<div class="outer"><div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\',this)" >Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div><div style="clear:both"></div><input type="hidden" name="sender" value="23" /><input type="text" name="receiver" value="' +
item.user_id + '" /></div>';
});
$("#top-transfers").html(html_to_append);
//add el it refer to `this`
function ConfirmDialog(message, el) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function() {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
//get closest div(outer) then find required inputs values
var sender = $(el).closest(".outer").find('input[name=sender]').val();
var receiver = $(el).closest(".outer").find('input[name=receiver]').val();
console.log("Reciver --" + receiver + " Sender ---" + sender)
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function() {
//use el here as well..
$(el).text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function(response) {
//use el here as well
$(el).text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function() {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<div id="top-transfers">
</div>

How to set response data to javascript code

How to set response data
$.ajax({
type : "POST",
async: true,
url : "<?php echo base_url(); ?>" + "Graphs/get_graphs",
dataType: 'json',
data :{hotel_name_realm:$("#hotel_names").val()},
success : function(res){
obj = JSON.parse(res);
console.log(obj.upload);
console.log(obj.download);
series: [{
name: 'Download',
data: [
(obj.Download) // I need set obj.download data here
]
}
}
Here is my console.log(obj) image
i do like this,
$.ajax({
method: "POST",
url: "chat/searchuser",
data: {name: $(this).val(), length: "10"}
})
.done(function (data) {
$('#scroll_user').val('10');
var html = '';
$.each(JSON.parse(data).data, function (k, v) {
html += '<div class="row sideBar-body getUserdata userchat" data-username="' + v.fname + '" data-id="<?php echo $key; ?>" onclick="showDiv()" id="' + v.fname + '"><div class="col-sm-3 col-xs-3 sideBar-avatar"><div class="avatar-icon"><img src="<?= base_url('assets/user2.jpg') ?>"></div></div><div class="col-sm-9 col-xs-9 sideBar-main"><div class="row"><div class="col-sm-12 col-xs-12 sideBar-name" data-username="' + v.fname + '"><span class="name-meta">' + v.fname + ' ' + v.lname + '(' + v.username + ')</span></div></div></div></div>'
$('#usersindiv').html(html);
});
}).fail(function () {
alert("failed");
});
You are doing it right, you just missed the right square bracket. JS is also case sensitive, obj.Download is not obj.download
$.ajax({
type : "POST",
async: true,
url : "<?php echo base_url(); ?>" + "Graphs/get_graphs",
dataType: 'json',
data :{hotel_name_realm:$("#hotel_names").val()},
success : function(res){
obj = JSON.parse(res);
console.log(obj.upload);
console.log(obj.download);
series: [{
name: 'Download',
data: [
(obj.Download) // shouldn' it be obj.download? (small D)
]
] // you are missing the right bracket here
}
}

select2 ajax not working

I'm working with select2 library to make a dropdown using ajax. I cant make it work. Here is my code:
$("#guests").select2({
multiple: true,
minimumInputLength: 1,
formatInputTooShort: function () {
return "Enter 1 Character";
},
data: function() {
return data;
},
ajax: {
url: 'some url',
dataType: 'json',
processResults: function (data) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
return {
results: data.data,
pagination: {
more: 30
}
}
}
/*,
cache: true*/
},
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
})
function formatRepo (results) {
var markup = "<div class='select2-result-resultssitory clearfix'>" +
"<div class='select2-result-resultssitory__avatar'><img src='" + results.id + "' /></div>" +
"<div class='select2-result-resultssitory__meta'>" +
"<div class='select2-result-resultssitory__title'>" + results.text + "</div>";
if (results.description) {
markup += "<div class='select2-result-resultssitory__description'>" + results.guest_first_name + "</div>";
}
markup += "<div class='select2-result-resultssitory__statistics'>" +
"<div class='select2-result-resultssitory__forks'><i class='fa fa-flash'></i> " + results.guest_last_name + " Forks</div>" +
"<div class='select2-result-resultssitory__stargazers'><i class='fa fa-star'></i> " + results.guest_do_b + " Stars</div>" +
"<div class='select2-result-resultssitory__watchers'><i class='fa fa-eye'></i> " + results.text + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatRepoSelection(results) {
return results.text || results.guest_first_name;
}
html:
<select id="guests" class="form-control input-guests " data-placeholder="Search guest..." multiple=""></select>
here is the JOSN data i'm getting from remote url:
[{
"id": 1,
"guest_first_name": "Jon",
"guest_last_name": "Doe",
"guest_do_b": "1954-07-13T00:00:00+0100",
"text": "Jon Doe"
}, {
"id": 2,
"guest_first_name": "Janne",
"guest_last_name": "Doe",
"guest_do_b": "1960-01-14T00:00:00+0100",
"text": "Janne Doe"
}]
A bit late, but was your error that options.results is undefined?
If that's the case, then you may want to rename the function processResults to results
I know it's in the docs with the processResults function, but I had the same problem and this article had the solution for me.

Javascript Won't Work On Duplicated Row [duplicate]

I'm having an issue using jQuery autocomplete with dynamically created inputs (again created with jQuery). I can't get autocomplete to bind to the new inputs.
Autocomplete
$("#description").autocomplete({
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
});
New table row with inputs
var i = 1;
var $table = $("#works");
var $tableBody = $("tbody",$table);
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" id="description" name="item[' + i + '][works_description]" /></td></tr>');
$tableBody.append(newtr);
i++;
});
I'm aware that the problem is due to the content being created after the page has been loaded but I can't figure out how to get around it. I've read several related questions and come across the jQuery live method but I'm still in a jam!
Any advice?
First you'll want to store the options for .autocomplete() like :
var autocomp_opt={
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
};
It's more neat to use the class attribute for marking the input, like:
<input type="text" class="description" name="item[' + i + '][works_description]" />
Last, when you create a new table row apply the .autocomplete() with the options already stored in autocomp_opt:
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" class="description" name="item[' + i + '][works_description]" /></td></tr>');
$('.description', newtr).autocomplete(autocomp_opt);
$tableBody.append(newtr);
i++;
});
I found that I needed to put teh autocomplete after the append so:
$tableBody.append(newtr);
$('.description', newtr).autocomplete(autocomp_opt);

Using ng-repeat to show json data fetched from database

I have implemented a process to show my data from database in a #showdata div with the following method.
function UserCntrl($scope) {
getUser();
$scope.save = function () {
$.ajax({
type: "POST",
url: "UserService.asmx/InsertUser",
data: "{'Username':'" + $scope.Name + "','Email':'" + $scope.Mail + "','Password':'" + $scope.Password + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
$("#showdata").append("Username: " + $scope.Name + "<br />" + "Email:" + $scope.Mail + "<br />");
},
error: function (msg) {
alert(msg.d);
}
});
};
function getUser() {
$.ajax({
type: "POST",
url: "UserService.asmx/GetUserDetails",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = $.parseJSON(data.d);
$.each(parsed, function (i, jsondata) {
$("#showdata").append("Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />");
});
},
error: function (XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
alert(errorMessage);
}
});
};
}
Everything working just fine and all data showing properly in #showdata div. But now I want to do the same thing but by using the ng-repeat directive.
How can I achieve this?
as RGraham said, it's not the "angular way" to work with HTTP request but as a starting point, here's a working example:
js:
function EntryCtrl ($scope, $http) {
$scope.rootEntry = [];
$http.get('https://api.github.com/users/mralexgray/repos').success(function(root) {
$scope.rootEntry = root;
});
}
html:
<div ng-controller="EntryCtrl">
<ul>
<li ng-repeat="root in rootEntry">{{root.name}}</li>
</ul>
</div>
Live example: http://plnkr.co/edit/Grlgfob6tjE63JizWdCD?p=preview
$scope.data = object
<tr ng-repeat="(key, value) in data">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
Assuming 'parsed' is in your controller's $scope property
<div id="showdata">
<div ng-repeat="(i, jsondata) in parsed" >{{"Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />"}}</div>
</div>

Categories