Laravel: Post Array of Objects - laravel

Im in trouble with this code, I cant store my dataP array objects into mysql.
Ajax request :
$.ajax({
url:'/register/addpostulantR',
method:'post',
dataType: "text",
data:JSON.stringify(dataP),
success(data){
console.log("succ "+data);
},
error:()=>{
console.log('error ');
}
})
Controller:intervenantController.php
public static function addPostulantR(Request $request)
{
return response()->json([
'dataP' => Intervenant::addPostulantR($request->all())
]);
//The dataP is my json
}
Model: Intervenant.php
public static function addPostulantR($data)
{
//$test = json_decode($data);
$id = 0;
foreach($data as $dataP) {
$id = DB::table('reponse')->insertGetId($dataP);
}
return $id;
}
Array: From my javascript
let dataP = [
{
fk_id_quest:1,
fk_id_post:id,
reponse : $("#descriptif_offre").val(),
created_at:date.getTime()/1000,
},
{
fk_id_quest:2,
fk_id_post:id,
reponse : $("#descriptif_offre").val(),
created_at:date.getTime()/1000,
}
];
Thanks a lot..

Related

Symfony 5 ajax post form

I need to make dynamic form in symfony 5 with ajax.
I make post request with axios on input value change on main route "/".
This route call my controller and i call dump() function for debug my request but i don't have any params on my request.
I looked in my network and my data is posted well. But I don't receive params on my request controller :/
On my view
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js"></script>
<script>
cat = document.getElementById("article_category")
token = document.querySelector("#article__token");
title = document.querySelector("#article_title");
cat.addEventListener("change", function (e) {
let form = document.querySelector("form")
let data = {}
data[title.getAttribute("name")] = title.value
data[token.getAttribute("name")] = token.value
data[cat.getAttribute("name")] = cat.value
axios.post("https://127.0.0.1:8000/", data).then(res => {
str = res.data
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html')
console.log(doc);
}).catch(function (error) {
console.log(error);
});
})
</script>
My Controller
/**
* #Route("/", name="article")
*/
public function index(Request $request, EntityManagerInterface $em): Response
{
$article = new Article();
$form = $this->createForm(ArticleType::class, $article);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
dump($request);
}
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($article);
$em->flush();
}
return $this->render('article/index.html.twig', [
"form" => $form->createView(),
]);
}
FormType
$builder
->add('title')
->add('category')
->add('Submit', SubmitType::class);
$builder->get('category')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$form = $event->getForm();
if ($form->getData()->getName() == "Cat 0") {
$form->getParent()->add('tag', EntityType::class, [
'class' => Tag::class,
]);
}
}
);

Ajax submission triggers Error = True by default even at success

Laravel ajax submission.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '{{URL::to('expense_bill/store2')}}',
method: 'POST',
data: $("#expense_create").serialize(),
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
},
error: function (xhr) {
$('#validation-errors').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');
});
},
});
});
Controller:
public function store2(Request $request)
{
if($request->ajax()){
//return response()->json($request);
$validator = Validator::make($request->all(), [
'supplier' => 'required',
]);
if ($validator->fails()) {
$returnArray['error']=true;
$returnArray['err_msg']=json_decode(json_encode($validator->errors()), true);
return $returnArray;
}
if ($validator->passes()) {
$request->merge(['total' => $request->total*100]);
$request->merge(['tax_value' => $request->tax_value*100]);
$expensebillheader = ExpenseBillHeader::create($request->all());
$expense_bill_no = $expensebillheader->id;
$count = $request->input('count');
for ($i = 0; $i <= $count; $i++){
//checks if input with this name exists (incase if any middle row was deleted)
if (isset($request->input('amount')[$i]))
{
$line = new ExpenseBillBody;
$line->bill_no = $expense_bill_no;
$line->description = $request->input('description')[$i];
$line->amount = $request->input('amount')[$i];
$line->account = $request->input('account')[$i];
$line->save();
}
};
$successArray = ['success'=>'true','msg'=>"Expnese No".$expense_bill_no." Created"];
return response()->json($successArray);
}
}
}
When validator fails, it's all fine. When validator passes it is supposed to give success=" true" message. But along with that it also gives error="true" as well. Not sure what am I doing wrong. See in the screenshot, the highlighted portion should not come.
Larave returns correct response. You have error here
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
}
...
if(data['success'] = true) and if(data['success'] = true) isn't comparasion, these are assigning values
Try to write comparasion operators ==
success:function(data){
console.log(data)
if(data['success'] === true){
}
if(data['error'] === true){
//Clear Valdiation Errors
console.log('hi');
}
}
...

Applying Ajax (Codeigniter)

I have this script and i need to apply ajax on it. Can someone give me an idea on how to apply ajax on these codes? I need to pass those variables on the controller. It works just fine but i need to alter it into ajax. It's just, im having a hard time figuring it out, how i can reassemble to ajax. Thank you ♥
function saveData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.post('<?php echo site_url("welcome/add") ?>', {id:id, nm:name, em:slug, hp:books, ad:address}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function editData(id, nm, em, hp, ad) {
$('#id').val(id)
$('#nm').val(nm)
$('#em').val(em)
$('#hp').val(hp)
$('#ad').val(ad)
$('#id').prop("readonly",true);
$('#save').prop("disabled",true);
$('#update').prop("disabled",false);
}
function updateData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.post('<?php echo site_url("welcome/update") ?>', {id:id, nm:name, em:slug, hp:books, ad:address}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
$('#id').prop("readonly",false);
$('#save').prop("disabled",false);
$('#update').prop("disabled",true);
})
}
function deleteData(id){
$.post('<?php echo site_url("welcome/remove") ?>', {id:id}, function(data){
viewData()
})
}
function removeConfirm(id){
var con = confirm('Are you sure to delete this data? HUHHHHH?!');
if(con=='1'){
deleteData(id);
}
}
$(".clicker").on("click", function(){
$(this).siblings().slideToggle('normal');
})
$(function() {
var $sidebar = $("#sidebar"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 0
});
}
});
});
</script>
Controller:
<?php
header('Access-Control-Allow-Origin: *');
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('crud_model');
}
public function index()
{
$data['books'] = $this->crud_model->getBooks();
$this->load->view('header');
$this->load->view('welcome_message',$data);
$this->load->view('footer');
}
public function view()
{
$data['books'] = $this->crud_model->getBooks();
$data['crud']=$this->crud_model->getView();
$this->load->view('view_data',$data);
}
public function add()
{
$data = array(
'id' => $this->input->post('id'),
'title' => $this->input->post('nm'),
'slug' => $this->input->post('em'),
'book_id'=>$this->input->post('hp'),
);
// $insert = $this->crud_model->postNew($data);
$data2 = array(
'book_id'=>$this->input->post('hp'),
'faqs_id' =>$this->crud_model->postNew($data),
);
$insert1 = $this->crud_model->postNewBridge($data2);
}
public function update()
{
$data = array(
'title' => $this->input->post('nm'),
'slug' => $this->input->post('em'),
'book_id'=>$this->input->post('hp'),
);
$this->crud_model->postUpdate(array('id' => $this->input->post('id')), $data);
}
public function remove()
{
$id = $this->input->post('id');
$this->crud_model->getDelete($id);
}
}
Model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Crud_model extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getBooks()
{
$this->db->select('*');
$this->db->from('book');
$query=$this->db->get();
return $query->result();
}
public function getView()
{
$this->db->select('*');
$this->db->from('book');
$this->db->join('faqs', 'book.id = faqs.book_id','inner');
$query=$this->db->get();
return $query->result();
}
public function postNew($data)
{
$this->db->insert('faqs', $data);
return $this->db->insert_id();
}
public function postNewBridge($data2)
{
$this->db->insert('book_faqs', $data2);
return $this->db->insert_id();
}
public function postUpdate($where, $data)
{
$this->db->update('faqs', $data, $where);
return $this->db->affected_rows();
}
public function getDelete($id)
{
$this->db->where('id', $id);
$this->db->delete('faqs');
}
}
Try this, Here I m giving you only saveData() in ajax
function saveData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.ajax({
beforeSend: function () {
//do something before ajax call
},
complete: function () {
//do something after ajax call done
},
type: "POST",
url: '<?php echo site_url('your_contoller/your_function'); ?>/',
data: ({id: id, nm: nm, em: em,hp: hp,ad: ad}),
success: function (data) {
setTimeout(function () {
//do something after a second
}, 1000);
}, error: function (data) {
}
});
}
i hope this helps
You simply need get() with your current code. Just use this function to call page and load it in a container with a class result with ajax.
$('#buttonId').click(function() {
$.get( "controller/function", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
});

codeigniter foreach not displaying all records in table

Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached

Select2 not returning any data, just display searching

i'm using codeigniter and select2 plugin for displaying my data.. but i have a problem, that plugin not display anything, just display searching... there is my code
/*------------- JS -----------------*/
$("‪#‎nm_peg‬").select2({
placeholder: "Masukkan Nama Pegawai",
width:'element',
ajax : {
url : "<?php echo site_url('pegawai/getAllData'); ?>",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
this is my controller
/*-------------- Controller ---------------*/
public function getAllData()
{
$this->load->model('pegawaimodel');
$d = $this->pegawaimodel->get_all_pegawai();
$rows = array();
foreach ($d as $a) {
$rows[] = $a;
}
header('Content-Type:application/json');
return json_encode($d);
}
and this is my model.
/*--------------Model-----------------*/
public function get_all_pegawai()
{
$this->db->select('peg_id, peg_nama');
$this->db->from('master_pegawai');
$query = $this->db->get();
return $query->result();
}
thank's for any help..

Resources