hihihihi
hihihihi

Reputation: 88

Convert JSON to string JAVASCRIPT

I want my position to show as a string. Can someone give me clue on how to do this? Im just new to laravel and javascript. enter image description here

public function myformAjax(Request $request)
{

    $position =Tbl_press_release_recipient::select('position')->where('country',Request::input('country'))->distinct()->get();
    return json_encode($position);
}

my ajax:

 $(document).ready(function() {
        $('#country').on('change', function() {
            var country = this.value;
            if(country){
                $.ajax({
                    url: '/member/page/press_release_email/choose_recipient_press_release/ajax',
                    type: "GET",
                    data:{country:country},
                    dataType: "json",
                    success:function(data) {


                        $('select[name="position"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="position"]').append('<option value="'+ JSON.stringify(key) +'">'+ JSON.stringify(value) +'</option>');

                        });

                    }
                });
            }else{
               alert("as23d");
            }
        });
    });

Upvotes: 2

Views: 63

Answers (2)

tomol1111
tomol1111

Reputation: 13

If in ajax response you get json like {key: value}, check this:

...,
success: function(repsonse) {
   $.each(repsonse, function(i, elem) {
      $('select[name="position"]').append('<option value="'+ i +'">'+ elem +'</option>');
   });
}

jsfiddle: https://jsfiddle.net/tomol1111/7sw53q45/

Upvotes: 0

MrCode
MrCode

Reputation: 64536

You're stringifying the value object whereas you need to access the position property of the value object:

$('select[name="position"]').append(
    $('<option>', { value : value.position, text : value.position })
);

This also creates an option element object to set the text and value, instead of concatenating the HTML which could lead to XSS vulnerabilities.

Upvotes: 1

Related Questions