I already got it working to find out the YouTube ID of an normal YouTube URL. But I didn't thought about the short youtu.be URLs and I don't get it woking to filter out the YouTube-Id the video. As far as I know there are these kinds of YT-URLs available:
youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
youtube.com/watch?v=0zM3nApSvMg#t=0m10s
youtube.com/embed/0zM3nApSvMg?rel=0
youtube.com/watch?v=0zM3nApSvMg
youtu.be/0zM3nApSvMg
I found this in another question but it's not working:
/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/
So my question is: How do I have to edit the following code the get always the YouTube-ID back?! ;)
Thank you so much!
add_filter('embed_oembed_html', 'my_embed_oembed_html', 99, 4);
function my_embed_oembed_html( $html, $url, $attr, $post_id) {
$posttext = substr($url[0],1);
preg_match('/v\=([a-zA-Z0-9,-]+)/', $url, $youtubeID);
return '<div id="video" class="border-frame"><video class="video" data-settings="autoresize:fit" preload="none" data-youtube-id="' . $youtubeID[1] . '"></video></div>';
}
Actually, you might consider not using regular expressions. PHP has lots of built in functions that can help you. For instance, try the following code:
$urls = array(
'youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
'youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
'youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
'youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
'youtube.com/embed/0zM3nApSvMg?rel=0',
'youtube.com/watch?v=0zM3nApSvMg',
'youtu.be/0zM3nApSvMg'
);
function displayId($url, $id) {
echo "URL: ", $url, "\n";
echo "ID: ", $id, "\n\n";
}
foreach ($urls as $url) {
$u = parse_url($url);
parse_str($u['query'], $queryVars);
if ($u['query'] && $queryVars['v']) {
displayId($url, $queryVars['v']);
} else if ($u['fragment']) {
displayId($url, basename($u['fragment']));
} else if ($u['path']) {
displayId($url, basename($u['path']));
}
}
This produces the following output:
URL: youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
ID: 0zM3nApSvMg
URL: youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
ID: QdK8U-VIH_o
URL: youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
ID: 0zM3nApSvMg
URL: youtube.com/watch?v=0zM3nApSvMg#t=0m10s
ID: 0zM3nApSvMg
URL: youtube.com/embed/0zM3nApSvMg?rel=0
ID: 0zM3nApSvMg
URL: youtube.com/watch?v=0zM3nApSvMg
ID: 0zM3nApSvMg
URL: youtu.be/0zM3nApSvMg
ID: 0zM3nApSvMg
The code could be more robust but I think it gives you the idea. :)
Cheers.
add_filter('embed_oembed_html', 'my_embed_oembed_html', 99, 4);
function my_embed_oembed_html( $html, $url, $attr, $post_id) {
$posttext = substr($url[0],1);
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $youtubeID);
return '<div id="video" class="border-frame"><video class="video" data-settings="autoresize:fit" preload="none" data-youtube-id="' . $youtubeID[1] . '"></video></div>';
}
Related
I need some help with changing the URL/ permalink of my blog posts in 11ty. Currently, it's making the slug with the title of the post. However, I want it to make a slug that I want. For example: for this post named "Alphabets start from A B C", 11ty is creating url(slug) as "/alphabets-start-from-a-b-c". I want it to be as "/alphabets-start-a-b-c".
Here's my posts.11tydata.js file:
module.exports = {
layout: 'post',
title: 'Untitled',
eleventyComputed: {
permalink: "/{{ page.fileSlug }}/",
featured_image: (data) => {
if (data.featured_image) {
if (data.featured_image.search(/^https?:\/\//) !== -1) {
return data.featured_image;
}
return `/assets/img/${data.featured_image}`;
} else {
return false;
}
}
}
};
Please tell me a way so that I can directly fetch customized url of post from font-matter.
title: Alphabets start from A B C
body_class: blog
featured_image: lumberg.jpg
description: The first blog post in the new site.
permalink: alphabets-start-a-b-c
After reading through 11ty Docs, I got a workaround by using variable {{ page.filePathStem }}.
So now my posts.11tydata.js file look like:
module.exports = {
layout: 'post',
title: 'Untitled',
eleventyComputed: {
permalink: (data) => "/{{ page.filePathStem }}/",
featured_image: (data) => {
if (data.featured_image) {
if (data.featured_image.search(/^https?:\/\//) !== -1) {
return data.featured_image;
}
return `/assets/img/${data.featured_image}`;
} else {
return false;
}
}
}
};
And Front Matter for my example looks like:
title: Alphabets start from A B C
body_class: blog
featured_image: lumberg.jpg
description: The first blog post in the new site.
permalink: "{{ page.filePathStem }}"
I want to make API (Get & Post) requests to an API build with Yii2 using Electron.
I have tried Axion, Fetch, HTTP, request modules and all of them gave me the same error:
data: {
name: 'PHP Notice',
message: 'Undefined index: username',
code: 8,
type: 'yii\base\ErrorException',
file: 'C:\xampp\htdocs\app\controllers\ApiController.php',
line: 898,
'stack-trace': [Array]
}
Here is the code for the action I want to call:
public function actionLogin(){
if(Yii::$app->request->isPost){
Yii::$app->response->format = Response::FORMAT_JSON;
$data = Yii::$app->request->post();
$username = $data['username'];
$password = $data['password'];
$device_token = $data['device_token'];
$prefix = substr($username, 0, 3);
$model = null;
}
}
And here is the code in Electron:
axios.post('http://localhost:8080/app/api/login', {
username: 'Fred',
psssword: 'Flintstone'
})
.then(function (response) {
console.log(response);
});
For some reason, the parameters are not passing to the action.
I have tried a lot of ways and this one seems to be the simplest.
P.S. all of the way I have tried gave the same error.
I have found the solution for this issue, the way it worked was:
const login = async(username, password)=>{
const data = new URLSearchParams();
data.append('username', username);
data.append('password', password);
data.append('device_token', 'null');
await fetch(`http://localhost:8080/app/api/login`,{
method: 'post',
body: data
})
.then(res => res.json())
.then(data => {
if(data.status){
ipcRenderer.send('user:login', data.data.user_type, data.data.access_token);
}
else{
document.querySelector('#message').innerText = 'Wrong password or username';
document.querySelector('#message').style.display = 'block';
}
})
}
I am trying to post some data usng this.$http.post and I could not figure out how to pass in the data through the route api..
new Vue({
el: '#root',
data: {
newName: '',
nameList: []
},
methods: {
addName(){
this.nameList = this.nameList.concat(this.newName);
var name = this.newName;
this.newName = '';
this.$http.post('/api/name', {name: name}).then((response) => {
console.log(response.message);
});
}
},
mounted(){
this.$http.get('/api/name').then((response) => {
this.nameList= this.nameList.concat(JSON.parse(response.body));
console.log(this.nameList);
});
}
});
It is not very clear, what is the exact issue, here, what exact API you are trying to hit.
If you are trying to hit: /api/name/:someName, you can do following
this.$http.post('/api/name/'+name ).then((response) => {
console.log(response.message);
});
If you are trying to hit: /api/:someName with payload, you can do following
this.$http.post('/api/' + name, {name: name}).then((response) => {
console.log(response.message);
});
Let me know if it helps.
I'am struggling with select2.
I have an ajax call that returns me a json. The json is formated like that (from server):
public function get_groups()
{
$result = array();
$sql = "SELECT * FROM auth_groups ";
foreach ($this->db->query($sql)->result() as $row){
$tmp = array("id" => $row->id ,"label" => $row->name );
array_push($result, $tmp);
}
header('Content-type: application/json');
echo json_encode($result);
}
Then from my javascript i have :
$('#group_choice').select2({
minimumInputLength: 2,
ajax: {
url: "/bonsejour/extranet/ajax/resources/get_groups",
dataType: 'json',
data: function (term, page) {
return {
term:term
};
},
results: function (data, page) {
var results = [];
$.each(data, function(index, item)
{
results.push({id:item.ID, text:item.label});
});
return {
results: results
};
}
}
});
Where #group_choice is an input text.
When i type some text inside the input box it does shows all the elements coming from the json. But when i try to select an element nothing happens. How can i select the elements inside the input ?
Thanks
Refer http://ivaynberg.github.io/select2/#documentation
formatSelection: formatSelectionMethod,
function formatSelectionMethod(row) { return row.text;}
I hope you will find it helpful.
Please refer to Select2 Ajax Method Not Selecting,
and take the correct value:
id: function(data){return {id: data.id};},
or
id: function(data){return data.id}
My autocomplete is not working and I can't spot the error.
Jquery:
<script>
$(function() {
$('#autoComplete').autocomplete({
//source: "/groceries/items/autoComplete", ///This works but response isn't formatted correctly'
//dataType: "json"
minLength: 2,
source: function( request, response ) {
$.ajax({
url: "/groceries/items/autoComplete",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
term: request.term
},
success: function( data ) {
response( $.map( data, function( el ) {
return { label: el.id, value: el.name }
}));
}
});
}
});
});
Controller:
public function autoComplete() {
Configure::write('debug', 0);
$this->layout = 'ajax';
$query = $_GET['term'];
$items = $this->Item->find('all', array(
'conditions' => array('Item.name LIKE' => $query . '%'),
'fields' => array('name', 'id', 'category_id'),
'group' => array('name')));
$this->set('items', $items);
}
Form:
<p>
<?php echo $this->Form->create('Item', array('model'=>'item','action' => 'addItem', 'name'=>'AddItem'));?>
<?php echo $this->Form->text('Item.name', array('size'=>'30', 'id'=>'autoComplete', 'autocomplete'=>'off')); ?>
<?php echo $this->Form->text('Item.category_id', array('type'=>'hidden', 'value'=>'0')); ?>
<?php echo $this->Form->text('Groclist.id', array('type'=>'hidden', 'value'=>$groclist['Groclist']['id'])); ?>
<?php echo $this->Form->end('Add'); ?>
</p>
Response:
0: {Item:{name:Cake, id:6, category_id:null}}
1: {Item:{name:Carrot Cake, id:9, category_id:null}}
2: {Item:{name:Carrots, id:8, category_id:null}}
3: {Item:{name:Casserole, id:11, category_id:null}}
4: {Item:{name:Cauliflower, id:10, category_id:null}}
Edited for clarification.
I realize JqueryUI expects label and value and that map should rearrange them, but for some reason it's not. Any ideas?
I found an even better solution. This is done completely in the controller. No view required.
public function autoComplete() {
Configure::write('debug', 0);
*$this->autoRender=false;*
$this->layout = 'ajax';
$query = $_GET['term'];
$items = $this->Item->find('all', array(
'conditions' => array('Item.name LIKE' => $query . '%'),
'fields' => array('name', 'id', 'category_id'),
'group' => array('name')));
*$i=0;
foreach($items as $item){
$response[$i]['value']="'".$item['Item']['id']."'";
$response[$i]['label']="'".$item['Item']['name']."'";
$i++;
}
echo json_encode($response);*
}
What if you reduce the array that is being returned by the Items model. So instead of $this->set('items', $items); you return the json encoded results like so:
foreach($items as $item) {
$data[] = $item['Item'];
}
$data = json_encode($data);
echo $data;
exit;
This is inside the auto_complete method in the controller.
UPDATE:
When querying for Cake for example, it would return a result like so:
[
{"name":"Cake Batter","id":"1","category_id":"3"},
{"name":"Cake Mix","id":"2","category_id":"3"}
]
if you are not wanting to return the json, you could just return $data without the json encoding.
Format Update:
I am not certain if this is to "sloppy", but you could change the foreach loop to:
foreach($items as $item) {
$data[]= array(
'label' => $item['Item']['name'],
'value' => $item['Item']['id']
);
}
Looks like you forgot the Item:
response($.map( data, function( el ) {
return { label: el.Item.id, value: el.Item.name }
});
You can also do it in the server side using Set:
$this->set('items', Set::extract('/Item', $items));