This is my first time working with AJAX, I am creating a drum loop generator, instead of having to refresh the page to create a new loop I would like to try AJAX.
When #button1 is clicked it runs generate.php, I am trying to return multiple values from the generate.php echo and place them in different elements on the page.
The different values are the file url to be placed in audio src, background image url, the number of bars the loop is, and the BPM of the loop. They are separated by commas in the php echo.
I get an error in google developer tools that says "jquery-1.7.1.min.js:4 GET https://whatever.com/random/undefined 404 (Not Found)" when I click the button
Button:
<div id="button1"><div class="namething">Generate</div></div>
Jquery
<script>
$('#button1').click(function(){
$.ajax({
type:'post',
url:'generate.php',
data: $(this).val(),
success: function(value){
var data = value.split(",");
$('#fileurl').val(data[0]);
$('body').css('background-image', 'url(' + data[1] + ')');
$('#bars').val(data[2]);
$('#bpm').val(data[3]);
}
});
});
</script>
generate.php (it preforms functions before this, but this is the only data I need to return to my jquery and the rest of the page)
echo $fileurl,$imageurl,$bars,$randbpm;
I am not sure but I think its something with the 'data:' in jQuery, I just need to find out how to return the echo data
When I click the button it is working and creating a new loop its just not returning the echo data properly so I know the path is correct to generate.php
EDIT: (Solution)
Thanks @Thamilan for the help! I had to make a few small changes to jquery to update the audio player it is all now working like desired:
Jquery
<script>
$('#button1').click(function(){
$.ajax({
type:'post',
url:'generate.php',
data: $(this).val(),
dataType: 'json',
success: function(data){
var fileName = data[0];
$("#music").attr("src",fileName).trigger("play");
$('#timeline').css('background-image', 'url(' + data[1] + ')');
$('#bars').text(data[2]);
$('#bpm').text(data[3]);
}
});
});
</script>
PHP:
$returnArr = [$fileurl,$imageurl,$bars,$randbpm];
echo json_encode($returnArr);
'generate.php'