-1

I have a problem using jquery ajax. I have already a js player that works fine without ajax. I.E.

/jwplayer.js

window.onload = function () {

function etc etc etc

jwplayer('player').setup({
playlist: [{
file: video_url,
}],
width: "640",
height: "380",
autostart: "true",
stretching: "exactfit",
volume: "100",
});
}

PHP page

<script type="text/javascript" src="/jwplayer.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<div id='player'></div>

<script type="text/javascript">
var video_url = some_website_dot_com/file/.m3u8
</script>

This works just fine. But i cant add an ajax function to var video_url. This is the script that i'm trying to make it work

<script type='text/javascript'>
var video_url = function () {
$.ajax({
    type: 'get',
    url: "some_website_dot_com/file/.m3u8",
    dataType: "html",
    success: function (data) {
        var result = data.match(/(http\:\/\/\S+m3u8)/);
        return result[1];
    }
});
}();
</script>
Avel
  • 111
  • 1
  • 2
  • 9

1 Answers1

2

You're trying to return something from an inner function, why not just do this?

var video_url;
$.ajax({
    type: 'get',
    url: "some_website_dot_com/file/.m3u8",
    dataType: "html",
    success: function (data) {
        var result = data.match(/(http\:\/\/\S+m3u8)/);
        video_url = result[1];
    }
});

Update: to get your player created and working when you get the url:

function setupVideo(data) {
    var result = data.match(/(http\:\/\/\S+m3u8)/);
    var video_url = result[1];
    jwplayer('player').setup({
        playlist: [{
            file: video_url,
        }],
        width: "640",
        height: "380",
        autostart: "true",
        stretching: "exactfit",
        volume: "100",
    });
}

$.ajax({
    type: 'get',
    url: "some_website_dot_com/file/.m3u8",
    dataType: "html",
    success: setupVideo
});

A good read on AJAX and specifically the A for asynchronous: How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • Even i'm not sure if this is a proper way to use ajax, but i tried before, and it doesnt work. – Avel Oct 23 '15 at 19:58
  • It works for getting `video_url` but I guess you're not familiar with async? I update my answer. – Shanoor Oct 23 '15 at 20:03
  • I updated my question posting my jwplayer.js file exactly as it is. – Avel Oct 23 '15 at 20:19
  • But it's true, i'm not familiar with async – Avel Oct 23 '15 at 20:21
  • I have found a simple way: `var page = $.ajax({ type: 'get', url: "some_website_dot_com/file/.m3u8", dataType: "html", async: false, success: function (data) { return data; } }).responseText; var video = page.match(/(http\:\/\/\S+m3u8)/); var video_url = video[1];` – Avel Oct 23 '15 at 23:13