I am storing some data from modal input. Everything works fine but when I work with file type data in this case I am taking an image which is to be stored in server folder and its location is to be stored in database.
I check if user wants to add data
then push the data to corresponding method of controller via ajax
there, I store the image in selected folder and retake location of the image, then push all data to model to store them in database.
Code:
modal:
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Blog Form</h3>
</div>
<div class="modal-body form">
<form id="form" class="form-horizontal" method='post' action='' enctype="multipart/form-data>
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Author Name</label>
<div class="col-md-9">
<input name="author" placeholder="author" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Blog Title</label>
<div class="col-md-9">
<input name="title" placeholder="title" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Blog Category</label>
<div class="col-md-9">
<input name="tag" placeholder="tag" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Blog Details</label>
<div class="col-md-9">
<input name="details" placeholder="details" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Blog Picture</label>
<div class="col-md-9">
<input name="picture" id="picture" placeholder="Add a photo" type="file">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
Save function in script:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/admin/blog_add')?>";
}
else
{
url = "<?php echo site_url('index.php/admin/blog_update')?>";
}
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
Blog_add method in Admin controller:
public function blog_add(){
$picture_name = $this->store_photo_return_photo_location();
$data = array(
'author' => $this->input->post('author'),
'title' => $this->input->post('title'),
'details' => $this->input->post('details'),
'tag' => $this->input->post('tag'),
'picture' => $picture_name,
);
$insert = $this->admin_model->blog_add($data);
echo json_encode(array("status" => TRUE));}
store_photo_return_photo_location function:
public function store_photo_return_photo_location(){
$filename = $_FILES['picture']['name'];
// Location
$location = 'assets/images/'.$filename;
// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// Valid image extensions
$image_ext = array("jpg","png","jpeg","gif");
$response = 0;
if(in_array($file_extension,$image_ext)){
// Upload file
if(move_uploaded_file($_FILES['picture']['tmp_name'],$location)){
$response = $location;
}
}
return $response;}
model:
public function blog_add($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
Until I worked with data without image, it was working ok, but when I'm working with image, it is not.
I think that pushing image name through ajax is not working.
Thanks in advance
you are calling this function for uploading an image but not passing a 'post' data to that function
$this->store_photo_return_photo_location();
call it like this
$image = $this->input->post['picture'];
$this->store_photo_return_photo_location($image);
and modify your function
public function store_photo_return_photo_location($image) {
//..your code
}
javascript's serialize() function won't be able to grab file from the html form. You should use FormData() instead
data: new FormData($('#form')),
Also in your store_photo_return_photo_location() function verify that a file actually exists before proceeding with the upload
if(!empty($_FILES['picture']['name'])){
//proceed
}
There's a different approach to uploading a file via ajax.
Please check this: https://stackoverflow.com/a/2320097/10412708
An easier approach is to put the submit URL in your form's action and let the form submit and refresh the page. Anyway, your JS reloads the page on success, why did you even use ajax for? Try to have your submit URL pre-conditioned in PHP if possible.
Related
I have a form which I am using to AJAX to submit. I have several forms using the same script all with different names posting to response.php however this particular form will not send.
When I remove my form name it tries to post in the normal way but when it has the correct name as the AJAX file I receive no reponse whatsoever leading me to think it is an error within the AJAX file.
HTML
<tr><Td>
<div class="row box" id="login-box">
<div class="col-md-9 col-md-offset-1">
<div class="panel panel-login">
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<div id="msg"></div>
<div class="alert alert-danger" role="alert" id="error" style="display: none;">...</div>
<form id="editMarshalTitleDetails-form" name="editMarshalTitleDetails_form" role="form" style="display: block;" method="post">
<div class="form-group">
<br><Br>
<input type="text" name="content" id="content" tabindex="2" class="form-control" value="<?php echo $content2 ?>">
<input type="hidden" name="marshalColumn" value="marshalPackFrontPageTitle">
<input type="hidden" name="userID" value="<?php echo "$userID"?>">
</div>
<div class="col-xs-12 form-group pull-right">
<button type="submit" name="editMarshalTitleDetails-submit" id="editMarshalTitleDetails-submit" tabindex="4" class="form-control btn btn-primary">
<span class="spinner"><i class="icon-spin icon-refresh" id="spinner"></i></span> Edit Title
</button>
</div>
</form>
</div>
</div>
</tr></td>
AJAX
$("#editMarshalTitleDetails-form").validate({
submitHandler: submitForm6
});
function submitForm6() {
var data = $("#editMarshalTitleDetails-form").serialize();
$.ajax({
type : 'POST',
url : 'response.php?action=editMarshalTitleDetails',
data : data,
beforeSend: function(){
$("#error").fadeOut();
$("#editMarshalTitleDetails_button").html('<span class="glyphicon glyphicon-transfer"></span> updating ...');
},
success : function(data){
$("#editMarshalTitleDetails_button").html('<span class="glyphicon glyphicon-transfer"></span> Template Updated');
var a = data.split('|***|');
if(a[1]=="update"){
$('#msg').html(a[0]);
}
}
});
return false;
}
So the problem when I click on submit it gives me this + no data is inserted into the db :
Screen shot of modal
I don't see any errors in the console.
my ajax code :
<script type="text/javascript">
$(document).ready(function () {
$("#lmao").on("submit", function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#add_data_Modal .modal-header .modal-title').html("Result");
$('#add_data_Modal .modal-body').html(data);
$("#submitForm").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#lmao").submit();
});
});
</script>
my form + modal :
<div id="add_data_Modal"class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add mew course</h4>
</div>
<div class="modal-body">
<div class="block-content block-content-narrow">
<form id="lmao"class="js-validation-courses form-horizontal push-10-t" data-async data-target="#add_data_Modal" action="add_c.php" method="post">
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_title" name="course_title" >
<label for="material-email">course title</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_cord"name="course_cord" >
<label for="material-email">Course cord</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_hours"name="course_hours" >
<label for="material-email">hours </label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_price" name="course_price" >
<label for="material-email">price</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<button class="btn btn-sm btn-primary" name="add_course" id="submitForm" type="submit">Add course</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
I have the add query in a separate file called add_c.PHP
so I have tried several answers from a lot of questions but I didn't manage to get something useful.
The PHP code in add_c.php :
Php code - pastebin
My knowledge is very small about ajax so I appreciate any help.
I tried your code, and the php file retrieves this post array
Array ( [course_title] => test [course_cord] => tet [course_hours] => tet [course_price] => tt )
your php code:
if(isset($_POST['add_course'])) {
add_course nevers gets posted, so it will never come into the if. Another issue is your form gets submitted twice the way you build it.
Change the button type into button, not submit. You already have a event listener on the button ;)
<button class="btn btn-sm btn-primary" name="add_course" id="submitForm" type="button">Add course</button>
I am sending data successfully using ajax method of jQuery to a PHP file.
Now, my problem is that I want to populate a modal form for editing an existing database record based on event ID that I am sending to my PHP page.
the snippet I use to call the PHP page is:
$.ajax({
url: 'dbget.php',
data: 'eventid='+event.id,
type: 'POST',
dataType: 'json',
cache: false,
success: function(json_resp){
//populate_data('#update_event', json_resp);
$('#updateModal').modal('show');
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
As you can see that I can't seem to get the data to populate in the form in success section of the ajax method.
Here is the data returned from PHP file:
[{"u_id":"21","u_eventName":"Ready Ply","u_eventDate":"2017-05-11","u_customerName":"Fassoooggg","u_customerMobile":"9383838383","u_customerEmail":"ffgg#gmaks.com","u_totalAmount":"1000","u_advanceAmount":"500","u_balanceAmount":"500"}]
Here is the PHP file snippet processing DB request and sending json encoded data:
//Get the evenId from the POST request
$eventId = $_POST['eventid'];
$events = array();
$getQuery = mysqli_query($con, "SELECT eventmaster.id, eventmaster.eventName, eventmaster.startDate, eventmaster.customerName, "
."eventmaster.customerMobile, eventmaster.customerEmail, eventdetail.totalAmount, eventdetail.advanceAmount, "
."eventdetail.balanceAmount FROM eventMaster INNER JOIN eventdetail ON eventmaster.id = eventdetail.eventId "
."WHERE eventmaster.id= '$eventId'");
while($fetch = mysqli_fetch_array($getQuery, MYSQLI_ASSOC))
{
$e = array();
$e['u_id'] = $fetch['id'];
$e['u_eventName'] = $fetch['eventName'];
$eventDate = substr($fetch['startDate'],0,10); //extract the eventDate in yyyy-mm-dd format from the table date
$e['u_eventDate'] = $eventDate;
$e['u_customerName'] = $fetch['customerName'];
$e['u_customerMobile'] = $fetch['customerMobile'];
$e['u_customerEmail'] = $fetch['customerEmail'];
$e['u_totalAmount'] = $fetch['totalAmount'];
$e['u_advanceAmount'] = $fetch['advanceAmount'];
$e['u_balanceAmount'] = $fetch['balanceAmount'];
array_push($events, $e);
}
//printf("Data sent to client: " );
echo json_encode($events); //return data in JSON array
Please note that the keys in the json data match the name of the form fields. Here is the form snippet. This is the form I am trying to populate:
<!-- Update Event Modal Starts -->
<div id="updateModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"><!-- Modal Header -->
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Update Event</h4>
</div>
<div class="modal-body"><!-- Modal Body -->
<p class="statusMsg"></p>
<form method="post" id="update_event">
<div class="form-group">
<input type="text" name="u_id" id="u_id" class="form-control" />
</div>
<div class="form-group">
<label for="u_eventName">Event Name</label>
<input type="text" name="u_eventName" id="u_eventName" class="form-control" placeholder="Event Name"/>
</div>
<label for="u_startDate">Event Date</label>
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" name="u_startDate" id="u_startDate" readonly />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<br />
<div class="form-group">
<label for="u_customerName">Customer Name</label>
<input type="text" name="u_customerName" id="u_customerName" class="form-control" placeholder="Customer Name"/>
</div>
<div class="form-group">
<label for="u_customerMobile">Customer Mobile</label>
<input type="text" name="u_customerMobile" id="u_customerMobile" class="form-control" />
</div>
<div class="form-group">
<label for="u_customerEmail">Customer Email</label>
<input type="text" name="u_customerEmail" id="u_customerEmail" class="form-control" placeholder="customer#email.com"/>
</div>
<div class="form-group">
<label for="u_totalAmount">Total Amount</label>
<input type="text" name="u_totalAmount" id="u_totalAmount" class="form-control" placeholder="0"/>
</div>
<div class="form-group">
<label for="u_advanceAmount">Advance Amount</label>
<input type="text" name="u_advanceAmount" id="u_advanceAmount" class="form-control" placeholder="0"/>
</div>
<div class="form-group">
<label for="u_balanceAmount">Balance Amount</label>
<input type="text" name="u_balanceAmount" id="u_balanceAmount" class="form-control" placeholder="0"/>
</div>
<div class="form-group">
<input type="submit" name="updateBtn" id="updateBtn" value="Update" class="btn btn-success" />
</div>
</form>
</div>
<div class="modal-footer"><!--Modal Footer -->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Update Event Modal Ends -->
So, once again, after you look at the above code snippets, please help me to populate the form with the JSON object sent from the PHP file containing one row record from database to be populated in the form.
Am I missing something or what? Also, if I try to print the JSON object in the html page, I only get an OBJECT printed instead of the data.
The sample I posted here was what I echoed from PHP.
Anyone's help will be highly appreciated. Thanks.
i am a beginner in using form validation in codeigniter, now i am trying to use form validation codeigniter library, why this is not executed? i already loaded the $this->load->library('form_validation'); at the top of my controller. I mean i want the output where it puts error below my input type. Why my error in array('required' => 'Error Message on rule2 for this field_name')); doesnt appear in my view. Only in Response at console
Here is my fullcode:
VIEW:
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="frm_create_user">
<div class="form-group">
<label for="userFName" class="control-label col-sm-4">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userFName" id="userFName" placeholder="First name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
<div class="form-group">
<label for="userMName" class="control-label col-sm-4">Middle Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userMName" id="userMName" placeholder="Middle name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
</form><!-- form-horizontal -->
<button type="button" id="btn_reg" onclick="create_User()" class="btn btn-primary">Create Account</button>
i am just trying one input type and some error for validating, now here is my Controller code:
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == FALSE) {
$result['type'] = 'error';
$result['message'] = validation_errors();
}else {
$result['type'] = 'success';
$result['message'] = 'Whooos..! Your Succes Message';
}
echo json_encode($result);
}
my ajax from view:
function create_User() {
$.ajax({
url: siteurl+"admin_controls/reg_user",
type: "POST",
data: $("#frm_create_user").serialize(),
dataType: "JSON",
success: function(data) {
alert(" User Successfully Added added! ");
$("#frm_create_user")[0].reset();
}
});
}
Please follow this Method.
Or
If you just copy and paste this code it will definately work, all you need to just change the controller name in the form action
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == TRUE) {
$result['status'] = true;
$result['message'] = "Data inserted successfully.";
}else {
$result['status'] = false;
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Now the Ajax Part
In Ajax i am using the FormData function instead of using serialize function. In case if you are going to upload files it will be helpful.
<script type="text/javascript">
$(document).ready(function() {
$("#form_data").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_data"));
$.ajax({
url : $("#form_data").attr('action'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
return false;
});
View Part
<a data-toggle="modal" href='#admin_create_acct' class="list_sort">Select<a>
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="<?php echo base_url('Practice/test_user')?>" method="post" id="form_data">
<div class="form-group">
username : <input type="text" class="form-control" name="name">
<span class="error userFName"></span>
</div>
<div class="form-group">
password : <input type="text" class="form-control" name="userMName">
<span class="error userMName"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
</div>
</div>
</div>
</div>
Am trying to submit data using modal bootstrap but i can't get it to work. The page will contain more than one modal to enable user to easily update their details.Here the code.
<div class="modal fade" id="overview-modal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Overview</h4>
</div>
<form id="overview_form" action="neuro/update_profile.php" class="form-horizontal" >
<div class="modal-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Overview</label>
<div class="col-sm-10">
<textarea class="form-control" id="overview_input" cols="20" rows="10" name="overview_textarea">
</textarea>
<input type="hidden" name="url"/>
</div>
</div>
<div class="form-group">
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<input type="submit" id="save" class="btn btn-success" value="Save"/>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
This is the javascript that will handle the form submission to the php file
<script>
$(document).ready(function () {
$("#save").submit(function () {
var formData = $("form#overview_form").serialize();
var my_url = "neuro/update_profile.php";
$.ajax({
type: "POST",
url: my_url,
data: formData ,
success: function (msg) {
$("#overview-modal").modal('hide');
},
error: function () {
alert("Error encounted");
}
});
return false;
});
});
</script>
The php is in a folder called neoro/update_profile ,since i will be using more than one modal in the profile page i have decided to append a url on the form attributes so that it can be easily processed in the php
$profile = new Profile();
$url = $_POST['url'];
if (isset($url)) {
if ($id == "overview") {
$overview = $_POST['overview'];
$profile->save_overview($user_id, $overview);
return TRUE;
}
} else {
header("Location: ./profile.php");
}
This is full of errors
You are sending the form via GET method and accessing it via POST method
Your URL field is empty
you are using action field and also submit simultaneously
your jquery code is not correct
you are using $id variable in your php code which is undefined
Corrected code:
<form id="overview_form" class="form-horizontal" method="post">
<input type="hidden" name="url" value='yoururl'/>
Do this:
$('#overview_form').submit(// your code here);
Instead of on #save, since you are submitting form not button 😉
Or
Even you can achieve same thing on #save but with click function as below
$('#save').click( // here your code );