JSON POST request, using php and javascript

时间:2018-03-25 19:32:39

标签: javascript php json api post

I am after some help. When the button is clicked a new window opens showing my website which is what I want however, when I click the add button on my website it does not pull the data stored in:/app/addons/myapp/callback. I want to make a post request. My button code is below:

<form action="/app/addons/myapp/callback" method="post">
    <input type="button" value="Customise" onclick="window.open.href=window.open 
    ('https://mywebsite.com',
    'popup','width=800,height=800'); return false;">
</form>

This is my JSON POST:

<?php
$type = $_SERVER['CONTENT_TYPE'];

switch($type)
{
    case 'application/json':
        $json = file_get_contents('php://input');
        break;
    case 'application/x-www-form-urlencoded':
        $json = $_POST['data'];
        break;
    default:
        throw new Exception('Invalid content-type');
}

$data = json_decode($json);

I want to return product information via a JSONP API which is like this below:

callback({
    'price': '£3.99',
    'name': 'iPhone 6 Case',
    'description': 'A stylish case for your iPhone'
});

Is my callback correct to make this happen?

<?php

$callback = $_GET['callback'];
$callback = preg_replace("/[^0-9a-zA-Z\$_]/", "", $callback); // XSS prevention

$price = "£3.99";
$name = "iPhone 6 Case";
$description = "A stylish case for your iPhone";

$json = json_encode(array('price' => $price, 'name' => $name, 'description' =>$description));
$jsonp = "{$callback}({$json})";

header('Content-type', 'text/plain');

echo $jsonp;

exit;

Both my callback and JSON are stored in:in:/app/addons/myapp

I am also using CS-Cart. Any help is much appreciated.

Thank you

0 个答案:

没有答案