Reputation: 3308
Here is my JavaScript:
$.ajax({
url: 'CheckColorPrice.php',
type: 'POST',
data: {
url: '<?php echo $LINK;?>',
ColorId: ColorNumber
},
dataType: 'json',
success: function (data) {
$('#LoadingImage').hide();
$("#PRICE").text("£ " + data["price"]);
}
});
Here is CheckColorPrice.php:
<?PHP
$url = $_POST['url'];
$ColorId = $_POST['ColorId'];
if(isset($_POST['url']))
{
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);
$DataVariants = $xpath->query('//span[@class="ImgButWrap"]/@data-variants')->item(0)->nodeValue;
$jsonStart = strpos($DataVariants, '[');
$jsonEnd = strrpos($DataVariants, ']');
$collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = [];
$SellPrice = [];
foreach ($item->SizeVariants as $size) {
$SizeNames[] = $size->SizeName;
$SellPrice[0] = $size->ProdSizePrices->SellPrice;
}
$names = implode(',', $SizeNames);
$price = implode('', $SellPrice);
if($ColVarId == $ColorId){
$healthy2 = array('£',' ','Â');
$yummy2 = array('','','');
$price = str_replace($healthy2, $yummy2, $price);
$PRICE = $price;
echo "price: ", json_encode($PRICE), "\n";
}
}
}
?>
The result from CheckColorPrice.php is looking just like this:
price: "37.99"
Where is my mistake, why it is not receiving the response properly. I don't get it at all... Can you help me out ?
Thanks in advance!
Upvotes: 1
Views: 2873
Reputation: 101
First thing, in your ajax request, add this parameter :
dataType : 'json'
Then, your response is not a correct json. You can return this :
echo json_encode(array("price"=>$PRICE));
Upvotes: 0
Reputation: 360572
You're not returning json. You're returning plain text which contains some json:
echo "price: ", json_encode($PRICE), "\n";
^^^^^^^^^^
That'd look like
price: "$9.99"
which is NOT valid json.
You need to return an array for your JS code to work:
echo json_encode(array('price' => $PRICE));
which would output:
{"price":"$9.99"}
Upvotes: 4
Reputation: 6047
Add the following header to your script:
header('Content-type: application/json'); header("Content-Disposition: inline; filename=ajax.json");
Also change the line
echo "price: ", json_encode($PRICE), "\n";
to
echo json_encode(array('price'=>$PRICE));
Hope that helps
Upvotes: 2