View Script
function AddToBag()
{
var url = "/Home/Populate_Entitle/";
$.ajax({
url: url,
data: { id: 1 },
cache: false,
type: "POST",
success: function (data) {
alert("hi");
$("#gridContent").html(markup);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
Controller Functions
public ActionResult Populate_Entitle(int id)
{
if (dtEntitle.Columns.Count == 0)
{
dtEntitle.Columns.Add("sno");
dtEntitle.Columns.Add("Sport");
dtEntitle.Columns.Add("Event");
dtEntitle.Columns.Add("SubEvent");
dtEntitle.Columns.Add("Classification");
dtEntitle.Columns.Add("Entitlement");
dtEntitle.Columns.Add("Channel");
dtEntitle.Columns.Add("Brand");
dtEntitle.Columns.Add("product");
dtEntitle.Columns.Add("Unit");
dtEntitle.Columns.Add("TotalSpots");
dtEntitle.Columns.Add("TotalNetRevenue");
dtEntitle.Columns.Add("remark");
dtEntitle.Columns.Add("Sport_id");
dtEntitle.Columns.Add("Event_id");
dtEntitle.Columns.Add("SubEvent_id");
dtEntitle.Columns.Add("channel_id");
dtEntitle.Columns.Add("brand_id");
dtEntitle.Columns.Add("product_id");
dtEntitle.Columns.Add("Effective_Rate");
dtEntitle.Columns.Add("Base_Rate");
}
DataRow dr = dtEntitle.NewRow();
dr["sno"] = 1;
dr["Sport"] = "Cricket";
dr["Event"] = "IND vs BANGLADESH";
dr["SubEvent"] = "1st Day 18-JUN-2015,2nd Day 20-JUN-2015";
dr["Classification"] = "LIVE";
dr["Entitlement"] = "Spot Buys";
dr["Channel"] = "SS1,SS2";
dr["Brand"] = "Brand 1";
dr["product"] = "Product 1";
dr["Unit"] = "Spots";
dr["TotalSpots"] = 10;
dr["TotalNetRevenue"] = 200 ;
dr["remark"] = "-";
dr["Sport_id"] = 1;
dr["Event_id"] = 1;
dr["channel_id"] = 1;
dr["brand_id"] = 1;
dr["product_id"] = 1;
dr["Effective_Rate"] = 100;
dr["Base_Rate"] = 100;
dtEntitle.Rows.Add(dr);
List<Sports_Deal.Models.Entitlements> lmdEntitle = new List<Sports_Deal.Models.Entitlements>();
foreach (DataRow dr1 in dtEntitle.Rows) // loop for adding add from dataset to list<modeldata>
{
lmdEntitle.Add(new Sports_Deal.Models.Entitlements
{
Event = dr1["Event"].ToString(),
Base_Rate = Convert.ToInt32(dr1["Base_rate"]),
brand_id = Convert.ToInt32(dr1["brand_id"]),
Brand = dr1["brand"].ToString(),
Channel = dr1["Channel"].ToString(),
Sport = dr1["Sport"].ToString(),
Effective_Rate = Convert.ToInt32(dr1["Effective_Rate"]),
channel_id =(dr1["channel_id"]).ToString(),
Quality = (dr1["channel_id"]).ToString(),
Classification = dr1["Classification"].ToString(),
Entitlement = dr1["Entitlement"].ToString(),
Event_id = Convert.ToInt32(dr1["Event_id"]),
product_id = Convert.ToInt32(dr1["Product_id"]),
remark = dr1["remark"].ToString(),
sno = Convert.ToInt32(dr1["sno"]),
Sport_id = Convert.ToInt32(dr1["Sport_id"]),
SubEvent = dr1["SubEvent"].ToString(),
SubEvent_id = dr1["SubEvent_id"].ToString (),
TotalNetRevenue = Convert.ToInt32( dr1["TotalNetRevenue"]),
TotalSpots = Convert.ToInt32(dr1["TotalSpots"]),
Unit = dr1["Unit"].ToString()
});
}
return PartialView("markup", lmdEntitle);
}
}
I need to populate Web grid dybamically when controller method returns list.
Replace your markup with the Data
function AddToBag() {
var url = "/Home/Populate_Entitle/";
$.ajax({
url: url,
data: { id: 1 },
cache: false,
type: "POST",
success: function (data) {
alert("hi");
$("#gridContent").html(data);
},
error: function (reponse) {
alert("error : " + Json.stringify(reponse));
}
});
}
You are getting data in response, markup is undefined for this criteria
Related
When 5 cards are created for the 5-day weather forecast, the icon, temp, and humidity data are correct, but the date stays the same on all five cards. Any idea why? Thank you!
UPDATE: I added "if-sentence" realizing that the data I get is for every few hours so that`s the reason my cards all have the same date. This syntax seems logical to me, but it ends up giving me only one card. I hope someone can spot the error in my code. Thank you.
$(document).ready(function() {
$("#submit").on("click", function() {
var userInput = $("#user-input").val();
fiveDayForecast(userInput);
});
var key = 'my API key';
var url = "https://api.openweathermap.org/data/2.5/forecast";
function fiveDayForecast(userInput) {
$.ajax({
url: url,
dataType: "json",
type: "GET",
data: {
q: userInput,
appid: key,
units: "imperial",
cnt: "5"
},
success: function(data) {
$("#five-day-forecast").empty();
for (var i = 0; i < data.list.length; i++) {
if(data.list[i].dt_txt.indexOf("15:00:00") !== -1) {
var colEl = $("<div>").addClass("col col-lg-2");
var cardEl = $("<div>").addClass("card text-white bg-primary m-3");
var cardBody = $("<div>").addClass("card-body");
var cardTitle = $("<h5>").addClass("card-title").text(new Date(data.list[i].dt_txt).toLocaleDateString());
var img = $("<img>").attr("src", "http://openweathermap.org/img/w/" + data.list[i].weather[0].icon + ".png");
var cardText1 = $("<p>").addClass("card-text").text("Temp: " + data.list[i].main.temp_max + " °F");
var cardText2 = $("<p>").addClass("card-text").text("Humidity: " + data.list[i].main.humidity + "%");
colEl.append(cardEl.append(cardBody.append(cardTitle, img, cardText1, cardText2)));
$("#five-day-forecast").append(cardEl);
}
}
}
})
}
});
Sample data:
"list":[
{ "dt":1595840400, "main":{}, "weather":[], "clouds":{}, "wind":{}, "visibility":10000, "pop":0.66, "rain":{},
"sys":{}, "dt_txt":"2020-07-27 09:00:00"
},
...
]
I have a function which makes an AJAX call and depending on the answer, sets the colour of an input. The function core itself works fine. However, when it comes to changing the colour of the input, it is not working.
function Nueva_Red() {
var e1 = document.getElementById("rrss_tipo");
var e2 = document.getElementById("rrss_usuario");
var e3 = document.getElementById("redes");
var e4 = document.getElementById("alta_nueva_red");
var id_red = e1.options[e1.selectedIndex].value;
var red = e1.options[e1.selectedIndex].text;
var usuario = e2.value;
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
if ((id_red > 0) && (usuario != "")) {
var datastr = 'seccion=rrss_check&dato=' + id_red + "|" + usuario;
$.ajax({
type: 'GET',
url: 'validacion.php',
data: datastr,
success: function(html) {
if (html == 1) {
document.getElementById("nuevas_rrss").style.visibility = "visible";
document.getElementById("nuevas_rrss").style.display = "inline-block";
var opcion = document.createElement("option");
opcion.value = id_red + "-" + usuario;
opcion.innerHTML = red + " -> " + usuario;
e3.appendChild(opcion);
e1.value = 0;
e2.value = "";
e2.title = "";
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
} else {
e2.title = html;
e2.style.backgroundColor = error_error;
e2.style.borderColor = error_error;
}
},
error: function(html) {
e2.style.borderColor = error_app;
e2.style.backgroundColor = error_app;
}
});
}
}
Thank you!
In asp.net webform i am trying to call data using ajax call. I have similar function of other page which works fine but on this page i am getting error.
I am getting pageCountInt as NaN
<div id="loadmore" class="loadmore-w"><p id="loadmore-btn" >Load more</p></div>
Table has about 6 records and it loads the first 2 records and when i cluck on the load more button it doesnt load any more data and show pageCountInt as NaN
var pageIndexInt = 0;
var pageCountInt = 0;
GetInterviewRecords();
$('#loadmore-btn').click(function() {
// console.log("button clicked");
GetInterviewRecords();
});
function GetInterviewRecords() {
//console.log("i am in GetInterviewRecords function");
pageIndexInt++;
console.log("pageIndexInt " + pageIndexInt);
console.log("pageCountInt " + pageCountInt);
if (pageIndexInt == 1 || pageIndexInt <= pageCountInt) {
$("#loading-interview").show();
$.ajax({
type: "POST",
url: "<%= ResolveUrl ("~/en/Default.aspx/GetInterviews ") %>",
data: '{pageIndex: ' + pageIndexInt + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessInterview,
failure: function(response) {
alert(response.d);
},
error: function(response) {
alert(response.d);
}
});
}
}
function OnSuccessInterview(response) {
// console.log("i am in OnSuccessInterview function");
var xmlDocInterview = $.parseXML(response.d);
console.log("Interview XML ----");
//console.dirxml(xmlDocInterview);
//console.dir(xmlDocInterview);
var xmlInterview = $(xmlDocInterview);
pageCountInt = parseInt(xmlInterview.find("pageCount").eq(0).find("pageCount").text());
var interview = xmlInterview.find("Table");
interview.each(function() {
var articleItem = $(this);
var aImagePath = '<%= ResolveUrl ("http://website.com/images/Interview/")%>' + articleItem.find("PageImage").text();
var aTitle = articleItem.find("Heading").text();
var aURL = 'http://website.com/interview/' + aID + "/" + aTitle;
$('<div class="tab-item-wrapper"><img src="' + aImagePath + '" class="tab-i-a-img"><span class="tab-i-a-title">' + aTitle + '</span></div>').appendTo(".wrapper");
});
if (pageIndexInt >= pageCountInt) {
$("#loadmore").hide();
}
}
C# Function
public static DataSet GetInterviewListByLangID(int LangID, int PageIndex, int PageSize)
{
DataSet ds = null; int PageCount = 0;
try
{
SqlParameter[] sqlparam = new SqlParameter[4];
sqlparam[0] = new SqlParameter("#LangID", LangID);
sqlparam[1] = new SqlParameter("#PageIndex", PageIndex);
sqlparam[2] = new SqlParameter("#PageSize", PageSize);
sqlparam[3] = new SqlParameter("#PageCount", PageCount);
sqlparam[3].Direction = ParameterDirection.Output;
ds = SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, "usp_GetInterviewListwise", sqlparam);
DataTable dt = new DataTable("PageCount");
dt.Columns.Add("PageCount");
dt.Rows.Add();
int TotalPageCount = 0;
if (!String.IsNullOrEmpty(sqlparam[3].Value.ToString()))
{
TotalPageCount = (int)sqlparam[3].Value;
}
dt.Rows[0][0] = TotalPageCount;
ds.Tables.Add(dt);
}
catch (Exception ex)
{
//HttpContext.Current.Response.Redirect("Message.aspx?msg=Invalid Request");
}
return ds;
}
[WebMethod]
public static string GetInterviews(int pageIndex)
{
// System.Threading.Thread.Sleep(1000);
return GetInterviewListByLangID(1, pageIndex, 2).GetXml();
}
SQL SERVER SP
ALTER PROCEDURE [dbo].[usp_GetInterviewListwise]
#LangID int
,#PageIndex INT = 1
,#PageSize INT = 6
,#PageCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [PublishDate] DESC
)AS RowNumber
,[InterviewID] AS ID
,[Title] As Heading
,[Description] AS Brief
,REPLACE(CONVERT(CHAR(10), [PublishDate], 103), '/', '-') AS ReleaseDate
,[Image] AS PageImage
,[VideoID] AS VideoID
INTO #Results
FROM Interview WHERE Visible = 1 AND Active = 1 AND LanguageID = #LangID
AND InterviewID NOT IN (SELECT TOP 1 InterviewID FROM Interview WHERE LanguageID=#LangID AND Active=1 AND Visible = 1 Order by PublishDate DESC)
DECLARE #RecordCount INT
SELECT #RecordCount = COUNT(*) FROM #Results
SET #PageCount = CEILING(CAST(#RecordCount AS DECIMAL(10, 2)) / CAST(#PageSize AS DECIMAL(10, 2)))
PRINT #PageCount
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
How i can improve this code and convert this into json or fix the same where i work with XML. I am not sure why pageCountInt value is NaN and i am finding it even more hard to debug it also.
I solved the issue as i was using PageCount as pageCount in the following lien of code
pageCountInt = parseInt(xmlInterview.find("PageCount").eq(0).find("PageCount").text());
Just wasted 4 hours figuring out what could be the issue. CaSe SeNsiTiVe OHHHH!!!
I have a problem with my page. It works on localhost (WebServ). On my vps (Debian 8) it not work.
You can look: http://www.csgobeton.pl/withdraw.
When you do recaptcha it says "syntax error unexpected end of input".
In the console I can see there is a problem at line "data = JSON.parse(data);".
Please help me.
function loadLeft(opts) {
inlineAlert("", "Loading your inventory - please wait...");
var DIV = "<div class='placeholder matched' data-name='{0}' data-pos='{1}'
data - price = '{2}'
data - bot = '{3}' > ";
DIV += "<div class='slot {13}' data-view='{15}' data-name='{4}' data-
pos = '{5}'
data - price = '{6}'
data - bot = '{7}'
data - id = '{8}'
style = 'background-
image: url(\"{9}\")'>"; DIV += "<div class='name'>{10}</div>"; DIV +=
"<div class='price {11}'>{12}</div>"; DIV +=
"<div class='bot'>{14}</div>"; DIV += "</div></div>";
var IMG = "{0}/{1}fx{2}f";
var url = "";
if (DEPOSIT) {
url = "/get_inv?" + opts;
} else {
var g = grecaptcha.getResponse();
url = "http://www.csgobeton.pl/get_bank_safe?g-recaptcha-response=" + g;
}
$.ajax({
url: url,
success: function (data) {
$("#inlineAlert").html("data");
try {
data = JSON.parse(data);
if (data.success) {
console.log(data);
$("#left .reals").empty();
$("#right .reals").empty();
$("#right .bricks").removeClass("hidden");
$("#avail").html(formatNum(data.balance));
var count = data.items.length;
var eleA = [];
for (var i = 0; i < count; i++) {
var item = data.items[i];
var url = IMG.format(item.img, 110, 50);
var price_class = "ball-1";
if (DEPOSIT) {
price_class = "ball-0";
}
var slot_class = "";
var price_content = item.price;
if (price_content == 0) {
price_content = item.reject;
slot_class = "reject";
} else {
price_content = formatNum(price_content);
}
bot = 0;
if (item.botid) {
bot = item.botid;
}
var botLabel = "";
if (!DEPOSIT) {
botLabel = "Bot " + bot;
}
var ele = DIV.format(item.name, i, item.price, bot,
item.name, i, item.price, bot, item.assetid, url, item.name,
price_class,
price_content, slot_class, botLabel, item.view);
eleA.push(ele);
}
$("#left_number").html(count);
document.getElementById("left").getElementsByClassName(
"reals")[0].innerHTML = eleA.join('');
addPadding("#left", 6);
if (data.fromcache) {
inlineAlert("success", "Loaded " + count + " items from
cache - < a href = \
"javascript:loadLeft('nocache')\">reload inventory</a>"
);
} else {
inlineAlert("success", "Loaded " + count + " items.");
}
} else {
inlineAlert("error", data.error);
if (data.count > 0) {
cmd();
}
}
if (data.tid) {
showPending(data);
}
} catch (err) {
inlineAlert("error", "Javascript error22: " + err);
console.log(err.stack);
}
},
error: function (err) {
inlineAlert("error", "AJAX error: " + err.statusText);
},
});
}
index.php is:
case 'get_bank_safe':
if(!$user) exit(json_encode(array('success'=>false, 'error'=>'You must
login to access the widthdraw.')));
$g = curl('https://www.google.com/recaptcha/api/siteverify?secret=6Le-
6R8TAAAAAAjgt_wfQMOUCMxCCAWs-iFlP9T-&response='.$_GET['g-recaptcha-response']);
$g = json_decode($g, true);
if($g['success'] == true) {
$array =array('balance'=>$user['balance'],'error'=>'none','items'=>array(),'success'=>true);
mysql_query('SET CHARACTER SET utf8');
$sql = $db->query('SELECT * FROM `items` WHERE `status` = 1');
$prices = file_get_contents('prices.txt');
$prices = json_decode($prices, true);
while ($row = $sql->fetch()) {
$array['items'][] =
array('botid'=>$row['botid'],'img'=>'http://steamcommunity-a.akamaihd.net/economy/image/'.$row['img'],'name'=>$row['market_hash_name'],'ass
etid'=>$row['id'],'price'=>$prices['response']['items']
[$row['market_hash_name']]['value']*10,'reject'=>'unknown items');
}
exit(json_encode($array));
}
break;
The result of get_safe_bank is:
{"balance":"0","error":"none","items": [{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFAuhqSaKWtEu43mxtbbk6b1a77Twm4Iu8Yl3bCU9Imii1Xt80M5MmD7JZjVLFH-6VnQJQ","name":"Chroma 2 Case","assetid":"8","price":0,"reject":"unknown items"},{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoo6m1FBRp3_bGcjhQ09ulq5WYh8jiPLfFl2xU18h0juDU-MKljgLjqRVuaj-gLIKUdQdtMgvS-VK_wrvpgZ7quM_Im3Qw6Cdz4CzZgVXp1o7eGVz_","name":"USP-S | Lead Conduit (Well-Worn)","assetid":"26","price":0,"reject":"unknown items"}],"success":true}{"balance":"0","error":"none","items":[{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFAuhqSaKWtEu43mxtbbk6b1a77Twm4Iu8Yl3bCU9Imii1Xt80M5MmD7JZjVLFH-6VnQJQ","name":"Chroma 2 Case","assetid":"8","price":0,"reject":"unknown items"},{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoo6m1FBRp3_bGcjhQ09ulq5WYh8jiPLfFl2xU18h0juDU-MKljgLjqRVuaj-gLIKUdQdtMgvS-VK_wrvpgZ7quM_Im3Qw6Cdz4CzZgVXp1o7eGVz_","name":"USP-S | Lead Conduit (Well-Worn)","assetid":"26","price":0,"reject":"unknown items"}],"success":true}
When I paste it instead data = JSON.parse(data); data it works correctly.
I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>