How to parse an object passed by an AJAX? - 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']);
}

Related

Ajax update field database field in laravel blade template

I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);

Uploading an image in Laravel via Ajax

I am trying to update an "article" which include title(text), body(textarea) and image(file). All goes well until i tried to implement uploading via ajax. Uploading image through regular Laravel means works great, but with ajax, i hit little snag. First, it refuses to validate file. Second if i comment-out validation for file in controller method, it goes "sort-of" well ... But then check $request->hasFile("image") doesn't recognize file at all ... so instead writes to db an default one("noimage.jpg"). My other ajax functions work great, only update causing problems.
Here is ajax function:
function ajaksUpdate(){
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
console.log("hitUpdate");
//console.log();
let updateForm = document.getElementById("updateForm");
let urlId = window.location.href;
let getaArticleId = urlId.lastIndexOf("/");
let articleId = urlId.substring(getaArticleId+1, urlId.length);
let updateFormElements = {};
updateFormElements.title = updateForm.elements[3].value;
updateFormElements.body = CKEDITOR.instances.ckeditor.getData();//Ovo trece po redu je id polja sa ckeditorom.
updateFormElements.image = updateForm.elements[5].files[0];
//console.log();
/*var myformData = new FormData();
myformData.append('title', updateFormElements.title);
myformData.append('body', updateFormElements.body);
myformData.append('image', updateFormElements.image);
let formData = $('#updateForm').serializeArray();
console.log(updateFormElements);*/
console.log("******");
/*for (var [key, value] of myformData.entries()) {
console.log(key, value);
}*/
$.ajax({
url: '/updateAjax/'+articleId,
enctype: 'multipart/form-data',
type: 'POST',
data: {_token: token , message: "bravo", articleId: articleId, title: updateFormElements.title, body: updateFormElements.body,image:updateFormElements.image},
dataType: 'JSON',
/*cache: false,
contentType: false,
processData: false,*/
success: (response) => {
console.log("success");
console.log(response);
},
error: (response) => {
console.log("error");
console.log(response);
}
});
}
Here is controller method:
public function ajaxUpdate(Request $request)
{
if($request->ajax()){
$article = Article::find($request->articleId);
$validator = \Validator::make($request->all(), [
"title" => "required",
"body" => "required",
'image' => 'image|nullable|max:1999'/*If commented, validation passes.*/
]);
if ($validator->passes()){/*If validation passes, it cannot find 'image'*/
$hasImage = false;
//Handle file upload
if($request->hasFile("image")){
$filenameWithExt = $request->file("image")->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file("image")->getClientOriginalExtension();
$fileNameToStore = $filename."_".time().".".$extension;
$path = $request->file("image")->storeAs("public/images", $fileNameToStore);
}
else{
$fileNameToStore = "noimage.jpg";
}
$article->title = $request->input("title");
$article->body = $request->input("body");
//$article->user_id = auth()->user()->id;
$article->image = $fileNameToStore;
$article->save();
$response = array(
'status' => 'success',
'msg' => "Hello!",
"request" => $request->all(),
"passesValidation" => true,
"article" => $article,
"hasImage" => $hasImage,
);
return response()->json($response);
}
else{
$response = array(
'status' => 'success',
'msg' => "Hello!",
"request" => $request->all(),
"passesValidation" => false,
);
return response()->json($response);
}
}
}
Edit1:
If validation(for image) in controller isn't commented out, it shows string like this: "C:\fakepath\855d671944d2c143ba672010acd04437.jpg".
Json if isn't commented out:
{
msg: "Hello!"
passesValidation: false
request:
articleId: "3"
body: "posttext"
image: "C:\fakepath\855d671944d2c143ba672010acd04437.jpg"
message: "bravo"
title: "Post1"
_token: "ZVZ9NDNOcMdgoJgvzYhR9LmrPfh7RfMiM1QJVk9v"
__proto__: Object
status: "success"
__proto__: Object
}
If commented out, json look like this:
{
article: {id: 3, title: "Post1", body: "<p><em>Lorem ipsum</em><strong> </strong>dolor sit…ctum. Duis feugiat facilisis lectus a cursus.</p>", created_at: "2019-06-18 00:23:25", updated_at: "2019-06-25 00:18:37", …}
hasImage: false
msg: "Hello!"
passesValidation: true
request:
articleId: "3"
body: "posttext"
image: "C:\fakepath\855d671944d2c143ba672010acd04437.jpg"
message: "bravo"
title: "Post1"
_token: "ZVZ9NDNOcMdgoJgvzYhR9LmrPfh7RfMiM1QJVk9v"
__proto__: Object
status: "success"
__proto__: Object
}
Edit2:
I also tried:
let formData = new FormData();
formData.append("title", updateFormElements.title);
formData.append("body", updateFormElements.body);
formData.append("image", updateFormElements.image);
and inserting and sending it. It throws "Illegal invocation at .... ". And for whatever reason, formData object is empty when i console.log(formData) it.
Edit3:
Even if i add processData: false, in ajax call. But then it throws 419 error ...
Edit4:
I don't know if it's going to help, but my form is in modal, there is no submit button and button with ajaksUpdate() function is the one who submits/updates and it's outside of form. I'm updating with put method, also got csrf in modal's form.
Here is a image of how my form/modal looks like:
Edit5:
As per #pal request:
My html is formed dynamically, in another function which is called when document is loaded, in layouts blade:
function ajaksShow(){
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
console.log("hit");
//var n = str.lastIndexOf("planet");
let urlId = window.location.href;
let getaArticleId = urlId.lastIndexOf("/");
let articleId = urlId.substring(getaArticleId+1, urlId.length);
console.log(articleId);
$.ajax({
url: '/showAjax',
type: 'POST',
data: {_token: token , message: "bravo", articleId: articleId},
dataType: 'JSON',
success: (response) => {
console.log("success");
console.log(response);
let body = "";
let imageStyle = ";height: 435px; background-position: center top; background-attachment: fixed; background-repeat: no-repeat;background-size:cover;";
let img = response.article.image;
let find = " ";
let rep = new RegExp(find, 'g');
img = img.replace(rep, "%20"); // class="alert alert-danger"
let mymodalDelete = "<div class='modal' id='myModalDelete'><div class='modal-dialog'><div class='modal-content'><div class='modal-header'><h4 class='modal-title'>Do you really want to delete this article?</h4><button type='button' class='close' data-dismiss='modal'>×</button></div><div class='modal-body'>deleting ...</div><div class='modal-footer'><button class='btn btn-outline-danger' style='position: absolute;left:0px; margin-left: 1rem;' onclick='ajaksDelete(this)'>Delete</button><button type='button' class='btn btn-danger' data-dismiss='modal'>Close</button></div></div></div></div>";
let updateForm = "<form method='POST' id='updateForm' enctype='multipart/form-data'><input type='hidden' name='_method' value='PUT'><input type='hidden' name='_token' value='"+token+"'><input id='' type='hidden' name='article_id' value='"+response.article.id+"' /><div class='form-group'><label class='label' for='title'>Title</label><input type='text' class='form-control' name='title' placeholder='Title' value='"+response.article.title+"' required></div><div class='form-group'><label for='body'>Body</label><textarea class='form-control' id='ckeditor' name='body' placeholder='Body' required>"+response.article.body+"</textarea></div><div class='form-group'><input type='file' name='image' id='image'></div></form>";
let mymodalUpdate = "<div class='modal' id='myModalUpdate'><div class='modal-dialog'><div class='modal-content'><div class='modal-header'><h4 class='modal-title'>Do you really want to update this article?</h4><button type='button' class='close' data-dismiss='modal'>×</button></div><div class='modal-body'>"+updateForm+"</div><div class='modal-footer'><button class='btn btn-outline-success' style='position: absolute;left:0px; margin-left: 1rem;' onclick='ajaksUpdate()'>Update</button><button type='button' class='btn btn-info' data-dismiss='modal'>Close</button></div></div></div></div>";
let imageUrl = "/storage/images/"+img;
let html = "<a href='/list' class='btn btn-outline-info btn-sm'>Go Back</a><div class='nextPrev'><a href='/list/"+response.prev+"' class='btn btn-outline-success'><i class='fas fa-arrow-left'></i></a><a href='/list/"+response.next+"' class='btn btn-outline-info'><i class='fas fa-arrow-right'></i></a></div><br><br><div id='single-kv' style='background-image: url("+imageUrl+")"+imageStyle+";background-color: red !important;'></div><div id='single-intro'><div id='single-intro-wrap'><h1> "+response.article.title+"</h1>";
if(response.article.body.length > 400){
body = response.article.body.substring(0, 400)+"<a id='readMore' href='/list/"+response.article.id+"'>...Read more</a>";
}
else{
body = response.article.body;
}
html += body;
html += "<div class='comment-time excerpt-details' style='margin-bottom: 20px; font-size: 14px;'><a href='#gotoprofil'> "+response.user.name+" </a> - "+response.article.created_at+"</div><button id='update' class='btn btn-outline-info btn-sm float-left' data-toggle='modal' data-target='#myModalUpdate' onclick='getCkEditor()'>Update</button><button class='btn btn-outline-danger btn-sm float-right' data-toggle='modal' data-target='#myModalDelete'>Delete</button></div></div><br><hr style='color:whitesmoke; width: 50%;'><div id='single-body'><div id='single-content'>"+response.article.body+"</div></div>"+mymodalDelete+mymodalUpdate;
if(document.getElementById("maine")){
document.getElementById("maine").innerHTML = html;
}
},
error: (response) => {
console.log("error");
console.log(response);
}
});
}
Form is updateForm variable and button that activate it, is in mymodalUpdate variable where it invokes function ajaksUpdate(). Also updateForm is chained in mymodalUpdate with two pluses on each side.
Edit6:
I also tried:
let formData = $('#updateForm').serializeArray();
console.log(formData);
but it's only shows csrf, hidden method put field,token, title and body field. No file field?.
Edit7:
Here is two pics that'll(i hope) help to illustrate my point:
and second
Edit8:
Somebody suggested it was a csrf mismatch concerning 419 error, so they suggested to temporary disable csrf to see what's what, here are pics:
Logged and middleware:
and logged and controller method:
Updated with change ajax function. If i add to ajax call
cache: false,
contentType: false,
processData: false,
then it show: "POST http://articleapp.test/updateAjax/3 419 (unknown status)" error. If comment this three lines out, then it shows: "Uncaught TypeError: Illegal invocation
at add ..." error. I tried everything. and csrf ain't it because i tried disabling, it sends blank request.
Final edit:
I don't know what i did, but file uploading works.
Here is ajax function:
function ajaksUpdate(){
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
console.log("hitUpdate");
//console.log();
let updateForm = document.getElementById("updateForm");
let urlId = window.location.href;
let getaArticleId = urlId.lastIndexOf("/");
let articleId = urlId.substring(getaArticleId+1, urlId.length);
let updateFormElements = {};
updateFormElements.title = updateForm.elements[3].value;
updateFormElements.body = CKEDITOR.instances.ckeditor.getData();//Ovo trece po redu je id polja sa ckeditorom.
updateFormElements.image = updateForm.elements[5].files[0];
let imginp = document.getElementById("imagex").files;
//console.log(imginp);
var myformData = new FormData();
myformData.append('title', updateFormElements.title);
myformData.append('body', updateFormElements.body);
myformData.append('image', updateFormElements.image);
myformData.append('_token', token);
myformData.append('articleId', articleId);
//let formData = $('#updateForm').serializeArray();
console.log("******");
for (var [key, value] of myformData.entries()) {
console.log(key, value);
}
console.log("======");
$.ajax({
url: '/updateAjax/'+articleId,
enctype: 'multipart/form-data',
type: 'POST',
data: myformData,
dataType: 'JSON',
cache: false,
contentType: false,
processData: false,
success: (response) => {
console.log("success");
console.log(response);
},
error: (response) => {
console.log("error");
console.log(response);
}
});
}
Here is controller method:
public function ajaxUpdate(Request $request)
{
if($request->ajax()){
$article = Article::find($request->articleId);
$validator = \Validator::make($request->all(), [
"title" => "required",
"body" => "required",
'image' => 'image|nullable|max:1999'
]);
if ($validator->passes()){
$hasImage = false;
//Handle file upload
if($request->hasFile("image")){
$filenameWithExt = $request->file("image")->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file("image")->getClientOriginalExtension();
$fileNameToStore = $filename."_".time().".".$extension;
$path = $request->file("image")->storeAs("public/images", $fileNameToStore);
}
else{
$fileNameToStore = "noimage.jpg";
}
$article->title = $request->input("title");
$article->body = $request->input("body");
//$article->user_id = auth()->user()->id;
$article->image = $fileNameToStore;
$article->save();
$response = array(
'status' => 'success',
'msg' => "Hello!",
"request" => $request->all(),
"passesValidation" => true,
"article" => $article,
"hasImage" => $hasImage,
);
return response()->json($response);
}
else{
$response = array(
'status' => 'success',
'msg' => "Hello!",
"request" => $request->all(),
"passesValidation" => false,
);
return response()->json($response);
}
}
}
Just want to leave this here for posterity and to ask others: Did you ever encountered problem, which miraculously resolved, but you've been none the wiser about solution whatever it may be?
Well it seems that you're uploading the local path to your image instead of the image itself in the Ajax method. Reading this part of MDN documentation I realized you might write this:
updateFormElements.image = updateForm.elements[5].files[0];
Instead of this
let formData = new FormData();
formData.append("title", updateFormElements.title);
formData.append("body", updateFormElements.body);
formData.append("image", updateFormElements.image);
use this
var formData = new FormData(this);
Full source as below as you have generate from dynamically Please use event binding instead if directly give click events:
Please check this out
event binding
just give button like this:
Submit
button out side the from can be part of from check out this button outside form
<script>
$(document).ready(function (e) {
$('#updateBtn').on('submit',(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ url('save-image')}}",
data:formData,
success:function(data){ },
error: function(data){}
});
}));
});
To upload file using ajax, try this:
var fileData = $('#id_of_file').prop('files')[0];
var formData = new FormData(); // Create formdata object
formData.append('fileData', fileData); // append key: value pair in it
formData.append('key1', value1);
formData.append('key2', value2);
and use it in ajax like:
$.ajax({
url: $('meta[name="route"]').attr('content') + '/ur_route',
method: 'post',
data: formData,
contentType : false,
processData : false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response){
// do whatever you want
}
});
on server side (controller) you will get the file using fileData index.

codeigniter form validation with anchor tag click

I want to validate some form fields without submitting the form.
Here is my code if someone can help.
View:
<form>
<input type="text" name="first_name" placeholder="First Name..." class="textfield">
<a href="javascript:void();" onClick="validateName();">
</form>
Script:
function validateName(){
var first_name = $('.textfield').val();
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: first_name,
dataType:"json",
success: function(response){
var obj = eval(response);
if(obj.error==0){
console.log('Success');
}
else{
console.log('Failed');
}
}
});
}
Controller:
public function contAjax(){
// loading form validation library //
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name', 'required');
if($this->form_validation->run()== TRUE){
echo json_encode(array('error' => 0));
}
else{
echo json_encode(array('error' => 1));
}
}
It always returns error=1 and form validation is not working...
This is untested code... but should work ( he said with a grin )
function validateName() {
var first_name = $('.textfield').val();
console.log('first_name is ' + first_name); // Check it's getting this far
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: {first_name: first_name},
dataType: "json",
success: function (response) {
if (response.error == 0) {
console.log('Success');
}
else {
console.log('Failed');
}
}
});
}
So with the addition of the console.log you can easily inspect your value...
I am not a big fan of using capitals in urls ( only works on windows and can lead to tears on a linux / apache server ) so best to use lowercase.
Just to add some more debug to this the simplish way you could inspect what the server side sees you posting...
This is just a way to check your posted values ( using something like firebug or similar is far better...)
function contAjax() {
// loading form validation library //
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name', 'required');
$first_name = $this->input->post('first_name');
if ($this->form_validation->run() == TRUE) {
echo json_encode(array('error' => 0, 'first_name' => $first_name));
} else {
echo json_encode(array('error' => 1, 'first_name' => $first_name));
}
}
And your JS would become...
function validateName() {
var first_name = $('.textfield').val();
console.log('first_name is ' + first_name); // Check it's getting this far
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: {first_name: first_name},
dataType: "json",
success: function (response) {
if (response.error == 0) {
console.log('Success - First Name = ' + response.first_name);
}
else {
console.log('Failed - First Name = ' + response.first_name);
}
}
});
}
The trick is to know how to "see" what is happening which makes debugging these kinds of things of lot easier...
Hope that helps. Again this code is untested but shows the principal...

Ajax response Not working in Codeigniter

I want to show tick.png image on clicking save button when data inserted in database successfully. My view file name is insert_your_committee, model is users_model & controller user
Here is my code of all there files:
My Script of my insert_your_commitee file, All console.log show correct result but success function is not working. What is the problem?
<script>
function save_committee($c_id,$m_id,$start_date){
console.log($c_id);
console.log($m_id);
console.log($start_date);
var mid=$('#irnum'+$start_date).val();
console.log("df"+mid);
var url= "<?php echo site_url("user").'/ref_add';?>";
$.ajax({
url: url,
type: "POST",
dataType:'json',
data: {c_id:$c_id,m_id:$m_id,start_date:$start_date,irnum:mid},
success: function(data){
console.log(data);
$('#'+$start_date).show();
$('#btn'+$start_date).hide();
}
});
}
</script>
My Controller
public function ref_add()
{
$this->load->model('Users_model');
$parms=$this->input->post();
$c_id=$this->input->post('c_id');
$m_id=$this->input->post('m_id');
$s_dateparms=$this->input->post('start_date');
$irnum=$this->input->post('irnum');
$data_to_store = array(
'Cid' =>$c_id,
'Mid' =>$m_id,
'Month' => $s_dateparms,
'Year'=>$s_dateparms,
'Ref_Number' =>$irnum,
);
$params=array();
if ($this->users_model->add_ref($data_to_store)) {
$params['status'] = TRUE;
} else {
$params['status'] = false;
}
$return["json"] = json_encode($params);
echo json_encode($return);
}
And Here is my model
function add_ref($data)
{
$this->db->insert('reference', $data);
$report = array();
$report['error'] = $this->db->_error_number();
$report['message'] = $this->db->_error_message();
if($report !== 0){
return true;
}else{
return false;
}
}
I am not completely sure, but in order to get ajax to work, I had to add return false; after the ajax call in the function.
In my case, I was using ajax for login and backend was in codeigniter.

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();
}

Resources