How to add new product into dabase from Ajax Request - ajax

I am trying to insert new product from a edit form via Ajax request, I am returning all values inserted however instead adding new product it's adding first product on the list. what am I doing wrong?
this is my Ajax request:
$(document).on('change','.qty',function(){
var id = $("#inv_id").val();
var tr = $(this).closest('tr');
var name = tr.find(".name").val();
var price = tr.find(".price").val();
var qty = tr.find(".qty").val();
var total = tr.find(".total").val();
$.ajax({
type: "POST",
url: '/product',
data: {id: id, name: name, price: price, qty: qty, total: total, '_token':$('meta[name="csrf-token"]').attr('content')},
success: function( data ) {
console.log(data);
},
error: function(data){
alert("fail");
}
});
});
this is my controller
public function product(Request $request){
$prod = new Product;
$prod->invoice_id = $request->id;
$prod->name = $request->name;
$prod->price = $request->price;
$prod->qty = $request->qty;
$prod->total = $request->total;
$prod->save();
return response()->json(['responseText' => 'Success!'], 200);
}
I have tried using Product::create([]); but it's not working either. it adds a copy of the first product the id returning is the id coming from invoice id.

What is wrong?
Ajax response data or inserted values into db?
It seems to me that your ajax call doesn't returns anything about the product you've created.
Maybe something like this?
public function product(Request $request) {
// ...
return response()->json($prod->toArray(), 200);
}

Related

laravel link href click to save some data

Preview Your File
here link click to open pdf its fine but i want to insert some data when click this link how to insert and how to pass data laravel
You can do this in two methods
1: Using Ajax:
First insert your data then in the success redirect to your file .
2: using controller to redirect you to the file
use form to submit the data you want to controller then via controller redirect it to your file after adding data to database
something like this
public function AddDataToDatabase(Request $request)
{
$datas=New DataModal();
$datas->name = $request->name;
$datas->address = $request->address;
$datas->lastName = $request->lastName;
$datas->email = $request->email;
$data->save();
$items=Attachments::where('id',1)->get();
return redirect('Attachments/'.$items[0]->attachmentName);
}
or Using Ajax
$.ajax({
type: "POST",
url: your_URL,
data: {
'name':'your_name',
'id':'your_id',
'email':'your_email',
},
success: function(data) {
window.location = 'https://localhost/sample.pdf';
},
error: function(e) {
console.log(e);
}
});
then in your controller create a new method like this:
public function AddDataToDatabase(Request $request)
{
$datas=New DataModal();
$datas->name = $request->name;
$datas->address = $request->address;
$datas->lastName = $request->lastName;
$datas->email = $request->email;
$data->save();
return response()->json(['msg' => 'added successfully'],200);
}
Instead of a link, create form that contains the fields that you want to store in database. Make the fields hidden if they won't be filled by the user. Then submit the form to a controller. Store the data, redirect to a new path that will display the pdf.

Laravel Autocomplete using Jquery is not fetching data if the table column name isn't 'name'

I am using Jquery and Laravel 5.7 to make an autocomplete feature.
I have a table named 'pricings' there is no column in that table named 'name'. When I search through a keyword it returns nothing.
<script>
$(document).ready(function() {
$( "#search" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "{{url('autocomplete')}}",
data: {
term : request.term
},
dataType: "json",
success: function(data){
var resp = $.map(data,function(obj){
//console.log(obj.city_name);
return obj.name;
});
response(resp);
}
});
},
minLength: 1
});
});
</script>
Here is my Controller:
public function search(Request $request)
{
$search = $request->get('term');
$result = DB::table('pricings')->where('title', 'LIKE', '%'.$search.'%')->get();
return response()->json($result);
}
Table Data
Data in my table
output
output
But if I change my table Column name from TITLE to NAME
It returns data
If there is no column named 'name' how can I fetch data from any column?
In the success callback of your ajax, you are checking for name, you should instead be looking for title which is the column in your Database Table.
success: function(data){
var resp = $.map(data,function(obj){
//console.log(obj.city_name);
return obj.title; //This should be title instead of name.
});

How to parse an object passed by an AJAX?

I made an Ajax POST request into my Laravel function however i am facing this result:
<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style')
This happens when i die and dump my data so as to see what i get from ajax request. I have this jquery method:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#save-person').on('click', function() {
let first_name = $('#first_name').val();
let middle_name = $('#middle_name').val();
let third_name = $('#third_name').val();
let family_name = $('#family_name').val();
$.ajax({
url: urlReq+"/api/employee/customize",
type: "POST",
data: {
first_name: first_name,
middle_name: middle_name,
third_name: third_name,
family_name: family_name,
},
cache: false,
success: function(dataResult){
console.log(dataResult);
let data = dataResult;
if(data.statusCode==200){
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
});
and on my php method i have this:
public function customize_store(Request $request){
//dd($request->first_name);
$input = $request->all();
dd($input);
return response()->json(['Person'=>$input]);
}
which result to <script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx =... but my input are also present there that looks like this:
#<span class=sf-dump-protected title="Protected property">parameters</span>: <span class=sf-dump-note>array:15</span> [<samp>
"<span class=sf-dump-key>first_name</span>" => "<span class=sf-dump-str title="7 characters">Michael</span>"
"<span class=sf-dump-key>middle_name</span>" => "<span class=sf-dump-str title="6 characters">Sangga</span>"
"<span class=sf-dump-key>third_name</span>" => <span class=sf-dump-const>null</span>
"<span class=sf-dump-key>family_name</span>" => "<span class=sf-dump-str title="7 characters">Smith</span>"
How would i extract those data so that i can persist it on my database?
Try this code.. check the URL, Routes on which you are sending your
data..
public function addPersonData(Request $request){
$save_person = new Person(); // Initialize your model here..
$save_person->first_name = $request->get('first_name');
$save_person->middle_name = $request->get('middle_name');
$save_person->third_name = $request->get('third_name');
$save_person->family_name = $request->get('family_name');
$save_person->save();
return 'ok';
}
I think I got it. First add a name to your route (see here) and the ajax part in your jQuery (assuming you use a form to submit the user data):
in your Route.php add:
Route::post('api/employee/customize', 'PersonController#customize_store')->name('api.employee.customize');
Your jQuery ajax request:
$('#save-person').submit(function(e) {
e.preventDefault();
let first_name = $('#first_name').val();
let middle_name = $('#middle_name').val();
let third_name = $('#third_name').val();
let family_name = $('#family_name').val();
$.ajax({
url: "{{ route('api.employee.customize') }}",
type: "POST",
data: { first_name, middle_name, third_name, family_name },
cache: false,
success: function(data){
console.log(data);
if(data.status === 'success'){
$("#success").show();
$('#success').html('Data added successfully !');
//the person's details are in data.person.first_name etc
//you already knew that, but added is the new data.person.id you may use
}
else {
alert("Error occured !");
}
}
});
});
and your controller, assuming the model linked to this data is Person:
public function customize_store(Request $request){
$person = new Person($request->all());
if ($person->save()) {
return response()->json(['status' => 'success', 'person'=>$person]);
}
return response()->json(['status' => 'fail']);
}

Delete a row from the database via ajax

I have this javascript function to delete the row but the function is not working
$(document).ready(function()
{
$('table#example td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "supprimerkpi",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
// sets specified color for every odd row
$('table#example tr:odd').css('background',' #FFFFFF');
}
});
}
});
and in my page html:
<a href="#" class="delete" style="color:#FF0000;">
in my controller
$repository = $this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi'); $id=$this->getRequest()->query->get('id');
$em = $this->getDoctrine()->getEntityManager();
$uti=$repository->findOneBy(array('id' => $id));
$em->remove($uti);
$em->flush();
You are sending the "id" via POST method. So, you need to change:
$id=$this->getRequest()->query->get('id');
into:
$id=$this->getRequest()->request->get('id');
Also, you could change:
$uti=$repository->findOneBy(array('id' => $id));
into:
$uti=$repository->find($id);
.. as find() searches entity using the primary key...
On a side note, what is "supprimerkpi"? That can't be a valid destination URL, right? :)
In your routing.yml
delete_data:
path: /delete
defaults: { _controller: AcmeDemoBundle:Default:delete}
in your ajax call url parameter change that according to this
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "{{ path('delete_data') }}",
data: {id :id },
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
// sets specified color for every odd row
$('table#example tr:odd').css('background',' #FFFFFF');
}
});
in your AcmeDemoBundle/Controller/DeafultControlller.php
public function deleteAction(Request $request)
{
$id = $request->get('id');
$repository =
$this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi');
$em = $this->getDoctrine()->getEntityManager();
$uti=$repository->findOneById($id);
$em->remove($uti);
$em->flush();
}

How to post multiple data through $.ajax to Codeigniter controller method

this is the method I want to send data to it
function get_lesson($reshte,$poodeman){
$this->load->model('dropdown_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->dropdown_model->get_lessons($reshte,$poodeman)));
}
and this is the get_lessens() function in the model file.
function get_lessons($reshte = null, $poodeman=NULL){
$this->db->select('rlessid, title');
if($reshte != NULL AND $poodeman!= NULL ){
$this->db->where('reshteid', $reshte);
$this->db->where('poodemanid', $poodeman);
}
$query = $this->db->get('tbllessons_root');
$lessons = array();
if($query->result()){
foreach ($query->result() as $lesson) {
$lessons[$lesson->rlessid] = $lesson->title;
}
return $lessons;
}else{
return FALSE;
}
}
and this is my ajax call at the view file
var reshteid = $('#reshte').val();
var poodemanid = $('#poodemanha').val();
$.ajax({
type:"POST",
url:"http://localhost/crud-grocery/index.php/examples/get_lesson/",//+reshte+"/"+poodeman,
data: "reshte="+reshteid+"&poodeman="+poodemanid,
success: function(lessons)
{
$.each(lessons,function(rlessid,title){
var opt = $('<option />');
opt.val(rlessid);
opt.text(title);
$('#lessons').append(opt);
});
}
});
as you see I am trying to chain options in the form
but The problem comes up when I try to post (send) two parameters to the controller method
any idea?
In your controller, you need to get POST values not as parameters:
//in controller
function get_lessons(){
...
//get POST values
$reshte = $this->input->post('reshte');
$poodeman = $this->input->post('poodeman');
You have to pass data as a javascript object literal:
...
data: {
reshte: reshteid,
poodeman: poodemanid
}
....

Resources