Uploading an image in Laravel via Ajax - 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.

Related

laravel7 working image upload but ajax says there's error

So I'm doing an image upload via modal and ajax. It is working, it is saved in the database and saved in public folder as an image, except that the modal does not hide because there's something wrong as said in the console.
statusCode: ƒ ( map )
statusText: "OK"
AJAX:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//ADD PICTURE
$('#btnUpload').click(function(){
$('#uploadModal').modal('show');
});
$('#btnSave').click(function(){
$.ajax({
data: new FormData($('#uploadForm').get(0)),
url: "{{ route('gallery.store') }}",
type: "POST",
dataType: 'json',
contentType: false, // required for
processData: false, // jquery ajax file upload
success: function(data){
$successmessage = 'SUCCESSFULLY UPLOADED';
$('#uploadModal').modal('hide');
$('#successmessage').text($successmessage);
},
error: function(data){
console.log('Error:', data);
}
});
});
});
CONTROLLER:
public function store(Request $request)
{
$galleries=new Gallery;
// Handle File Upload
if($request->hasFile('upload')){
// Get filename with the extension
$filenameWithExt = $request->file('upload')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('upload')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'.'.$extension;
// Upload Image
$path = $request->file('upload')->storeAs('public/upload', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$galleries->description = $request->input('description');
$galleries->upload = $fileNameToStore;
$galleries->save();
}
In store function, you have to return response status code. In the case of success, you return 200.
return response()->json(['success' => 'success'], 200);
In the event of a failure, you return the code that corresponds to the error.
Example:
return response()->json(['error' => 'invalid'], 401);

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
]);

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']);
}

forbidden in ajax call error function in codeigniter csrf

I'm just getting started with codeigniter I want to insert some data into database via ajax but I have a problem with my ajax call;
I've been searching for two hours but I could not solve the problem.
My problem is when I click on submit button it says forbidden.
Also my csrf protection is set to TRUE! Please help, thanks
JS
$(document).ready(function() {
$(".addbtn").click(function (e) {
e.preventDefault();
if($("#mname").val()==='' ||
$('#sname').val() === '' ||
$('#genre').val()==='' ||
$('#album').val()==='' ||
$('#publishyear').val() ==='' ||
$('#artist').val()==='')
{
alert("Please fill all the fields!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var baseurl = "<?php echo base_url(); ?>";
var data = {
'mname': $("#mname").val(),
'sname': $('#sname').val(),
'genre': $('#genre').val(),
'album': $('#album').val(),
'publishyear': $('#publishyear').val(),
'artist': $('#artist').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>':
'<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: baseurl+"index.php/admin_page/send_ajax",
data: data,
success:function(){
alert("success");
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});});
Config file
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
Controller
public function send_ajax(){
$data = array(
'name_of_music'=>$this->input->post("mname", TRUE),
'artist'=>$this->input->post("artist", TRUE),
'name_of_singer'=>$this->input->post("sname", TRUE),
'genre'=>$this->input->post("genre", TRUE),
'album'=>$this->input->post("album", TRUE),
'publishyear'=>$this->input->post("publishyear", TRUE)
);
$json_data['lyrics_info_data'] = json_decode($data);
$this->user_model->insert_json_in_db($json_data);
}
Model
public function insert_json_in_db($json_data){
$this->db->insert('lyrics', $json_data);
}
Can you confirm what is the use of this line $json_data['lyrics_info_data'] = json_decode($data); ? I think error is with this line.
You may use $json_data['lyrics_info_data'] = $data; instead of $json_data['lyrics_info_data'] = json_decode($data);
Also the model function need to update.
public function insert_json_in_db($json_data){
$this->db->insert('lyrics', $json_data['lyrics_info_data']);
}
Script update
Codeigniter will regenerate its crcf token on each request and this info will be stored in cookie. So token value you need to take from cookie and send along with ajax data you are passing. What I am doing with folliwing javascript is that, using a common function to attach crcf value along with all the ajax request.
In jquery there is an option to add custom data along with ajax request.
See jquery documentation http://api.jquery.com/jquery.ajaxprefilter/ for more details
<script>
$(document).ready(function(){
function getCookie(c_name) { // A javascript function to get the cookie value
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if(c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if(c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
$.ajaxPrefilter(function(options, originalOptions, jqXHR){ // This function will attach "csrf_test_name" with all the request you are sending.
if (options.type.toLowerCase() === "post") { // Required only if its a post method
var csrf_token = getCookie("csrf_test_name");
// initialize `data` to empty string if it does not exist
options.data = options.data || "";
// add leading ampersand if `data` is non-empty
options.data += options.data?"&":"";
// add _token entry
options.data += "csrf_test_name=" + csrf_token;
}
});
});
</script>
You can remove '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>' from var data.
Important note: if you change $config['csrf_token_name'] = 'csrf_test_name'; in config.php then you need to update this script as well.
Please try after updating your code and let me know if issues still exists.
Make Sure you are getting right base_url() and in javascript you should define the base_url() globally somewhere so that you can access it in any script as below
var baseurl = <?php echo base_url() ?>;
`
You are going way out of your way to make this difficult. csrf is not your problem. Try something like this
$(function () {
"use strict";
$("#form2").submit(function () {
var data = $("#form2").serialize();
//alert(data); return false;
$.ajax({
url: "/log/login",
data: data,
type: "POST",
success: function (msg) {
$("#display").text(msg);
},
error: function (msg) {
$("#display").text("its all bad");
}
});
return false;
});
});
(Of course you will need to put your own form id in etc)
Your controller should look something like this:
$data = array(
'borncity' => htmlspecialchars(trim($this->input->post('borncity'))),
'state' => htmlspecialchars(trim($this->input->post('state'))),
'country' => htmlspecialchars(trim($this->input->post('country'))),
'family' => htmlspecialchars(trim($this->input->post('family'))),
'year' => htmlspecialchars(trim($this->input->post('year'))),
'state1' => htmlspecialchars(trim($this->input->post('state1'))),
'deathcity' => htmlspecialchars(trim($this->input->post('deathcity')))
);
$this->form_validation->set_rules('borncity', 'city of birth', 'required|trim');
$this->form_validation->set_rules('state', 'state', 'required|trim');
$this->form_validation->set_rules('country', 'country', 'required|trim');
$this->form_validation->set_rules('family', 'family', 'required|trim');
$this->form_validation->set_rules('year', 'year', 'required|trim');
$this->form_validation->set_rules('state1', 'Born State', 'required|trim');
$this->form_validation->set_rules('deathcity', 'Death City', 'trim');
if( $this->form_validation->run() == FALSE) {
echo validation_errors();
}else
{
$this->db->insert('cities', $data);
echo "Success"; //this will show up in your ajax success line
}
}
Use Codeigniter's form validation in your controller. You do not need to use json decode. Please note these are examples

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