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

asked Jan 28, 2016 at 13:08
2
  • 1
    Try this var voucher_providers = '<?php echo json_encode($voucher_providers); ?>'; Commented Jan 28, 2016 at 13:10
  • 1
    If you view the source, do you see the json array? Commented 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);
answered Jan 28, 2016 at 15:02
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Jan 28, 2016 at 15:58

Comments

0

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

answered Jan 28, 2016 at 13:23

Comments

0

Hi please check the json format at below site:-

http://jsonlint.com/

and check if this is fine.

answered Jan 28, 2016 at 15:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.