Codeigniter form validation - javascript

I have the following html code below that will upload images from client side to my php apache server.
Backend, I have used the codeigniter form validation. However, after using the code below, user's images cannot be uploaded in to my server. If I comment the form_open(......) code <?php $prevURLPATH=urlencode($prevURL); echo form_open('newPost/createNewPost/'.$userID.'/'.$username.'?prevURL='.$prevURLPATH); ?>, my form actually works(those images get posted successfully), but of course it is done without codeigniter validation.
There,
is it possible to be able to post images and using codeigniter validation at the same time??
<div id="wrapper">
<div class="main-container">
<div class="container">
<?php echo validation_errors("<div style='color:red;'>","</div>"); ?>
<?php $prevURLPATH=urlencode($prevURL); echo form_open('newPost/createNewPost/'.$userID.'/'.$username.'?prevURL='.$prevURLPATH); ?>
<div class="row">
<div class="col-md-9 page-content">
<div class="inner-box category-content">
<div class="row">
<div class="col-sm-12">
<form id="newPost" class="form-horizontal" method="post" enctype="multipart/form-data"
action="<?php echo base_url(); echo MY_PATH;?>newPost/createNewPost/<?php echo $userID.'/'.$username.'?prevURL='.urlencode($prevURL); ?>">
<fieldset>
………….
…………………………………
<div class="form-group row">
<label class="col-md-3 control-label text-center" for="textarea">
<i class="icon-camera-1"></i><abbr title="Min. 1 picture required."><?php echo $Picture;?></abbr><font color="red">*</font></label>
</label>
<div class="col-md-8">
<div class="mb10">
<input id="image" name="images[]" class="file" type="file" accept="image/*" multiple>
<div id="uploadImgError">
</div>
</div>
<p class="help-block">Add up to 5 photos. Use a better image of your product, not catalogs.</p>
</div>
</div>
div class="form-group row">
<label class="col-md-3 control-label text-center"></label>
<div class="col-md-8">
<button id="submit-upload-form" class="btn btn-primary btn-tw" onclick="setup(); return false;"><i class="glyphicon glyphicon-upload"></i>Submit</button>
<button id="validate" hidden="true" type="submit"></button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
The follow is the javascript call that will submit the form:
function setup()
{
var myform = document.getElementById("newPost");
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
if(data == true)
{
var formData = new FormData(myform);
for (var i=0; i<fileList.length; i++){
formData.append('filelist[]', fileList[i]);
}
$('#image').fileinput('clear');
$('#image').fileinput('disable');
$('#Adtitle').attr('disabled', 'disabled');
$('#soldqty').attr('disabled', 'disabled');
$('#descriptionTextarea').attr('disabled', 'disabled');
$('#tagsInput').attr('disabled', 'disabled');
$('#submit-upload-form').attr('disabled', 'disabled');
$('#price').attr('disabled', 'disabled');
//console.log (formData.get('image'));
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total*100;
//Do something with upload progress
$("#upload-progress-bar").width(percentComplete+"%");
}
}, false);
return xhr;
},
url: "<?php echo base_url(); echo MY_PATH;?>newPost/createNewPost/<?php echo $userID.'/'.$username.'?prevURL='.urlencode($prevURL); ?>",
data: formData,
processData: false,
contentType: false,
type: 'POST',
success:function(msg){
$("#modal-text").html("Your post has been successfully uploaded.");
setTimeout(function(){
$("#modal-text").html("Your post will be reviewed and go on live within the next 24 hours.");
$('#fwd-btn').css("display", "block");
$('#fwd-btn').css("margin", "auto");
$('#progress-bar').css("display", "none");
}, 2000);
}
});
}
return data;
});
}
});
}

Actually,
I have below jquery javascript function in the submit button that will use URL to do form submit. How to change it??
function setup()
{
var myform = document.getElementById("newPost");
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
if(data == true)
{
var formData = new FormData(myform);
for (var i=0; i<fileList.length; i++){
formData.append('filelist[]', fileList[i]);
}
$('#image').fileinput('clear');
$('#image').fileinput('disable');
$('#Adtitle').attr('disabled', 'disabled');
$('#soldqty').attr('disabled', 'disabled');
$('#descriptionTextarea').attr('disabled', 'disabled');
$('#tagsInput').attr('disabled', 'disabled');
$('#submit-upload-form').attr('disabled', 'disabled');
$('#price').attr('disabled', 'disabled');
//console.log (formData.get('image'));
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total*100;
//Do something with upload progress
$("#upload-progress-bar").width(percentComplete+"%");
}
}, false);
return xhr;
},
url: "<?php echo base_url(); echo MY_PATH;?>newPost/createNewPost/<?php echo $userID.'/'.$username.'?prevURL='.urlencode($prevURL); ?>",
data: formData,
processData: false,
contentType: false,
type: 'POST',
success:function(msg){
$("#modal-text").html("Your post has been successfully uploaded.");
setTimeout(function(){
$("#modal-text").html("Your post will be reviewed and go on live within the next 24 hours.");
$('#fwd-btn').css("display", "block");
$('#fwd-btn').css("margin", "auto");
$('#progress-bar').css("display", "none");
}, 2000);
}
});
}
return data;
});
}
});
}

First, you should use form_open_multipart() instead of form_open() but probably it won't be enough.
Form validation is not checking file inputs, I don't know why but I'm sure that. Because of that, you have to control it in your model.
You can use this structure:
if(empty($_FILES))
{
return false;
}
else
{
//some code here
}

Related

how to use ajax to perform php background submission in html

Hi i'm trying to converting my form data to pdf like below.
HTML -> AJAX -> PHP (fpdf)
After click submit button ajax processing & pop message as "localhost say : ok"
if i not full any input name in html , ajax pop say "please fill all fields."
why ajax not able to reach php did i done any thing wrong in php, please help.
Below my code :
html code :
enter code here
<form id="form">
<div class="row">
<div class="col-md-12 form-group container"" >
<center> <b>E-FSR Reporting</b>
<p name="date" id="date"></p>
</center>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group" >
<input type="text" class="form-control" name="name" id="name" placeholder="name" >
</div>
</div>
<div class="row">
<div class="col-12 ">
<td colspan="2" align="center" >
<input type="submit" id="submit" name="submit" value=" Submit E-FSR " class="btn btn-primary rounded-0 py-2 px-4">
</td>
<span class="submitting"></span>
</div>
</div>
ajax code : script.js
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
var dataString = 'name='+ name;
if(name=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "pdf.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
php code : pdf.php
enter code here
<?php
if(!empty($_POST['submit']))
{
$name= $_POST['name'];
require("fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
....
Thanks
You are sending you data in a incorrect way:
Your javascript code should be like this:
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
if(name=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "pdf.php",
data:{
name:name
},
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
Remark:in php when you fetch data from the $_POST the key should be like how you sent it from ajax.
From example in ajax you are writing
data:{
name:fname,
gender:mygender
}
Then in php it should be $_POST["name"] and $_POST["gender"].

How to process two different ajax placed in different script tag?

I have a page with 3 dropdowns and 1 submit button, on selecting top dropdown value rest auto-populate with ajax.
And after that submit button is used to submit information, for this, I have written ajax in a different script tag.
The problem here is first ajax is working perfect, but second ajax is not working, I know 2 ajax call is not allowed.
I have tried to do this by writing PHP on the same page, but on reloading the page the previously selected information auto submits.
<form style="margin: 10px 50px 10px 50px;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<div class="row">
<div class="col-md-12">
<div class="form-group">Book Name
<select class="form-control" id="sel_book">
<option value='0'>---Select---</option>
<?php
foreach($result as $key=>$rs):
{
?>
<option value="<?php $key; ?>"> <?php echo $rs[1];?> </option>
<?php
}
endforeach;
?>
</select>
</div>
</div>
</div>
<div class="row" >
<div class="col-md-12" >
<div class="form-group">Member ID
<select class="form-control" id="sel_uid">
</select>
</div>
</div>
</div>
<div class="row" >
<div class="col-md-12" >
<div class="form-group">Member Name
<select class="form-control" id ="sel_uname">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-icon btn-3 btn-primary" id="accept">
<span class="btn-inner--icon"><i class="ni ni-user-run"></i></span>
<span class="btn-inner--text">Accept Return</span>
</button>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$("#sel_book").change(function(){
var bid = $(this).val();
bid = bid+1;
//alert(bid);
$.ajax({
url: 'get_user.php',
type: 'post',
data: {id:bid},
async: false,
dataType: 'json',
success:function(response){
$("#sel_uid").append("<option value='"+response.name+"'>"+response.name+"</option>");
$("#sel_uname").append("<option value='"+response.mname+"'>"+response.mname+"</option>");
}
});
});
});
</script>
<script>
$(document).ready(function(){
$('#accept').click(function(e){
var book = $("#sel_book :selected").text();
var memberId = $("#sel_uid :selected").text();
var memberName = $("#sel_uname :selected").text();
var message = book+'\n'+memberId+'\n'+memberName;
alert(message);
e.preventDefalut();
$.ajax({
type:'post',
url:'accept_return.php',
async: false,
data:{bname:book,memid:memberId,memname:memberName},
dataType:'json',
success:function(response){
$("#final").text("Processing completed sucessfully");
}
});
});
});
</script>
The second script is running properly, but the ajax call to the PHP page is not made.
<script>
$(document).ready(function(){
$("#sel_book").change(function(){
var bid = $(this).val();
bid = bid+1;
//alert(bid);
$.ajax({
url: 'get_user.php',
type: 'post',
data: {id:bid},
async: false,
dataType: 'json',
success:function(response){
$("#sel_uid").append("<option value='"+response.name+"'>"+response.name+"</option>");
$("#sel_uname").append("<option value='"+response.mname+"'>"+response.mname+"</option>");
}
});
});
});
$('#accept').click(function(e){
var book = $("#sel_book :selected").text();
var memberId = $("#sel_uid :selected").text();
var memberName = $("#sel_uname :selected").text();
var message = book+'\n'+memberId+'\n'+memberName;
alert(message);
e.preventDefalut();
$.ajax({
type:'post',
url:'accept_return.php',
async: false,
data:{bname:book,memid:memberId,memname:memberName},
dataType:'json',
success:function(response){
$("#final").text("Processing completed sucessfully");
}
});
});
</script>
Hi you are facing this problem because of two document ready used .First document ready works fine but second ready is not recognized.Please put your click function out of any document ready.Please try using single script as below.May be this helps

How to upload two or more `input type file` field into database via jquery ajax?

view:
<script>
$(document).ready(function(){
$(".vehicle").click(function(e){
e.preventDefault();
vehicle_number = $("#vehicle_number").val();
var fileInputs = $('#dl');
var formData = new FormData();
$.each(fileInputs, function(i,fileInput){
if( fileInput.files.length > 0 )
{
$.each(fileInput.files, function(k,file){
formData.append('dl[]', file);
});
}
});
var fileInputss = $('#rc');
var formData = new FormData();
$.each(fileInputss, function(i,fileInputr){
if( fileInputr.files.length > 0 )
{
$.each(fileInputr.files, function(k,file){
formData.append('rc[]', file);
});
}
});
formData.append('vehicle_number', vehicle_number);
$("#success_vec").html("<img src='<?php echo base_url(); ?>assets/loading.gif'>");
$.ajax({
type:"POST",
data:formData,
processData: false,
contentType: false,
url:"<?php echo base_url(); ?>add_vech",
success:function(data){
$("#success_vec").html(data);
}
});
});
});
</script>
<form>
<div id="success_vec"></div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="vehicle_number md-addon">Vehicle Number</label>
<input type="text" class="form-control" id="vehicle_number">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="dl">Upload DL Of Vehicle Owner</label>
<input type="file" id="dl">
</div>
<div class="form-group col-md-6">
<label for="rc">Upload RC</label>
<input type="file" id="rc">
</div>
</div>
<button type="submit" class="btn btn-primary vehicle">save</button>
</form>
controller:
public function add_vech()
{
$dataInfo = array();
$files = $_FILES;
print_r($files);
}
In this code I want to upload two document i.e. dl and rc. Now, Problem is that when I upload both field file and print the value inside the controller then It show me only last file data i.e rc. So, I want to know that how can I print or upload both input file in my controller? Please help me.
Thank You
That's because you are overwriting the formData:
var formData = new FormData();
Remove the second formData instantiation below fileInputss:
var fileInputss = $('#rc');
var formData = new FormData();

Undefined response while uploading image with ajax

I have a problem uploading images in AJAX.
When I click on send the image, I get a jquery feedback that tells me "undefined" while the image has been clicked
I have try one other thing who works properly, but creating a really simple form and by giving a class attribute to jquery instead of id.
And that works..
The form who does not works ( i would like it to works :) )
<form action="ajax/uploadimage.php" method="post" enctype="multipart/form-data" >
<div class="card-body">
<!-- Single -->
<div class="dropzone dropzone-single mb-3" data-toggle="dropzone" data-dropzone-url="http://">
<div class="custom-file">
<input id="file-upload" type="file" name="fileToUpload" class="custom-file-input" multiple required>
<label class="custom-file-label" for="file-upload">Choose file</label>
</div>
<div class="dz-preview dz-preview-single">
<div class="dz-preview-cover">
<img class="dz-preview-img" src="..." alt="..." data-dz-thumbnail>
</div>
</div>
</div>
<center><input type="submit" class="btn btn-primary" id="file-submit" value="<?php echo TXT_DASHBOARD_MODIFIER; ?>"></center>
</div>
</form>
The jquery who does not works
<script type="text/javascript">
$(function() {
$('#file-submit').on('click', function() {
var file_data = $('#file-upload').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('#file-upload').val('');
}
});
}
return false;
});
});
</script>
The form who works :
<form>
<input type="file" name="image" class="image" required>
<input type="submit" name="submit" class="submit" value="Submit">
</form>
The jquery who works :
<script type="text/javascript">
$(function() {
$('.submit').on('click', function() {
var file_data = $('.image').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('.image').val('');
}
});
}
return false;
});
});
</script>
I would like to solve the undefined error..
Thanks for help :)

Form is not submitting to data base from wordpress site through Ajax

Following is my form which comes in the popup and i cant submit the data to the data base. please help me to solve this out
<div id="fsModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<button type="button" id="cross-btn" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div id="desk-view" class="modal-body">
<div id="pop-up" class="row">
<div class="arrow_box side-heading col-xs-5 col-sm-5">
<h3>Join the Movement, the newsletter that tackles the justice issues that matter to you most.</h3>
</div>
<div class="right-form col-xs-7 col-sm-7">
<form id="form-search" action="" method="POST" class="form-inline subscribe-form">
<div class="form-group">
<input id="email-form" type="email" class="email-popup" placeholder="Enter your email" name="email">
</div>
Sign up
</form>
</div>
</div>
</div>
</div>
</div>
and my Ajax is like this
$('#submit-form').click(function(e) {
$.ajax({
data: {'user_email':$("#email-form").val()},
type: "POST",
url: "http://localhost/womensweb-local/index.php/news-letter/",
success: function(data){
alert(data);
}
});});
and im directing to the template page to newsletter_insert.php to submit form.and my template php code is like this
$email=$_POST['email'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['user_email']) && !empty($_POST['user_email'])) {
$wpdb->insert('newsletter_table', array(
"emailaddress" => $email
));
echo "1";
}else{
echo "2";
}
}
if (data == 1) {
alert("Subscribed Successfully!!");
} else if(data == 2){
alert("Something Went Error");
}
var data = {'user_email':$("#email-form").val()};
use JSON.stringify to stringify data to JSON and then pass from ajax as below instead of data: {'user_email':$("#email-form").val()},
as well as make sure to add contentType: "application/json" in your ajax request
data: JSON.stringify(data),
In wordpress prefer function.php file using wp_ajax method:
Like below:
Your jquery code from any file in the wp
jQuery.ajax({
url: "http:your_host_name/wp-admin/admin-ajax.php",
type: 'POST',
dataType: 'json',
data:{
action: 'your_action_name',
},
success : function(response){
console.log(response);
}
});
In your functions.php file write:
add_action("wp_ajax_your_action_name", "test_function");
function test_function(){
echo "Here";
}
This way ajax works in wordpress.
$('#submit-form').click(function(e) {
$.ajax({
data:{'user_email':$("#email-form").val()},
type: "POST",
url: "http://localhost/xxxx/index.php/news-letter/",
success: function(data){
if (data == 1) {
alert("Subscribed Successfully!!");
} else if(data == 2){
alert("Something Went Error");
}
}
});
});
php code is
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['user_email']) && !empty($_POST['user_email'])) {
$wpdb->insert('newsletter-table', array(
"emailaddress" => $_POST['user_email'],
"date" => date('Y-m-d')
));
echo "1";
}else{
echo "2";
}
}

Categories

Resources