Getting Internal Server Error (500) - CodeIgniter - javascript

In my CodeIgniter project I need to insert data into db table, I am having
Internal server error (500)
issues to add data to database using Ajax.
My Ajax code is below,
$("#rsvp_form").validate({
rules: {
uname: {
required: true,
minlength: 8
},
uemail: "required",
umessage: {
required: true,
maxlength: 100
}
},
messages: {
uname: {
required: "Please enter your name",
minlength: jQuery.validator.format("At least 8 characters required!")
},
uemail: "Please enter your email",
umessage: {
maxlength: jQuery.validator.format("Please enter no more than 100 characters!")
},
},
// ajax request
submitHandler: function (form) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
// loader
$(".loader").show();
// ajax request
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Welcome/create_wish",
data: formData,
dataType: "json",
success: function (data) {
// if send data successfull
if (data.status === 'success') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-success").show("slow");
}, 300);
// if send data something wrong
} else if (data.status === 'error') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-error").show("slow");
}, 300);
}
}
});
return false;
}
});
My Welcome Controller function is below : ,
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_wish' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model_wishes Model is here,
function createWish($data) {
$this->db->insert("wishes", $data);
}
welcome_message View is,
<form id="rsvp_form" action="">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
When Post Wish button is clicked getting XHR failed loading: POST and an error
POST http://localhost/CodeIgniterProj/index.php/Welcome/create_wish 500 (Internal Server Error)
Please let me know what actually force to internal server error, and how could I fix this Issue.

You are using wrong post input, please check below updated code
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('user_name'),
'user_email' => $this->input->post('user_email'),
'user_wish' => $this->input->post('user_wish')
);
$this->model_wishes->createWish($data);
}

Hope this will help you :
Your submitHandler code should be like this :
submitHandler: function (form)
{
var formData = $(form).serialize();
$(".loader").show();
console.log(formData);
$.ajax({
type: "POST",
url: "<?=site_url('Welcome/create_wish'); ?>",
data: formData,
dataType: "json",
success: function (data) {
alert(data);
}
});
}
And your controller create_wish should be like this :
public function create_wish()
{
$this->load->model("model_wishes");
$user_name = $this->input->post('uname'));
$user_email = $this->input->post('uemail');
$user_wish = $this->input->post('umessage');
$data = array(
'user_name' => $user_name,
'user_email' => $user_email,
'user_wish' => $user_wish
);
$this->model_wishes->createWish($data);
$response = array('status' => 'success');
echo json_encode($response);
}

Instead of base_url use the site_url
site_url('Welcome/create_wish')

Related

ajax Uncaught ReferenceError: post is not defined at HTMLButtonElement.<anonymous>

Have no idea what it could be. Please help me release this ajax commentaries. I have never done this before. HTML form for input text and some ids:
<form id="send_comment" method="POST" action="write_comment.php">
<input hidden type="text" id="c_post_id" name="c_post_id" value="<?=$_GET["id"]?>">
<input hidden type="text" id="c_user_id" name="c_user_id" value="<?=$user_id?>">
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" type="text" id="c_text" rows="3" placeholder="Write comment here..." name="c_text" required pattern="^[a-zA-Z0-9\s]+$"></textarea>
</div>
<div class="col-md-12 text-center">
<button id="make_comment" class="btn btn-default" name="make_comment" type="submit" value="Submit"><i class="fas fa-check" style="font-size: 35px;"></i></button>
</div>
</form>
PHP processing:
if($_POST["make_comment"]) {
$c_post_id = $_POST["c_post_id"];
$c_user_id = $_POST["c_user_id"];
$c_text = $_POST["c_text"];
$date = date("m/d/y G:i:s<br>", time());
$sql = "INSERT INTO `comments` VALUES ('$c_post_id','$c_user_id',null,'$c_text','$date')";
if ($connect->query($sql) === TRUE) {
header("Location: http://thecobnmod.com/post.php?id=$c_post_id");
}
else {
exit( "Error: " . $sql . "<br>" . $conn->error);
}
}
JS ajax:
function funcSuccess (data) {
$("#comment_ajax").text(data);
}
function funcBefore (){
$("#comment_ajax").text("Loading comment...");
}
$(document).ready(function(){
$("#make_comment").bind("click", function () {
event.preventDefault();
$.ajax({
post: $("#c_post_id").val(),
user: $("#c_user_id").val(),
text: $("#c_text").val(),
url: "write_comment.php",
type: "POST",
data: {
c_post_id:post,
c_user_id:user,
c_text:text
},
dataType: "html",
beforeSend: funcBefore,
success: funcSuccess
});
});
});
Post id comes fro GET request to input field. I thought it could be a problem but not. now I really do not know what's wrong. Please help.
I strongly recommend consulting the documentations: Ajax doc
Ajax doesn't have post property AFAIK!
I'm not sure what you wanted to do, but here is a simple ajax example:
$.ajax({
url: 'here/is/some/url',
type: 'post',
data: {
some_key: 'value1',
other_key: 'value2',
/*...*/
},
dataType: 'html',
beforeSend: function() {/*...*/}
success: function(result) {/*...*/},
error: function(error) {/*...*/}
});

ajax function starts after second click

I have a form connected with ajax request. I use validation jquery plugin for form check.
So, when i click to submit button ajax call not work. After clicking submit button again it's working.
Why is this happening?
Here is my form
<form action="" id="anyQuestion" class="form-row">
#csrf
<input type="hidden" name="slug" value="{{$page->slug}}">
<div class="form-group col-12">
<input type="text" name="name" placeholder="name" class="form-control">
</div>
<div class="form-group col-6">
<input type="text" name="email" placeholder="mail" class="form-control">
</div>
<div class="form-group col-6">
<input type="text" name="phone" placeholder="phone" class="form-control">
</div>
<button class="submit-button mb-4 mt-2 w-100">submit</button>
</form>
And my ajax function with validation
$('#anyQuestion').validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
minlength: 10
}
},
submitHandler: function () {
var anyQuestionForm = $('#anyQuestion');
anyQuestionForm.submit(function (e) {
// e.preventDefault();
$.ajax({
type: 'post',
url: '/xhr/anyquestion',
data: anyQuestionForm.serialize(),
success: function (data) {
if( data == 'ok' ){
Swal.fire({
position: 'top-end',
type: 'success',
showConfirmButton: false
})
console.log(data);
document.getElementById("anyQuestion").reset();
}
},
error: function (data) {
Swal.fire({
type: 'error',
})
},
});
});
}
});
These two lines:
var anyQuestionForm = $('#anyQuestion');
anyQuestionForm.submit(function (e) {
are in your submit handler, but they are what set up the submit handling in the first place. So, it seems your first button click is calling submitHandler, which is then setting up your form's submit event handler so that another click will submit the AJAX request.
They should be in a document.ready() function:
$(function(){
var anyQuestionForm = $('#anyQuestion');
anyQuestionForm.submit(function (e) { . . .
});
Or, since you have your submit callback already inside your submitHandler, you may not even need the submit callback and just go with:
submitHandler: function () {
$.ajax({
type: 'post',
url: '/xhr/anyquestion',
data: anyQuestionForm.serialize(),
success: function (data) {
if( data == 'ok' ){
Swal.fire({
position: 'top-end',
type: 'success',
showConfirmButton: false
})
console.log(data);
document.getElementById("anyQuestion").reset();
}
},
. . .

jQuery File Upload and put Filename in Database

I have this AJAX message form:
HTML:
<form class="" id="message-form" action="message-send.php" method="POST">
<div class="form-group">
<textarea name="message" id="message-field" rows="3" class="form-control message-field"></textarea>
</div>
<div class="form-group">
<input type="file" id="file" name="file">
</div>
<div class="form-group text-right">
<input type="submit" id="submit" class="btn btn-success btn-sm msg-send" value="Envoyer" disabled>
</div>
</form>
JavaScript:
var message_form = $('#message-form');
message_form.submit(function (e) {
e.preventDefault();
$('#submit').attr('disabled', true).val('Sending...');
$.ajax({
type: message_form.attr('method'),
url: message_form.attr('action'),
data: message_form.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
$('#message-field').val('');
$('#submit').val('Send');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
PHP:
require 'config.php';
$message = $_POST['message'];
$query = 'INSERT INTO messages (time, from, to, message, file) VALUES (?, ?, ?, ?, ?)';
if (!($stmt = $mysqli->prepare($query))) {
echo $mysqli->error;
}
$stmt->bind_param('iiiss', $time, $from, $to, $message, $file);
$stmt->execute();
$stmt->close();
$mysqli->close();
Now what I need:
Upload the file using AJAX
Store the file as is to "/uploads/" with the same name
Put the filename in the db with the message
NB: The form already works well (The code presented is just a minimal version) I just need the handling of the file.
You have not included mimetypes in your ajax request.
mimeTypes: "multipart/form-data" add this inside ajax
try sending input values with formdata
var message_form = $('#message-form');
message_form.submit(function (e) {
e.preventDefault();
$('#submit').attr('disabled', true).val('Sending...');
var message_form = $('#message-form');
var file = $('#file');
var formdata = new FormData();
formdata.append('file', file.files[0]);
formdata.append('message', $('#message-field').val());
$.ajax({
type: message_form.attr('method'),
url: message_form.attr('action'),
mimeTypes: "multipart/form-data,
data: formdata,
async: true,
contentType: false,
processData: false,
beforeSend: function(){
},
success: function (data) {
console.log('Submission was successful.');
console.log(data);
$('#message-field').val('');
$('#submit').val('Send');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
}

Codeigniter-POST not working via ajax

I have a form, whose values I am trying to post after serializing to a controller via ajax. Below is the form:
Form
<form method="post" id="frm_reg_student" class="stop-propagation registration-form">
<input type="hidden" name="register[user_type]" value="2">
<input type="hidden" name="register[status_id]" value="1">
<div class="stud_register_error"></div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">First Name <span>*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your First Name" name="register[first_name]">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">Last Name <span class="req">*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your Last Name" name="register[last_name]">
</div>
</div>
</div>
</form>
js
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
type: "POST",
url: '<?=base_url()?>index.php/register/signup/',
data: serialData,
success: function(result) {
alert(result);
output = JSON.parse(result);
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
Controller
public function signup(){
if($_SERVER["REQUEST_METHOD"]=="POST"){
print_r($_POST);
}
}
Here, $_POST comes out to be empty, it never goes inside the loop. If you see in the JS, I have included an alert with the serialized data, which even shows me the proper serialized data. I believe it is something wrong with the way I am posting it.
Any help!
Try on ajax
$(".js-btn_reg_student").click(function(e){
var formdata = $( "#frm_reg_student" ).serialize();
$.ajax({
type: "post",
url: "<?php echo base_url('register/signup');?>",
data: formdata,
dataType: 'json',
success: function(json) {
if (json[success]) {
alert(json['post']);
} else {
}
}
});
e.preventDefault();
});
And controller
public function signup() {
$data = array(
'success' => false,
'post' => ''
);
if ($this->input->server("REQUEST_METHOD") == 'POST')
{
$data['success'] = true;
$data['post'] = $_POST;
}
echo json_encode($data);
}
Try
$('#js-btn_reg_student').click(function () {
$.ajax ({
type: 'post',
url: '<?php echo base_url(); ?>index.php/test/signup/',
data: $('#frm_reg_student').serialize(),
dataType: 'json',
success: function(result) {
if(result.status == 'success')
{
alert(result.name);
}
else
{
alert(result.status);
}
}
});
});
And in Controller
public function signup ()
{
if($this->input->post())
{
$data = array('status' => 'success');
$data['name'] = $this->input->post('register[first_name]');
}
else
{
$data = array('status' => 'failed');
}
echo json_encode($data);
}
Try it and let me know if it works or not :)
Try to use below code.
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
url: '<?=base_url()?>index.php/register/signup/',
method : 'POST',
data: serialData,
success: function(result) {
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
I think all the answers were correct in their own way. I figured out that it might be possible that it is not getting the DOM upon submit so I simply put it in document.ready and it worked!
Thanks

uploading image in a form using codeigniter/ajax

what should I do if i can't upload an image in a form it successfully created but the file is shows 0 not the upload file. please help me thanks in advance!
script in view where I can update and add a single form with upload
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
table = $('#dataTable2').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('about/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add About US'); // Set Title to Bootstrap modal title
}
function edit_person(about_id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('about/ajax_edit/')?>/" + about_id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="about_id"]').val(data.about_id);
$('[name="about_details"]').val(data.about_details);
$('[name="images"]').val(data.image);
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('about/ajax_add')?>";
}
else
{
url = "<?php echo site_url('about/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#myModal').modal('hide');
reload_table();
if (empty($_FILES['image'])) {
return FALSE;
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function delete_person(about_id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('about/ajax_delete')?>/"+about_id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
}
This is my form
<div class="modal-body form">
<form action="#" id="form">
<input type="hidden" value="" name="about_id"/>
<!-- <div class="form-group has-feedback ">
<label>Date</label>
<input type="date" id="date" class="form-control" input-sm placeholder="Date"/>
</div>-->
<div class="form-group has-feedback">
<label>About Details</label>
<input type="text" id="title" name="about_details" class="form-control" input-sm placeholder="About Details"/>
</div>
<!-- Description -->
<div class="form-group has-feedback">
<label>Image</label>
<?php $attrib = array('type'=>'text','name'=>'image','class'=>'form-control','id'=>'file'); ?>
<?php echo form_upload( $attrib,set_value('image')); ?>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-success" aria-hidden="true" onclick="save()">Save</button>
my controller for add and update
public function ajax_add()
{
$data = array(
'about_details' => $this->input->post('about_details'),
'image' => $this->upload->do_upload('image'),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$data = array(
'about_details' => $this->input->post('about_details'),
'image' => $this->upload->do_upload('image'),
);
$this->person->update(array('about_id' => $this->input->post('about_id')), $data);
echo json_encode(array("status" => TRUE));
}
What I have found out on uploading through ajax in CodeIgniter is that when we submit the form the images doesn't get uploaded. Because of this I used an extra js file "jquery.form.min.js" and the ajax upload went well. To implement it the script would look like:
$('#uploadimg').ajaxForm({
//uploadimg is my form id
dataType: 'json',
success: processJson
});
function processJson(data) {
if(data.msg=="success"){
alert('Upload is successful.');
}
else{
alert('Upload couldn't be completed.');
}
}
The form would be
<form action="<?=base_url();?>controller/uploadImage/" method="post" enctype="multipart/form-data" id="uploadimg">
On submition this will call the uploadImg function in the controller and here saving the image and insertion in the database is done.
public function uploadImage(){
//$id = $this->session->userdata('uid');
$config[ 'upload_path' ] = UPLOAD_DIR.'/newsletter/0';
$config[ 'allowed_types' ] = 'gif|jpg|png';
$config[ 'max_size' ] = '1500';
$config[ 'max_width' ] = '1000';
$config[ 'max_height' ] = '1500';
$image_name = "files";
$this->load->library( 'upload', $config );
if ( $this->upload->do_upload( $image_name ) ) {
$upload_data = $this->upload->data();
if(!empty($upload_data)){
$arg = array(
'name' => $upload_data[ 'file_name' ]
);
$this->modelName->insert($arg );
$data['msg']="success";
}
else{
$data['errmsg']="Couldnot upload the file!";
}
}
else{
$data['errmsg'] =$this->upload->display_errors();
}
echo json_encode($data);
}
Now this will trigger the processJson function in the script. And the upload shows the result.
You can find the javascript file on jquery.form.js.
I hope it works out for you.

Categories

Resources