Jump to content
Sign in to follow this  
ajoo

Return from ajax results in object being undefined

Recommended Posts

Hi, 

 In an earlier topic I was trying to get the sounds to play off the server. The sound file being served by the server.

Eventually I have a situation where I have finally managed to get the sound to play within the ajax block. The lines of code shown execute and the sound is played. However if I try and pass the audio object  back to the calling function (// return audio) it ends up in the calling code as undefined !???

Could this be because of the asynchronous nature of ajax ? If so, Is there a way to get around it and pass the object back to the calling function successfully?   

 

<script>
	
$(document).ready(function(){

   $('.btn').click( function()
    
    	startSound();

    });     
     
      
   		function startSound() 
		{
			$('.btn').disabled = true;
			playURL = getURL();
			audio = playServerURL(playURL);
			console.log(audio); --------------------------------- ( ERROR--A )
	//		alert("Received Data");
	//		var audio = new Audio(playURL);
	//		audio.type = 'audio/mpeg';
	//		audio.play();
	//		audio.onended = getNextUrl;
		}	
 
		// Get sounds off the server
		$.ajax({
		  type: 'GET',
		  url: 'playsound1.php',
		  data: {sf: 'ready.mp3'},
		  dataType:"binary",
		  success:function(data){				// doesn't trigger
			alert("Yey !");					// does not popup
            .
            .
            .
            audio = new Audio(audBlob);
            var audio = new Audio(audBlob);
            // return audio;
            audio.type = 'audio/mp3';
            console.log(audio); -------------------------------------- (Message B)
            audio.play();
            
		  }
		})
  
})
</script>

console.log() inside the ajax (Message -- B) gives the audio object

Quote

<audio preload="auto" src="blob:http://franchisee.com/445a1868-1927-477f-afe1-e4241939dad2"></audio>

console.log() inside the startSound gives (Error -- A) :-

Quote

undefined  ----- serv_sound_1.js:25                          which corresponds to (ERROR -- A) in function startSound()

Please can someone shed light on this. 

Thanks all !

 

Share this post


Link to post
Share on other sites

Your code block is messy and doesn't make a lot of sense.   For example, what is playServerURL()?  Is that supposed to be where your ajax call is?  Then why isn't it?  What are those three lines of dots that are absolutely a syntax error? You need to post something more representative of what you have, not just random lines that show no structure and won't even compile.

That said, you don't return data from an ajax call by using return because of the deferred nature of the ajax process.   Either you use a callback function that then accepts the data (like how $.ajax calls your success handler) or you return a promise that can then have callbacks added to it and are run when the data is ready.

 

Share this post


Link to post
Share on other sites

OK - we don't know what playServerURL() or getURL() look like, so no idea what those are doing in the meantime. However, in my experience when you're dealing with AJAX you'll need to stop the actual click event from happening until you want it to. However, before we even consider that, there's a syntax error you should be seeing:

$('.btn').click( function()
	startSound();
});

Note that there's no opening brace after the function() declaration, but there is a closing brace before the closing parenthesis. This alone should be breaking everything. Once that's fixed, I still think you'll need to block the submit until you've got done what you need done, so update like so:

$('.btn').click( function(e){
	e.preventDefault();
	startSound();
});

 

Edited by maxxd

Share this post


Link to post
Share on other sites

Hi Kicken, Maxxd, all else  !

Sorry for the delay in my response. It was Diwali week in India, the light of festivals to celebrate the auspicious occasion of the return of Lord Ram from from an exile ! So a very Happy Diwali to all !!

I am making amends by posting fresh bit of code.

@Maxxd  Thanks for finding that syntax error. Surely It occurred while I was deleting comments etc from the pasted code to clean it a bit. Please find below the complete code that works.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<meta charset="UTF-8">
<h2>My Sounds</h2>
<span class='btn'>Play</span>

<script>
$(document).ready(function(){
			
	$('.btn').click( function(){
	
		startSound();
	});		
		
	function getSoundURL(soundURL){	
		$.ajax({
			type: "GET",
			url: 'playsound1.php',
			data: {sf: soundURL},
			dataType: 'binary',
			xhrFields: {
			responseType: 'blob'
			},
			success: function(blob){
				alert("YEY !");
				window.URL = window.URL || window.webkitURL;
				var blob = new Blob([blob]);
				var link=document.createElement('a');
				link.href=window.URL.createObjectURL(blob);
				blob = null;	
				var audio = new Audio(link.href);
				audio.type = 'audio/mpeg';
				console.log(audio);
				audio.play();
			}
		});
	}

	function startSound() 
	{
		var playURL = "ready.mp3";
		audio = getSoundURL(playURL);			// This is where,i want ajax to return the audio object.
//		audio.type = 'audio/mpeg';
//		audio.play();
	
	}  
	
});      
</script>

 

playsound1.php (simplified)

	if($_SERVER["REQUEST_METHOD"]==="GET")
	{	
		$sounddir = "sounddir/";	// Path to sound files
		$sf = html_escape($_GET["sf"]);

		$sf = $sounddir.$sf;
		$type = "audio/mpeg";	// The sound file has an extention of .mp3

		header("X-Sendfile: ".$sf);
		header("Content-Type: " .$type);
	}

The above code works but does not return the sound object back to the calling code as asked earlier. Would appreciate some help on that. There are quite some examples that i came across on callbacks but I am not sure which is the latest method to use since it has modified a lot over the years and a lot of those examples use deprecated code. 

Thanks !!

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.