URL Name not resolved in Jquery - javascript

I am trying to dynamically build up HTML using JQuery in ASP.NET MVC5. I have so far had success, but the URL cannot be resolved in the JQuery Code.
My code looks something like this:
$.ajax({
type: 'POST',
url: '#Url.Action("QuerySearch")',
dataType: 'json',
data: {
queryName: $("#queryText").val()
},
success: function (data) {
// var items = '';
$.each(data, function (i, item) {
var resource_Url = item.ResourceURL;
// var resource_url = item.ResourceURL;
var append_data = $('<div class="row">'
+ '<h3>' + item.ResourceTitle + '</h3>'
+ '</div>'
+ '<div class="row">'
+ '<span class="label label-primary" style="margin:3px;font-size:small;">'
+ item.ResourceEducation
+ '</span>'
+ '<span class="label label-warning" style="margin:3px;font-size:small;">'
+ item.ResourceGrades
+ '</span>'
+ '<span class="label label-info" style="margin:3px;font-size:small;">'
+ item.ResourceSubject
+ '</span>'
+ '<a href="#Url.Content("' + item.ResourceURL + '")">'
+ '<img src="#Url.Content("~/Content/Resources/download_icon.png")" alt="Download Resource" style="height:24px;width:24px;"/>'
+ '</a>'
Although this code is able to retrieve the image for the download_icon defined in my project, it is not able to display / embed the URL fetched from the server by my function which I am trying to display in the <a href> tag.
Any help is greatly appreciated.

You will need to pass the complete url value from the server as a property of the data received. Or have it stored locally
ASP code doesn't run in the browser, only on server

The trick was simple, the href tag had to be changed to:
'<a href="' + item.ResourceURL + '">'
It worked like a charm

Related

hyperlink on update button (ajax json)

It's my first time using json and I'm trying to make an update button on a table that i make with ajax json, there is a problem that i can't put id_news attribute on the tag along with the target link. I tried put it next to the target link, but it doesn't work, and even the tables doesn't show anything, is there any way to make it work?
$(document).ready(function() {
display_data_info();
function display_data_info() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url()?>/information/data_read_info',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var no;
var id_news;
for (i = 0; i < data.length; i++) {
no = +1;
html += '<tr>' +
'<td>' +
no +
'</td>' +
'<td>' +
data[i].news_title +
'</td>' +
'<td>' +
data[i].news_info +
'</td>' +
'<td>' +
data[i].news_status +
'</td>' +
'<td><a href="<?php echo site_url("information/display_update_info/".data[i].id_news); ?>" class="btn btn-app">' +
'<i class="fas fa-edit"></i> ' +
'</a>' +
'</td>' +
'</tr>';
}
$('#show_data_info').html(html);
}
});
}
});
[wanted to post just a comment, but haven't enough reputation yet. Perhaps a moderator can change my feedback into a comment?]
I see multiple typos and mistakes here:
In the first php part, put a ; after base_url()
You are not initializing no before you do no += 1
Instead of no += 1 you do no = +1 (which may accidentally overcome the previous error but it's probably not what you want)
In the <td><a href=.... line you are mixing up single and double quotes
In that same line, your javascript variable is inside PHP. data[i].id_news does not exist in PHP scope.
Check your web console and PHP error log, there will be several errors.

Ajax MySQL POST responses with Object without data

I am using that code to send a POST request to add data to a mysql table.
var todoItem = $(this).serialize();
$.ajax({
type: "POST",
url: "/test",
data: todoItem,
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
if(data.success){
$('#todo-list').append(
'<li class="list-group-item">' +
'<span class="lead">' +
data.todo +
'</span>' +
'<div class="pull-right">' +
'Edit' +
'<form style="display: inline" method="POST" action="/test/${data.id}">' +
'<button type="submit" class="btn btn-sm btn-danger">Delete</button>' +
'</form>' +
'</div>' +
'<div class="clearfix"></div>' +
'</li>'
);
} else {
$("#todo-list").append(
'<li class="list-group-item">' +
'<span class="lead">' +
'Fail' +
'</span>' +
'<div class="clearfix"></div>' +
'</li>'
);
}
}
Then i want to use data from the response to append to my list.
But if(data.success) isnt passing. why is that?
Also my data in console.log looks like object Object and doesnt contain the inserted row data.
Do i need to send a get request now to retrieve the last data row?

ADD #url.action with parameter on Table cell in AJAX

I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:
$.ajax({
url: "GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (obj) {
debugger;
$tbl.empty();
$tbl.append('<tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
for (var i = 0; i < obj.length; i++) {
$tbl.append(' <tr><td> ' + obj[i].senderId + '</td><td>' + obj[i].subject + '</td><td>' + obj[i].msg + '</td><td>TESTING</td></tr>');
}
}
});
Now instead of <a href="#"> I want to add Action Method #URL.Action on that <td>. Here's my Action Method:
<a href=#Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+',receiverId='+obj[i].senderId+ })>
But it shows error, I can't use javascript variable obj[i].senderId with c# code #Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?
David is right, but a simplified way for easy understanding.
var href = #Url.Action("SingleSentShow","Home", new { msgId ="__msgID__" ,receiverId="__receiverID__" });
href = href.replace("__mgsID__",obj[i].senderId).replace("__receiverID__",obj[i].senderId);
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
Both will work fine.
Update: As per Comment.
Move the value of href to data-href and set href to # and add a new class for script to work. And when the link is clicked we can swap the values.
$tbl.append(' <tr><td> <a href=# class=Test data-href="' + href + '">' + '... the rest of your line');
And add the below script.
$(document).on('click', '.Test', function () {
$(this).attr('href',$(this).attr('data-href'));
});
You can't mix server-side code and client-side code like that.
One option might be to put the base action URL in a JavaScript variable, and then append your query string parameters to it in JavaScript code. Something like this:
var singleSentShowURL = '#Url.Action("SingleSentShow","Home")';
This would result in something like this client-side:
var singleSentShowURL = '/Home/SingleSentShow';
Then in your loop you could use that variable to manually build the URL. Something like this:
$tbl.append(' <tr><td> <a href="' + singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId + '">' + '... the rest of your line');
You might split it into multiple lines for readability:
var href = singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId;
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');

Format of OnClick link in a .append

I am building a iPhone PhoneGap app, I am trying to include a Share button to share some data I pull from the server using JSON.
Here is what my code looks like:
$.ajax({
url: 'http://www.myurl.com.au/api/get_category_posts/?category_id=5&custom_fields=displaynative&callback=?',
dataType: 'json',
data: null,
// crossDomain: true,
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
timeout: 15000,
success: function(data, status)
{
(data.portfolio);
$.each(data.posts, function(i,item){
if(item.title_plain != undefined){
if(item.custom_fields.displaynative != undefined){
$('#datanews').append("<div data-role='collapsible' class='ui-nodisc-icon ui-alt-icon' data-theme='a' data-icon='r'><h4>" + item.title_plain + "</h4><p>"+ item.custom_fields.displaynative +"</p><a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + ")'>Save/Share</a></div>").trigger('create');
}
}
});
IT works except the Save/Share button and I know why but i don't know how to fix it.
Needs to be: `Save/Share
But I can't use the "" for the on click because it causes a formatting error.
Anyone know what I can do?
Thanks,
Ben
Your last parenthesis was on the wrong side.
Your code
<a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + ")'>Save/Share</a>
Fixed
<a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + "')>Save/Share</a>
Could also recommend to put double quotes on the onclick attribute:
<a href='#' class='ui-btn' onclick=\"window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + "'\")>Save/Share</a>

javascript Alert isn't working from inside getjson function

I have this script that creates a table from a json file. Each row has a clickale element that loads another json file. When the second json file loads I want to alert the user, but with the script I have the alert isnt working. What am I doing wrong? I am very new to javascript so it might just be a simple mistake.
$.each(result["auctionInfo"], function(i, player){
$("#curAuctions").append('<tr id="row'+i+'"><td>' + player["sellerName"] + "</td><td>" + style[player["itemData"]["playStyle"]] + "</td><td>" + player["itemData"]["preferredPosition"] + "</td><td>" + player["itemData"]["injuryType"] + "</td><td>" + player["itemData"]["contract"] + "</td><td>" + player["startingBid"] + '</td><td>' + player["buyNowPrice"] + '</td><td><div id="countdown'+i+'"></div></td><td style="text-align:center;" ><a id="buy'+i+'" data-id="'+ player["tradeId"] +'" data-price="'+ player["buyNowPrice"] +'" title="" class="button greenB" style="margin: 5px;"><span>Buy</span></a></td></tr>');
$('#countdown'+i).countdown({until: +player["expires"], format: 'HMS', compact: true});
$("#activeTable").tablesorter();
$( "#buy"+i ).bind( "click", function() {
$(this).replaceWith('<img src="images/loaders/loader.gif" alt="" style="margin: 14px;">');
$.getJSON("auction.php?action=buy&player=" + player["tradeId"] +"&value="+ player["buyNowPrice"], function(result){
alert("request finished");
});
});
});

Categories

Resources