ani0904071
ani0904071

Reputation: 368

Unable to pass JSON/JSON string in function parameter

I have stored json string in my db field like following which is a valid json:

{"contact_person_name":"abcd","address_line1":"line1","address_line2":"line2","postal_code":"1111","country_id":"2","state":"someState","city":"someCity"}

when I am trying to pass this json string variable requestData.fields_values in a function parameter it is being printed in console like following while clicking the anchor tag:

literal not terminated before end of script

my JavaScript function is following:

function performChangeRequest(vendorId, requestedData){
            console.log('data: ' + requestedData);
}

I am appending dynamically data like following:

<a href="javascript:performChangeRequest('${requestData.vendor_id}', '${requestData.fields_values}' )"></a>

If I print the first variable vendorId it is working fine.

Any help? I have tried looking around

Upvotes: 0

Views: 842

Answers (1)

hngr18
hngr18

Reputation: 857

When you retrieve the JSON from the database and set requestData.fields_values, instead of assigning

requestData.field_values = **data**

instead do

requestData.field_values = **data**.replace('"', '\\"')

If you don't have the ability to intercept this value as it is being retrieved from the database, try instead to change the anchor tag to something like this:

<a href="javascript:performChangeRequest('${requestData.vendor_id}', '${requestData.fields_values.replace('"', '\\"')}' )"></a>

In the function performChangeRequest do console.log('data: ' + JSON.parse(requestedData));

Upvotes: 1

Related Questions