Upload image to database in laravel 5 using eloquent ORM? - laravel

I have one form which contains one file upload.
Form Id is "upload_form"
<input type="file" id="image" name="image"/>
Using javascript onclick function and ajax to pass the image to the controller.
Ajax fn:
$.ajax({
url: 'UploadImage',
data:new FormData($("#upload_form")[0]),
type: "post",
dataType:"JSON",
async:false,
success: function (data) {
console.log(data);
}
});
}
Routes:
Routes::post('UploadImage','UploadController#Upload');
UploadController:
public function Upload()
{
$file = Input::file('image');
$tmpFilePath = '/temp/uploads/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$path = $tmpFilePath.$tmpFileName;
$data_file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
// Error for move() and getClientOriginalName() functions.
}

use this and it should work for you ... :)
<form action="" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" id="image" name="image"/>
<input type="submit" value="Upload" name="submit">
</form>

Thanks #GONG.
Changed my form to this. Worked.
<form enctype="multipart/form-data" id="upload_form" role="form" method="POST" action="" >

Related

After form submit redirect without refresh using Ajax in laravel 8

I am developing multi Step Form Submit without refresh. collect the data from 1st step 2nd step collect some date, 3rd step collect some date & finally submit data in the database. Can you tell me how to fix this.
My blade template.
<form id="post-form" method="post" action="javascript:void(0)">
#csrf
<div>
<input class="form-input" type="text" id="ptitle" name="ptitle" required="required"
placeholder="What do you want to achieve?">
</div>
<button type="text" id="send_form" class="btn-continue">Continue</button>
</div>
</form>
Ajax Script
$(document).ready(function() {
$("#send_form").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var ptitle = $('#ptitle').val();
$.ajax({
url: "{{route('create.setp2') }}",
method:'POST',
data: {_token:_token,ptitle:ptitle},
success: function(data) {
alert('data.success');
}
});
});
Web.php router
Route::post('/setp2', [Abedoncontroller::class, 'funcsetp1'])->name('create.setp2');
Controller method
public function funcsetp1(Request $request) {
$postdata=$request->input('ptitle');
return response()->json('themes.abedon.pages.create-step-2');
}

Success function not being called after making AJAX request codeigniter

When I make an AJAX call from view and pass form data to the controller. I get a couple of problems. First, the code inside success is never executed, and second, the page is being refreshed even though it is an AJAX call. Can anyone tell me where am I doing wrong?
I have seen a lot of questions since yesterday but none of them were able to solve my problem.
Model code
public function insert_user($name, $email) {
$data = array();
$data['name'] = $name;
$data['email'] = $email;
$data['created_at'] = date('y-m-d');
$this->db->insert('all_users', $data);
return true;
}
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$this->User_model->insert_user($name, $email);
$this->load->view('view');
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
My form looks something like this:
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
NOTE: I am able to successfully insert data into the database.
The browser is submitting the form before your AJAX code gets a chance to run/finish.
Instead of binding an event to the click event of the button, you want to bind to the submit event of the form. Then you want to cancel the browser's default action. This is done via the e.preventDefault(); method.
Also, dataType: "json" is not needed here. dataType tells jQuery what kind of data your AJAX call is returning. You generally don't need it as jQuery can automatically detect it. Plus, if you are not returning a JSON document, then this may cause a problem.
const insertForm = $(".insert-form");
insertForm.on("submit", function (e) {
const name = insertForm.find("input[type=name]");
const email = insertForm.find("input[type=email]");
e.preventDefault();
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
success: function () {
$("body").append("Request made successfully");
}
})
});
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$data = $this->User_model->insert_user($name, $email);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>Users/insert_user", // <?php echo base_url() ?>controller_name/function_name
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
form looks something like this:
<form class="insert-form" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
The page was being refreshed because I had a button that was acting as submit button on changing it to the input of the type button it does not submits the form and we don't see the page being refreshed. And also the AJAX request made also runs successfully.
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<input type="button" class="insert-btn" value="Insert Data">
</form>

How to save the content of a textarea using Ckeditor and CodeIgniter?

I'm using Codeigniter with Ckeditor. My problem is that when I submit the content, the data from the textarea is not stored in the database. But when I tried it again it finally did. So the situation is like I have to double click submit button to save it.
I stored the downloaded Ckeditor on a folder named ./Assests/Ckeditor(Sorry for the wrong spelling.I'll fix this later.)
Here's my form in my view folder:
ask_view.php:
<form id="form" enctype="multipart/data" method="post" onsubmit="createTextSnippet();">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name ="title" class="form-control" id="title" placeholder="Title" required >
</div>
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
<div class="form-group">
<label for="exampleInputEmail1">Editor</label>
<textarea name ="text" class="form-control" id="text" rows="3" placeholder="Textarea" required></textarea>
</div>
<input type="submit" class="btn " name="submit" value ="Submit" style="width: 100%;background: #f4a950;color:#161b21;">
</form>
<script src="<?php echo base_url('assests/js/editor.js')?>"></script>
<script type="text/javascript">
CKEDITOR.replace('text' ,{
filebrowserBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserUploadUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserImageBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=1&editor=ckeditor&fldr=')?>'
}
);
</script>
<script type="text/javascript">
//code used to save content in textarea as plain text
function createTextSnippet() {
var html=CKEDITOR.instances.text.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
var snippet=plain_text.substr(0,500);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/knowmore2/index.php/ask_controller/book_add',
data: $('form').serialize(),
success: function (data) {
console.log(JSON.parse(data));
}
});
});
</script>
Ask_model.php:
public function book_add($data)
{
$query=$this->db->insert('article', $data);
return $query;
}
Ask_controller.php:
public function book_add(){
$data = $_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
echo json_encode($details);
}
The content with html tags should be save in a column named content in the database, but it didn't save in the first click. It only saves on the second one,but the other data are saved in the first like the title, etc. So I get 2 rows of data, one without the content and the other with one.
Database:

commenting module by ajax not working in laravel 5

i am working on commenting module in my project by ajax. i am getting this error
POST http://127.0.0.1:8000/comments 500 (Internal Server Error)
and the data not post. what i am doing wrong? My route is a resource route and i want to display it without refreshing the page .
Form
<form action="{{route('comments.store')}}" method="post">
{{ csrf_field() }}
<div class="col-md-11 col-sm-11">
<div class="form-group">
<textarea name="comment-msg" id="comment-name" cols="30" rows="1" class="form-control" placeholder="comment here..."></textarea>
<input type="hidden" id="eventID" name="eventID" value="<?php echo $eventData->id; ?>">
<input type="hidden" id="userID" name="userID" value="<?php echo Auth::user()->id; ?>">
</div>
</div>
<div class="col-md-12">
<button type="submit" id="submit-comment" class="btn-primary pull-right">Comment</button>
</div>
</form>
Ajax Call
<script>
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});
$( '#submit-comment' ).click(function() {
var formData = {
'message' : $('#comment-msg').val(),
'eventID' : $('#eventID').val(),
'userID' : $('#userID').val(),
};
$.ajax({
type : 'POST',
url : '{{route('comments.store')}}',
data : formData,
dataType : 'json',
encode : true,
success: function (response) {
console.log(response);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
event.preventDefault();
} );
</script>
Controller
public function store(Request $request)
{
$content = $request->input( 'comment-msg' );
$userID = $request->input( 'userID' );
$eventID = $request->input( 'eventID' );
$response=Comment::create([
'user_id' => $userID,
'event_id' => $eventID,
'message' => $content,
]);
return response()->json($response);
}
Route
Route::resource('comments', 'CommentsController');

Ajax call back: Return variable as input value

After ajax call back I need to echo out a variable as value of hidden field.
HTML
<form ajax1>
<input name="Place" value="Milan">
<input name=submit onclick="return submitForm1()">
</form>
<form ajax2>
<input type="hidden" value="$place">
<input name="filter">
<input name=submit onclick="return submitForm2()">
</form>
<div id="result"></div>
Ajax Call
function submitForm1() {
var form1 = document.myform1;
var dataString1 = $(form2).serialize();
$.ajax({
type:'GET',
url:'query.php',
cache: false,
data: dataString1,
success: function(data){
$('#results').html(data);
}
});
return false;
}
PHP
<?
$place= $_GET['Place']
//do stuffs
?>
It works perfectly, but now I need to add a function to echo out $place in value=" " of form ajax2
Any help appreciated

Resources