Slamet Bedjo
Slamet Bedjo

Reputation: 103

jQuery : error on ajax return because of line break and some character

Everyone, i have a problem. Making an ajax request with jQuery. It was error. I try to remove some variable that contains 'line break, double-quotes, etc'. And nothing error, everything just fine. How to solve this?

$.ajax({
    url: 'layout/owner/required/processing/get-product-data.php',
    cache: false,
    data: {idStr: thisProduct}
});

and the requested php file is:

<?php
header('Content-type: text/javascript');

$printData = '
var editData = {
    cat: "' . $cat . '",
    subcat: "' . $subcat . '",
    id: "' . $id . '",
    name: "' . $name . '",
    description: "' . $description . '",
    price: "' . $price . '",
    dlong: "' . $long . '",
    dwidth: "' . $width . '",
    dheight: "' . $height . '",
    spec: "' . $spec . '",
    fac: "' . $fac . '",
    rp: "' . $rp . '",
    cm: "' . $cm . '",
    color: "' . $color . '"
};
';

echo $printData;
?>

editData.description , editData.spec, editData.fac are contain enter/linebreak character, uhmm said they contain html

Upvotes: 0

Views: 171

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075019

Put them in a PHP associative array, and then output that array using json_encode. That will ensure that characters in strings are properly handled.

E.g., something like this:

<?php
header('Content-type: text/javascript');
$a = array(
    cat =>  $cat,
    subcat =>  $subcat,
    id =>  $id,
    name =>  $name,
    description =>  $description,
    price =>  $price,
    dlong =>  $long,
    dwidth =>  $width,
    dheight =>  $height,
    spec =>  $spec,
    fac =>  $fac,
    rp =>  $rp,
    cm =>  $cm,
    color =>  $color
);
echo 'var editData = ' . json_encode($a) . ';';
?>

Upvotes: 3

Related Questions