Jeff Jeff - 6 months ago 50
jQuery Question

Return multiple values ajax and php

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 Jquey, 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

Answer

In generate.php add those to an array and encode to JSON and send. Get JSON in AJAX, print out.

Make your AJAX similar to:

$.ajax({
    type:'post',
    url:'generate.php',
    data: $(this).val(),
    dataType: 'json',          //Added this
    success: function(data){   //value to data
        $('#fileurl').val(data[0]);
        $('body').css('background-image', 'url(' + data[1] + ')');
        $('#bars').val(data[2]);
        $('#bpm').val(data[3]);
    }
}); 

generate.php

$returnArr = [$fileurl,$imageurl,$bars,$randbpm];    
echo json_encode($returnArr);