Youtube Search js function - javascript

While i was searching at stackoverflow, i found the code below :
$(document).ready(function () {
$("#show").click(function () {
getYoutube($("#Search").val());
});
});
function getYoutube(title) {
$.ajax({
type: "GET",
url: yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + title + '&format=5&max-results=1&v=2&alt=jsonc',
dataType: "jsonp",
success: function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_id = data.id;
var video_title = data.title;
var video_viewCount = data.viewCount;
$("#result").html(video_id);
});
} else {
$("#result").html('false');
}
}
});
}
How can i edit the code to keep only the function?
I want to be able to use it like that : getYoutube(my_keywords);
Also, how can i save the function output to variable? something like :
var_name = getYoutube(my_keywords);
would be ok?
Thnx! ;)

yes, you can use it as without $(document).ready. No, function does not return anything
To "return" value from Ajax:
$.ajax({
...
success: function(dataFromServer) {
processServerOutput(dataFromServer);
}
});
function processServerOutput(someString) {
alert(someString);
}

Related

JavaScript ajax call: how to return a value in if statement

I have a function in which, if idType is 1, I do a ajax call to my php file, in which I get the name with specific idName and return it. If idType is not 1, return another exemple value.
function get_name(idName, idType){
var resultString = ""
if(idType == 1){
$.ajax({
type:"GET",
url:"myFile.php",
dataType:"JSON",
data:{idName: idN},
success: function(data){
resultString = data.name
console.log(resultString)
return resultString
},
error: function(d){
}
});
} else {
resultString = "otherValueName"
console.log(resultString)
return resultString
}
}
I have this function that takes as parameter some id names, and calls get_name with that specific idName and type. In this exemple function, I omitted the for cicle
function printName(exempIdName){
var string= get_name(exempIdName, 1);
console.log(string)
return string
}
Finaly, I print the name
printName("Alex");
But if idType is 1 and does ajax call, the result is undefined. In the console, the result of variable "string" in printName function is undefined. But the result of the variable "resultString" in get_name has the right value.
How can I resolve this problem?
There is one simple approach to achieve what you want. Just mark the ajax call to sync. By default, the jQuery Ajax call runs in Async mode, but we can make it run in Sync mode by passing "async: false" as one more argument.
Here is the working copy of the solution: Way1- We should return the promise from the function and then handle the promise to get result. Way2 - using async: false
HTML 2. JSON sample data (data.son)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function get_ContentWay1(idName, idType) {
var resultString = ""
if (idType == 1) {
return $.ajax({
type: "GET",
url: "data.json",
dataType: "JSON",
data: { idName: idName },
success: function (data) {
resultString = data.employee.name;
console.log(resultString)
},
error: function (d) {
}
});
} else {
resultString = "otherValueName"
console.log(resultString)
return new Promise(function (resolve, reject) {
resolve(resultString);
});
}
}
function get_ContentWay2(idName, idType) {
var resultString = ""
if (idType == 1) {
$.ajax({
type: "GET",
url: "data.json",
async: false,//You need to pass this
dataType: "JSON",
data: { idName: idName },
success: function (data) {
resultString = data.employee.name;
console.log(resultString)
},
error: function (d) {
}
});
} else {
resultString = "otherValueName"
console.log(resultString)
}
return resultString;
}
$("button.btnWay1").click(function () {
var idType = $(this).attr("idType");
var idName = $(this).attr("idName");
// Way 1
var contect = get_ContentWay1(idName, idType).then((result) => {
if (result != "otherValueName")
$("#div1").html(result.employee.name);
else
$("#div1").html(result);
}).catch((err) => {
alert("error");
});
});
$("button.btnWay2").click(function () {
var idType = $(this).attr("idType");
var idName = $(this).attr("idName");
//Way 2
var contect = get_ContentWay2(idName, idType);
$("#div1").html(contect);
});
});
</script>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<button class="btnWay1" idType="1" idName="abc">Get External Content Way 1</button>
<button class="btnWay1" idType="2" idName="abc">Don't Get External Content Way 1</button>
<button class="btnWay2" idType="1" idName="abc">Get External Content Way 2</button>
<button class="btnWay2" idType="2" idName="abc">Don't Get External Content Way 2</button>
</body>
</html>
{
"employee": {
"name": "sonoo",
"salary": 56000,
"married": true
}
}
I think you have a typo in your code:
function get_name(idName, idType){
var resultString = ""
if(idType == 1){
$.ajax({
type:"GET",
url:"myFile.php",
dataType:"JSON",
data:{idName: idN}, // Here you are passing idN instead of idName
success: function(data){
resultString = data.name
console.log(resultString)
},
error: function(d){}
});
} else {
resultString = "otherValueName"
console.log(resultString)
}
return resultString;
}

Add removed element back to DOM jQuery 2

I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/

Jquery with variable selector doesn't work

I don't know why the selector jquery doesn't accept a variable.
function myfunction()
{
$.ajax({
url: "/file.php", dataType: "json", type: "GET",
success: function(data)
{
var data = data.split("-");
data.forEach(function(entry)
{
if (entry != "")
{
$("#check_status_" + entry).html('text');
}
});
}
});
}
variable entry is not empty, the problem is when I put it into the selector.
Thanks.
[update]
{
var test = "aaa-bbb-ccc";
var data = test.split("-");
data.forEach(function(entry) {
if (entry != ""){
$("#check_status_" + entry).html('!NEW!');
}
});
}
nothing the same
It seems to work fine if you are achieving something like this
data.forEach(function(entry) {
if (entry) {
$("#check_status_" + entry).html('text');
}
});

Variable not accesable in ajax response

I'm having troubles using a global variable in my ajax response.
LastDate is a variable defined in the page I loaded into my second page. (function load_table)
I am able to acces the variable before the ajax call, but I can't seem to acces it in my ajax succes. because it gives undefined. <==== in code
my code:
var dia_date = {};
$(window).load(function()
{
DP("eerste keer")
load_table();
} );
function load_table()
{
DP('load_table');
$.ajax({
type: "POST",
url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID,
success: function (data) {
$("#diagnoses_zelf").html('');
$("#diagnoses_zelf").append(data).trigger('create');
//initialize_table();
update_table();
},
error: function(){
alert('error');
}
});
return false;
}
function update_table()
{
if(LastDate > Datum)
{
alert("LasteDate" + LasteDate);
}
else
{
alert("Datum" + Datum);
}
alert('gast .... ' + LastDate); // <========== this is promted on the screen so there is no problem
$.ajax({
type: "POST",
url: "/refresh_diagnose/" + DosierID,
dataType: "json",
data : JSON.stringify(dia_date),
success: function (data) {
var DataDate = new Date(data.Year, data.Month, data.Day, data.Hour, data.Minute, data.Second);
alert('lastdate :'+ LastDate + 'date.date :' + DataDate);
//<============ BUT HERE HE GIVES LastDate AS UNDEFINED
},
error: function(data){
alert(data);
}
});
return false;
}
I can't see what I'm doing wrong. Can annyone help me plaese ? Thanks in advance.
You can try making a function.
var lastDate = #;
function getLastDate(){return lastDate;}
ajax.blablabla.success :{getLastDate();}

Can't set HTML using jQuery

For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});

Categories