How to insert data json in database laravel? - ajax

I use a jquery and ajax to get data json and send it to my controller, now I want to insert this data into table pointages help me please.
here is jquery ajax code:
$('.add-all').on('click', function() {
var items = [];
let valu = $('#datePicker').val();
$("tr").each(function(i,r){
if ( i > 0 && $(r).find("input").first().prop("checked"))
{
items.push({"matricule": r.cells[3].innerText, "salaire": r.cells[5].innerText, "date" : valu })
}
});
//ajax
$.ajax({
method : 'POST',
url : 'mois',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data : {"items":items}, // pass in json format
success : function(data) {
console.log(data);
},
error : function(err){
console.log(err)
}
});
//fin ajax
});
Controller :
public function addMultiple(Request $request){
$data = $request->only('datep','salaire','matricule');
$pointage['data'] = json_encode($data);
Pointage::insert($pointage);
}
i get :
data: {…}
items: (3) […]
0: Object { matricule: "1", salaire: "6000", date: "2019-06-23"}
1: Object { matricule: "2", salaire: "5000", date: "2019-06-23"}
2: Object { matricule: "3", salaire: "7000", date: "2019-06-23" }
length: 3
<prototype>: Array [
<prototype>: {…
model Pointage:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pointage extends Model
{
//
}
table pointages
public function up()
{
Schema::create('pointages', function (Blueprint $table) {
$table->increments('id');
$table->integer('matricule');
$table->date('datep');
$table->double('nbrj');
$table->double('prime');
$table->double('solde');
$table->timestamps();
});
}

Related

Ajax to call Symfony controller

I'm trying to call a method with ajax.
ajax connection is succeed and no error message was appeared.
the JS code
$("[id^=changeStatus]").each(function(){
$(this).on("click", function(){
const id = $(this).data('id');
console.log(id);
$.ajax({
type: "POST",
url: "{{url('change_order_status')}}",
data: id,
async: false,
})
.done(function() {
console.log('success');
})
.fail(function () {
console.log('error');
});
});
but the method in the controller seemingly not working.
controller
/**
* #Method("POST")
* #Route("/%eccube_admin_route%/", name="change_order_status")
* #param $request
* #return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function changeOrderStatus(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$this->logger->info("it's working");
dump($rquest);
}
I don't know what is wrong with it.
Please help.
I insert the js to every pages as an snippet is that's why it doesn't work properly.
You must return an instance of Response class in a controller . So here, what you can do is to return a JsonResponse
return new JsonResponse($request->getContent());
May be you can try this.
$("[id^=changeStatus]").each(function(){
$(this).on("click", function(){
const id = $(this).data('id');
console.log(id);
$.ajax({
type: "POST",
url: "{{ path('change_order_status') }}",
data: {
id : id
},
async: false,
})
.done(function(data) {
console.log(data)
console.log('success');
})
.fail(function () {
console.log('error');
});
});
/**
* #Route("/%eccube_admin_route%/", name="change_order_status", methods={"POST"})
* #param $request
* #return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function changeOrderStatus(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$this->logger->info("it's working");
$id = $request->request->get('id');
// Try to dump your request
// dd($request);
return $this->json([
'success' => true
]);
}
I just don't know what eccube_admin_route mean.
And don't forget to extend AbstractController in your controller class
This is example from my project. Try to dump your controller object and use symfony debugbar to open your ajax request, click on url columns

Prestashop 1.7.6.2 ajax call backoffice module

I have problem with ajax from select2 in prestashop 1.7. When I try writte something the calling is 200 but I got error "The Controller Psb2BAjaxModuleAdmin is missing or invalid."
I create Controller for test in my module
modules/psb2b/src/Controller/Psb2BAjaxModuleAdminController.php
<?php
namespace Scenario\PSB2B\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
class Psb2BAjaxModuleAdminController extends FrameworkBundleAdminController
{
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
return $this->ajaxDie(json_encode("test"));
}
public function postProcess()
{
PrestaShopLogger::addLog("MODULE CONTROLLER OK ", 1);
}
public function displayAjax()
{
$usb_search_token = $this->generateUrl("psb2bAjaxAdmin");
return $this->ajaxDie(json_encode("test"));
}
}
and in admin directory admin*********/themes/default/js
$(document).ready(function(){
$('#category_features').select2({
width: 'resolve',
ajax: {
type: 'POST',
url: usb_search_token,
dataType:'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
success: function (result) {
console.log(result);
}
} });
});
In my module i used hook
public function hookActionAdminControllerSetMedia()
{
MediaCore::addJsDefL('usb_search_token', $this->context->link->getAdminLink('Psb2BAjaxModuleAdmin'));
$this->context->controller->addCSS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/select2-full/dist/css/select2.min.css','all');
$this->context->controller->addJS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/select2-full/dist/js/select2.min.js');
$this->context->controller->addJS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/tree.js');
}
It seems your controller looks more like a 1.6+ one rather than a 1.7 with Symfony one.
I usually have an indexAction method in the controllers/Admin/my_controller.php.
In this method I use a
Media::addJsDef(array(
'usb_search_token' => admin_link));
));
Then as this method returns a
return $this->render('#Modules/rmvcolorgrid/views/admin/my_file.html.twig', [])
the URL is available for the js file in views/js/back.js.
You should have a look at PS docs for the recommended way to build this.

how insert data json into database laravel?

I use ajax to get data json and send it to my controller, now I want to insert this data into table pointages help me please wher is the error. here is ajax code:
he give me this error
$('.add-all').on('click', function() {
var items = [];
let valu = $('#datePicker').val();
$("tr").each(function(i,r){
if ( i > 0 && $(r).find("input").first().prop("checked"))
{
items.push({"matricule": r.cells[3].innerText, "salaire": r.cells[5].innerText, "date" : valu })
}
});
//ajax
$.ajax({
method : 'POST',
url : 'mois',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data : {"items":items}, // pass in json format
success : function(data) {
console.log(data);
},
error : function(err){
console.log(err)
}
});
//fin ajax
});
Controller:
public function addMultiple(Request $request){
foreach($request->get('items') as $item){
$pointage = Pointage::create([
'matricule' => $item->$item['matricule'],
'datep' => $item->$item['datep'],
'solde' => $item->$item['salaire']
]);
}
return redirect("mois");
}
modele Pointage :
class Pointage extends Model
{
/**
*
*
* #var array
*/
protected $fillable = [
'matricule', 'datep', 'solde',
];
}
table pointages:the other fields is nullable
public function up()
{
Schema::create('pointages', function (Blueprint $table) {
$table->increments('id');
$table->integer('matricule');
$table->date('datep');
$table->double('nbrj');
$table->double('prime');
$table->double('solde');
$table->timestamps();
});
}
what do you have in the line 79? I think could be
'matricule' => $item['matricule'],
instead
'matricule' => $item->$item['matricule'],

Is it possible to post from custom js to .module/custom.php/controller file and get response in custom js while developing custom module in drupal8?

i have this in custom.js file in drupal modules/mymodule/js/ folder
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: 'modules/mymodule/custom.php',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);
and i have to post to modules/mymodule/custom.php
<?php
echo "test";
?>
and return data from custom.php
You can do that by creating a controller for listening that ajax call
my_module.routing.yml
my_module.call_back:
path: '/my_module/call_back'
defaults:
_controller: '\Drupal\my_module\Controller\DefaultController::callBack'
_title: 'Call Back'
Controller
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Class DefaultController.
*/
class DefaultController extends ControllerBase {
/**
* Your Callback
*
*/
public function callBack() {
return ["This is a test" ];
}
custom.js
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: '/my_module/call_back',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);

recover AJAX post data with Laravel 5.5

I have an Ajax script and i have to recover the datas in a controller as POST and we have error 404 ...
Here is my JS :
function ajax() {
var values = {
'str': "Salut",
'id': "Dave & Alex",
};
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/ajax',
type: 'post',
dataType: 'json',
async: true,
data:values,
success: function (result) {
console.log(result);
},
error: function (result) {
console.log(result);
},
complete: function (result) {
console.log("complete");
}
});
};
Here are my route which is /admin/ajax and which is available to logged in admins:
Route::group(['prefix' => 'admin'], function () {
Route::group(['middleware'=>'admin'], function(){
Route::post('/ajax', 'AdminsController#majax');
});
});
In my Controller i created a method :
public function index(Request $request)
{
if($request->ajax()){
return response()->json(['status'=>'Ajax request']);
}
return response()->json(['status'=>'Http request']);
}
I have 2 issues :
1. I have an Http request displayed as result
2. How can i display the values of my "values" array ?
Thanks for your help

Resources