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)
}
Related
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.
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;
};
};
});
});
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/
I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
Sorry, this is a Javascript beginner question. My jqGrid function works fine the first time around, but when I call it a second time, nothing happens, no request is issued. Code fragment:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
The alert() shows me that doGrid() is really called successfully the second time. So it's really the $("projectList").jqGrid() function that doesn't execute, or fails silently .. Unless I made an obvious mistake in the way I call it?
I think the second time is no longer a need to regenerate the entire Grid. Then you only change the set parameters and grid computing to date. For this you need a trigger("reloadGrid") call.
$(document).ready(function() {
var runonce=false;
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
if (false==runonce) {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
runonce=true;
} else {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl
}).trigger("reloadGrid");
}