I have a query. I am working on saving arrays into a database but before doing so, I need to split the data and only save specific values. My approach involves using Ajax to pass the data to the controller.
Important note: The array sets can be more than 1, therefore each set needs to be divided and stored based on columns inside the database.
Below is the JavaScript code with Ajax:
Hotspot.prototype.saveData = function (data) {
if (!data.length) {
return;
}
// Get previous data
var raw_data = localStorage.getItem(this.config.LS_Variable);
var hotspots = [];
if (raw_data) {
hotspots = JSON.parse(raw_data);
}
// Append to previous data
$.each(data, function (index, node) {
hotspots.push(node);
});
console.log(hotspots);
this.data=data;
$.ajax({
type:"POST",
url:"/store",
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
Title: JSON.stringify(hotspots),
Message: JSON.stringify(hotspots),
x: JSON.stringify(hotspots),
y: JSON.stringify(hotspots),
},
success: function(data){
console.log(data,d);
},
error: function(data)
{
console.log(data);
},
});
localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots));
this.element.trigger('afterSave.hotspot', [null, hotspots]);
};
The Controller:
public function storePin(Request $request)
{
request()->validate([
'Title' => 'required',
'Message' => 'required',
'x'=> 'required',
'y'=>'required',
]);
dd($request);
if ($request->all())
{
$pin = new Pin();
$pin->Title=json_encode($request->input('Title'));
$pin->Message= json_encode($request->input('Message'));
$pin->x = json_encode($request->input('x'));
$pin->y =json_encode($request->input('y'));
$pin->save();
}
}
An example of the output:
Title: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
Message: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
x: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
y: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
Based on this, I want to only save:
Title:only save title
Message:save message
x:save x
y save y