I want to set a url inside my ajax call back function - javascript

I want to make a clickable link in my ajax success response. But I could not do this.
<td id="attachment"></td>
function DoAction(id) {
$.ajax({
type: "get",
url: "/view_message",
data: "id=" + id,
dataType: 'json',
success: function(data) {
if (data) {
var text = "No Files There !";
$('#myModal').modal('show');
$('#subject').text(data.subject);
$('#body').text(data.body);
$('#created_at').text(data.created_at);
if (data.attachment) {
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
} else {
$('#attachment').text(text);
}
}
}
});
}
I want to display a clickable link in my .

I always encounter this when using ajax calls so;
Update your code from this.
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
To This.
$(document).find('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
if the code doesn't work add a console.log("working") function to see if your code is really reaching the success function.
I hope it helps.

Related

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

JQuery click 1 does nothing

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

using jQuery mobile with ajax

I am trying to print a jQuery mobile thing using ajax but it doesn't encode the result as jQuery mobile is supposed to do.
This is a simplified version of the part of the javascript code that is supposed to do so:
<script type="text/javascript">
function changePage(task) {
var objText = "";
$.ajax({
type: "POST",
url: "DataFetch.aspx/FetchData",
data: '{id: ' + <%=Session["loggedID"] %> + ', task: ' + task + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var obj = JSON.parse(response.d);
if (task == 2)
{
objText += "<div data-role='collapsible'><h3>click me</h3><p>text</p></div>";
}
document.getElementById('content' + task).innerHTML = objText;
}
});
}
</script>
How can I make it work? (when I write it explicitly in the html or outside the ajax functions it works but I need it to work with json)
Try changing
document.getElementById('content' + task).innerHTML = objText;
to
$('#content' + task).HTML(objText).enhanceWithin();
The enhanceWithin() call tells jQM to enhace the new content you added via AJAX:
http://api.jquerymobile.com/enhanceWithin/

Cannot read property 'length' of undefined jquery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am getting a list from C# web method with ajax (code below), the list is returned fine, but after the success method is done, it gives me an error - (Cannot read property 'length' of undefined) in the jquery (screenshot below)
Am I missing something ??
function getMainParentMenus() {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
The method above is called by the below method.
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
// var parentMenus = getMainParentMenus();
getMainParentMenus();
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
};
EDIT :
the data in the alert in the first block of code above is displayed like so
and in the chrome debugger :
Because getMainParentMenus is using AJAX it is asynchronous. Your next line of code after calling getMainParentMenus will be executed before the .success part of your AJAX call, so it will be executed before parentMenuss has been populated.
There are a few ways you can tackle this, one way would be to pass the callback function to getMainParentMenus, something like this:
function getMainParentMenus(myCallback) {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
if (callback && typeof(callback)==="function") {
callback();
}
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
Now you can call it like this:
var html = "<div id='accordian'> ddd";
getMainParentMenus(function() {
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
});
Your code for rendering the menus is being executed immediately after getMainParentMenus(); Javascript does not wait for the ajax call to complete before moving on to the next block. It is operating asynchronously, as others have mentioned in the comments.
Your code has to wait for the ajax call to complete before trying to display the data.
jQuery supports deferred execution and promises, so you can create code that will not execute until other code has completed. This is the preferred way of handling asynchronous operations.
Try this:
function getMainParentMenus() {
var request = $.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
return request;
}
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
getMainParentMenus().success(function (result) {
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
});
}

Parsing json synchronously from url in javascript

I'm trying to get title of a youtube video. So i'm using jQuery to parse json. But it works asynchronously, so the answer comes after the page loaded. The result is:
http://www.youtube.com/watch?v=Ym0hZG-zNOk (undefined)
How can i fix it?
Thanks.
http://jsfiddle.net/3vQht/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
document.writeln("<a target='_blank' href='" + link + "'>" + link.bold() + "</a> (" + name(videoID) + ")<br>");
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc&callback=?";
var fin;
$.getJSON(source, function(json) {
fin = json.data.title;
console.log(fin);
});
return fin;
}
</script>
</head>
<body>
</body>
</html>
Hy,
here is the solution :)
<script type="text/javascript">
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc";
$.ajax({
type: 'GET',
url: source,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
$(document).ready(function() {
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
name(videoID);
});
</script>
If you want to get your data sync just use this version:
$.ajax({
type: 'GET',
url: source,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
getJSON is asynchronous, so when the return fin; is reached, the data hasn't been fetched yet.
Everything that depends on the JSON MUST be inside the success callback.
If you prefere, you can also fetch your data synchronously. Check the jQuery.ajax() documentation for the async parameter.
EDIT: Just figured that you're loading your data using JSONP and that it's not possible to do that synchronously. You need to use asynchronous callbacks instead.
I haven't played with their api, but a quick look at
https://developers.google.com/youtube/2.0/developers_guide_json
indicates that they support jsonp callbacks so that you can prepend a script that does sends the data to a callback function (just add &callback=yourFunction to the end of the url)
function prependScriptFromUrl(s){
var a=document.createElement("script");
var b=document.getElementsByTagName('head')[0];
a.src=s;
b.insertBefore(a,b.firstChild)
}

Categories

Resources