问题描述:

I am receiving 400 (Bad Request) on jQuery ajax post to Product Controller. I am trying to post an array to my database.

Path attr

<a id="store-product" data-path="{{ path_for('product.design', {sku: design.sku}) }}">Submit</a>

Ajax code

/** Call to the Fancy Product Designer **/

fpd = new FancyProductDesigner(_container, pluginOpts);

var _storeProduct = jQuery('#store-product');

_storeProduct.click(function() {

var url = _storeProduct.attr("data-path");

var productViews = fpd.getProduct();

/*******

//console.log(productViews);

//Works Fine upto here with the log array below

//Array[5]0: Object1: Object2: Object3: Object4: Objectlength: 5__proto__: Array[0]

*******/

jQuery.ajax({

url: url,

type: "post",

data: JSON.stringify({

action: 'store',

views: productViews

}),

contentType: "application/json; charset=utf-8",

success: function (data) {

if(parseInt(data) > 0) {

alert('Product with ID ' + data + ' stored!');

} else {

alert('Error: ' + data + '');

}

}

});

});

Not sure what i have wrong here.

Controller Code

public function design($sku, Request $request, Response $response) {

$design = Design::where('sku', $sku)->first();

if($request->getParam('action') == 'store') {

$views = $request->getParam('views');

$design->update([

'views' => $views

]);

return $response->withRedirect($this->router->pathFor('product.get', [

'sku' => $sku,

]));

}

}

UPDATE

Apache Access Log

::1 - - [18/Jan/2017:16:27:25 +0700] "POST /projects/GolfBag/public/golf-bags/design/2563901 HTTP/1.1" 400 18 "http://localhost/projects/GolfBag/public/golf-bags/2563901" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"

Routes

$app->get('/golf-bags/{sku}', ['Base\Controllers\ProductController', 'getProducts'])->setName('product.get');

$app->post('/golf-bags/design/{sku}', ['Base\Controllers\ProductController', 'design'])->setName('product.design');

网友答案:

After a bit of digging i found the issue was that the CSRF token is not applied to the post data

相关阅读:
Top