2

I have an HTML form generated by php which has a dropdown of voucherproviders.

I want to select the provider and have this populate the form for editing.

Here is my JQuery code:

$(document).ready(function() { 
    $(document).on('change','#id_voucherprovider',function(){
        var voucher_providers = <?php echo json_encode($voucher_providers); ?>;

        //The value I have got from the drop down is....
        var value = $('#id_voucherprovider option:selected').val();
        var vendortext = $('#id_voucherprovider option:selected').text();
        //so the voucher provider is
        alert(vendortext);

        $('.ftext input').val(vendortext);
        $("textarea#id_vendornotes").val(voucher_providers[value]);
    });
}); 

voucherproviders is not being passed into the JQuery despite the echo json_encode($voucher_providers); code working when inline with the php code.

It seems to return a null array. Can anyone see what is wrong?

Many Thanks

Dave

2
  • 1
    Try this var voucher_providers = '<?php echo json_encode($voucher_providers); ?>'; Jan 28, 2016 at 13:10
  • 1
    If you view the source, do you see the json array?
    – Foon
    Jan 28, 2016 at 13:15

4 Answers 4

1
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;

json_encode returns a string, unless it is parsed it will not be usable. Use JQuery .parseJSON and you should have better results. :)

var jsonString = <?php echo json_encode($voucher_providers); ?>;
var voucher_providers = $.parseJSON(jsonString);
1

try this (note the quotes):
var voucher_providers = JSON.parse('<?php echo json_encode($voucher_providers); ?>');

0

parse your json ex: obj = JSON.parse(data);

0

Hi please check the json format at below site:-

http://jsonlint.com/

and check if this is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.