I want to upload file along with other field data but all other data will posted but how to post file through ajax to controller.
my view file
<form method="post"action=""id="meetingform"enctype="multipart/form-data" >
<label for="inputEmail4">Meeting Date</label>
<input type="text" id="date" name="meetingdate">
<label for="inputEmail2" >Subject</label>
<input type="text" id="subjectt" name="subject" placeholder="Subject">
<input type="hidden" name="meetingevent" value="Meeting"/>
<label for="inputEmail2" >Venue</label>
<input type="text" id="venuee" name="venue" placeholder="Venue" >
<label for="inputEmail2" >Description</label>
<textarea name="description" id="desc" placeholder="Description" >
</textarea>
<label for="inputEmail2" >MOM</label>
<input type="text" id="momm" name="mom" placeholder="MOM" >
<input type="file" name="photo" id="photo">
<input type="file" name="document" id="documents">
<button type="button" id="submit"> </button>
</form>
my script is
<script>
$(document).ready(function () {
$("#submit").click(function (e) {
$.ajax({
url: '<?php echo site_url() ?>admin/meeting_form',
type: 'POST',
fileElementId :'photos',
data: $("#meetingform").serialize(),
success: function () {
$('#msg').html('<span style="color:green;align:center;">Data
Posted.</span>');
$('#date').val('');
$('#subjectt').val('');
$('#venuee').val('');
$('#desc').val('');
$('#momm').val('');
$('#photo').val('');
$("#msg").delay(3000).fadeOut();
},
error: function () {
$('#msg').html('<span style="color:red;">Data didnot post .
</span>');
}
});
});
});
</script>
my controller
public function meeting_form() {
$session_data = $this->session->userdata('admin_logged_in');
$id = $session_data['id'];
if ($session_data) {
$this->form_validation->set_rules('meetingdate', 'Meeting Date',
'required');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('venue', 'Venue', 'required');
$this->form_validation->set_rules('description', 'Description','required');
$this->form_validation->set_rules('mom', 'MOM', 'required');
if ($this->form_validation->run() == false)
{
$this->load->view('project_monnetering');
}
else
{
$data = array('event_date' => date('y-m-d', strtotime($this-
>input->post('meetingdate'))), 'event_type' => $this->input-
>post('meetingevent'), 'user_id' => $id,
'post_description' => $this->input->post('description'));
$last_id = $this->admin_model->insert_event_master($data);
$data1 = array('meeting_date' => date('y-m-d', strtotime($this-
>input->post('meetingdate'))), 'event_id' => $last_id, 'subject'
=> $this->input->post('subject'),
'venue' => $this->input->post('venue'), 'brief_desc' =>
$this->input->post('description'), 'mom' => $this->input-
>post('mom'));
$this->admin_model->insert_meeting_details($data1);
redirect('admin/project_monnetering', 'refresh');
}
} else {
$this->load->view('login');
}
}
How can i upload file along with other filed data here?
Please check below mentioned solution, This will help you to send file with input data.
var myFormData = new FormData();
$(document).on("click", "button", function(e) {
e.preventDefault();
var inputs = $('#my_form input[type="file"]');
$.each(inputs, function(obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
var inputs = $('#my_form input[type="text"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("id");
var value = $(v).val();
myFormData.append(name, value);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '/echo/html/', true);
xhr.send(myFormData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_form" enctype="multipart/form-data">
<input type="file" name="file_1" id="file_1" data-filename="image.jpg">
<input type="text" name="check1" id="check1"/>
<input type="text" name="check2" id="check2"/>
<input type="text" name="check3" id="check3"/>
<button>click</button>
</form>
Let me know if it not works.
Related
I am trying to implement a Contact from with custom Captcha using PHPmailer. The contact form works fine. The PHPmailer works fine as well. To avoid a lot of spam letters, I decided to implement custom Captcha, the problem is that the emails go anyway captcha is correct or incorrect.
<h4 class="sent-notification"></h4>
<form id="myForm">
<p>
<label>Name<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="name" type="text" name="name" required>
</p>
<p>
<label>Company<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="subject" type="text" name="company" required>
</p>
<p>
<label>Email<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="email" type="email" name="email" required>
</p>
<p class="full">
<label>Message<span style="color:#ff0000; margin-left:5px;">*</span></label>
<textarea id="body" name="message" rows="5" required></textarea>
</p>
<div class="contain">
<input type="text" id="capt" readonly="readonly">
<div id="refresh"> <img src="assets/img/icons/refresh.png" alt="refresh" width="50px" onclick="cap()"></div>
<input type="text" id="textinput" placeholder="Refresh to type Captcha" required>
<button onclick="validcap()">Check</button>
</div>
<p>
<button class="full" onclick="sendEmail()" value="Send An Email">Submit</button>
</p>
</form>
Script for PHPmailer
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
var textinput = $("#textinput");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body) && isNotEmpty(textinput)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
textinput: textinput.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully");
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
Script for Captcha
<script type="text/javascript">
function cap() {
var alpha=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V'
,'W','X','Y','Z','1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var a=alpha[Math.floor(Math.random()*62)];
var b=alpha[Math.floor(Math.random()*62)];
var c=alpha[Math.floor(Math.random()*62)];
var d=alpha[Math.floor(Math.random()*62)];
var e=alpha[Math.floor(Math.random()*62)];
var f=alpha[Math.floor(Math.random()*62)];
var sum=a + b + c + d + e + f;
document.getElementById("capt").value=sum;
}
function validcap() {
var string1 = document.getElementById('capt').value;
var string2 = document.getElementById('textinput').value;
if (string1 == string2){
alert("Form is validated Succesfully");
return true;
}
else {
alert("Please enter a valid captcha");
return false;
}
}
</script>
I want to listen to two input change events, when one of the changes, check the checkbox and disable the element. Likewise, it needs to roll the checkbox back to the previous state when the value of input boxes back to the default values. The click function looks like 90% resemblance, how to DRY them?
var payment = 'old payment';
var billAdr = 'old billAdr';
$('#payment').val(payment);
$('#bill-adr').val(billAdr);
$('#payment').on('input', function() {
var newPayment = $('#payment').val();
if(newPayment !== payment) {
$("#save-nxt-time").attr('checked', true);
$("#save-nxt-time").prop('disabled', true);
} else {
var newBillAdr = $('#bill-adr').val();
if(newBillAdr === billAdr) {
$("#save-nxt-time").prop('disabled', false);
$("#save-nxt-time").attr('checked', false);
}
}
});
$('#bill-adr').on('input', function() {
var newBillAdr = $('#bill-adr').val();
if(newBillAdr !== billAdr) {
$("#save-nxt-time").attr('checked', true);
$("#save-nxt-time").prop('disabled', true);
} else {
var newPayment = $('#payment').val();
if(newPayment === payment) {
$("#save-nxt-time").prop('disabled', false);
$("#save-nxt-time").attr('checked', false);
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="/#">
<label for="payment">payment</label>
<input type="text" id="payment" name="payment">
<br>
<label for="bill-adr">bill address</label>
<input type="text" id="bill-adr" name="bill-adr">
<br>
<input type="checkbox" id="save-nxt-time">
<label for="save">Save to next time</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
const oldPa = 'old payment';
const oldBi = 'old billAdr';
const $next = $('[name="save-nxt-time"]');
const $paym = $('[name="payment"]').val(oldPa);
const $bill = $('[name="bill-adr"]').val(oldBi);
const $paBi = $paym.add($bill);
$paBi.on('input', () => {
const bool = $paym.val() !== oldPa || $bill.val() !== oldBi;
$next.prop({disabled: bool, checked: bool});
});
form label {display: block;}
<form action="/#">
<label><span>Payment</span> <input type="text" name="payment"></label>
<label><span>Billing address</span> <input type="text" name="bill-adr"></label>
<label><input type="checkbox" name="save-nxt-time"> <span>Save to next time</span></label>
<input type="submit" value="Submit">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Like this ?
// first load
checkTest(true);
$('#payment, #bill-adr').on('input', function() {
checkTest(false, $(this).attr('id'), $(this).val(), "#save-nxt-time");
});
function checkTest(init = false, id, value, input) {
var payment = 'old payment', billAdr = 'old billAdr';
if (init === true) {
$('#payment').val(payment);
$('#bill-adr').val(billAdr);
}
console.clear();
console.log(value);
if (value === billAdr || value === payment) {
$(input).prop('disabled', false).attr('checked', false);
} else {
$(input).attr('checked', true).prop('disabled', true);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="/#">
<label for="other">payment</label>
<input type="text" id="payment" name="fname">
<br>
<label for="other">bill address</label>
<input type="text" id="bill-adr" name="fname">
<br>
<input type="checkbox" id="save-nxt-time">
<label for="save">Save to next time</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
how about putting the text and ids of the elements in an array and looping through
run snippet below
$(document).ready(function() {
const p = new PaymentMgr();
p.init();
});
class PaymentMgr {
constructor() {
this.data = [{
text: 'old payment',
id: 'payment'
}, {
text: 'old bill address',
id: 'bill-adr'
}];
}
init() {
this.data.forEach(element => $(`#${element.id}`)
.val(element.text)
.on("input", (e) => {
['checked', 'disabled'].forEach(attribute =>
$("#save-nxt-time")
.attr(attribute, $(e.target).val() !== element.text))
})
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/#">
<label for="payment">payment</label>
<input type="text" id="payment" name="payment">
<br>
<label for="bill-adr">bill address</label>
<input type="text" id="bill-adr" name="bill-adr">
<br>
<input type="checkbox" id="save-nxt-time">
<label for="save">Save to next time</label><br><br>
<input type="submit" value="Submit">
</form>
I have multiple select field among other fields on my form and submitting the data to the database using ajax. The data is submitting successfully but the problem is, when the multiple select field is empty, noting works: both the js and php code does not execute. Even thought I have the multiple select on the form but I plan not to make mandatory. Please help
$(function() {
$('#form1').on('click', function(e) {
e.preventDefault(); // do not allow the default form action
/* var realvalues = new Array();//storing the selected values inside an array
$('#s2_multi_value:selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
}); */
var form = $(this)[0].form;
var data = $(form).serialize();
$.ajax({
method: "POST",
url: "orgprocess1.php",
data: data
})
.done(function(data) { // capture the return from process.php
var obj = $.parseJSON(data);
var orgvalid = obj.valid2;
var buty = obj.$bty;
var orgmessage = obj.msg_orgcode;
var btypemessage = obj.msg_business;
if (orgvalid == 1) { // place results on the page
$('input[name="org_Code"]').removeClass('textBoxError');
$('#result2').html('<div class="valid"></div>');
} else {
$('input[name="org_Code"]').addClass('textBoxError');
$('#result2').html('<div class="error">' + orgmessage + '</div>');
}
if (buty == 1) { // place results on the page
$('select[name="btype"]').removeClass('textBoxError');
$('#result3').html('<div class="valid"></div>');
} else {
$('input[name="btype"]').addClass('textBoxError');
$('#select3').html('<div class="error">' + btypemessage + '</div>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-4">
<p>Email Address</p>
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="col-sm-4">
<p>Address</p>
<input type="text" class="form-control" id="addre" name="addre" placeholder="Physical Assress">
</div>
<div class="col-sm-4">
<p>Business Type</p>
<select id="s2_multi_value" name="btype[]" class="form-control" multiple="multiple">
<option value="">select one</option>
<option value="Goods">Goods</option>
<option value="Consultancy">Consultancy</option>
</select>
<input type="submit" value="submit" name="submit">
</div>
Try the following snippet it submits form weather you select any value or not.
$(document).ready(function() {
$(document).on('submit', function(e) {
e.preventDefault(); // do not allow the default form action
console.log("form submitting and sending ajax call");
/* var realvalues = new Array();//storing the selected values inside an array
$('#s2_multi_value:selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
}); */
var form = $(this)[0].form;
var data = $(form).serialize();
$.ajax({
method: "POST",
url: "orgprocess1.php",
data: data
}).error(function(){
console.log('error for ajax')
})
.done(function(data) { // capture the return from process.php
var obj = $.parseJSON(data);
var orgvalid = obj.valid2;
var buty = obj.$bty;
var orgmessage = obj.msg_orgcode;
var btypemessage = obj.msg_business;
console.log("into ajax done function",data);
if (orgvalid == 1) { // place results on the page
$('input[name="org_Code"]').removeClass('textBoxError');
$('#result2').html('<div class="valid"></div>');
} else {
$('input[name="org_Code"]').addClass('textBoxError');
$('#result2').html('<div class="error">' + orgmessage + '</div>');
}
if (buty == 1) { // place results on the page
$('select[name="btype"]').removeClass('textBoxError');
$('#result3').html('<div class="valid"></div>');
} else {
$('input[name="btype"]').addClass('textBoxError');
$('#select3').html('<div class="error">' + btypemessage + '</div>');
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="my-form" action="http://google.com">
<div class="form-group">
<div class="col-sm-4">
<p>Email Address</p>
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="col-sm-4">
<p>Address</p>
<input type="text" class="form-control" id="addre" name="addre" placeholder="Physical Assress">
</div>
<div class="col-sm-4">
<p>Business Type</p>
<select id="s2_multi_value" name="btype[]" class="form-control" multiple="multiple">
<option value="">select one</option>
<option value="Goods">Goods</option>
<option value="Consultancy">Consultancy</option>
</select>
<input type="submit" value="submit" name="submit">
</div>
</form>
With this code, I have succeed multiuploading from desktop. But the same script doesn't upload any images from a mobile phone. What could be wrong? Is there anyone who is a javascript master who knows a solution for multiuploading from mobile phones? I am not a very good javascript developer and I can not find a solution for this problem. Is there something special I need to do for javascript mobile uploads?
//upload
var abc = 0;
$(document).ready(function() {
$('#add_more').click(function() {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append(
$("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
}),
$("<br/><br/>")
));
});
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
abc += 1;
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="flag">
<form id="skickanytt" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Titel:</label>
<input type="text" name="title" class="form-control" placeholder="Enter a title" />
</div>
<div class="form-group">
<label>Message:</label>
<textarea class="form-control" rows="3" name="content" placeholder="Enter content"></textarea>
</div>
<div class="form-group">
<label>Image:</label>
<div id="filediv"><input name="file[]" type="file" id="file" /></div><br/> </div>
<h5><b> Label question?</b></h5>
<label><input type="radio" id="radioinput1" value="radioinput1" name="readornot">1</input></label>
<label><input type="radio" id="radioinput2" value="radioinput2" name="readornot" >2</input></label>
<br>
<button type="submit" name="submit" class="btn btn-success">submit</button>
<input type="button" id="add_more" class="upload" value="Add more images" />
Avbryt
</form>
</div>
</div>
In my abc.html I have the following code which will covert the form data(hard coded for now) to JSON format:
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
From the code above I get *
{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}*
Now I need to assign the Json String formed by this data to variable 'FormData' so that FormData is like:
FormData = '{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}'
How do I do this assignment of data ?
The further code in abc.html will use this variable FormData in the following way:
function sendAjax() {
$.ajax({
url : "myurl",
type : 'POST',
dataType : 'json',
data : FormData,
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
alert(data.uuid);
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
If you are not handling this in backend you can retrieve the data in Javascript in a variable then just appned it as JSON to your data using JSON.stringify().
This is a working snippet:
function submitform() {
var FormData = {
Company: myForm.Company.value,
User: myForm.User.value,
parameterMap: {
p1: myForm.p1.value,
p2: myForm.p2.value,
p3: myForm.p3.value
}
};
console.log(FormData);
$.ajax({
url: "myurl",
type: 'POST',
dataType: 'json',
data: JSON.stringify(FormData),
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.uuid);
},
error: function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='p1' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='p2' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='p3' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
Notes:
Use Javascript naming conventions, for example FormData will better be formData.
Using the provided HTML structure you could get the data into the format using:
function submitform(){
var form = document.querySelector('form');
var result = {};
var input = form.getElementsByTagName('input');
for(var i = 0; i < input.length; i ++) {
var row = input[i];
var rowName = ((row.name || '').match(/(\w+)(\[(\w+)\])?/) || []);
var rowIndex = rowName[3];
rowName = rowName[1];
if(rowName) {
var typeOfRowIndex = typeof rowIndex;
var rowValue = row.value;
if(typeof result[rowName] === 'undefined') {
var rowToAdd = {};
rowToAdd[rowIndex] = rowValue;
result[rowName] = typeOfRowIndex === 'undefined' ? rowValue : rowToAdd;
} else if(typeOfRowIndex !== 'undefined') {
result[rowName][rowIndex] = rowValue;
}
}
}
document.getElementById('output').innerHTML = JSON.stringify(result)
console.log(result);
return false;
}
<body>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="return submitform()">
</form>
<p>JSON Output (after clicking submit button):</p>
<div id="output"></div>
<p>Can also check console to see JSON object (after clicking submit button)</p>
</body>
var FormData = $('form[name=myForm]').serializeArray();
FormData = JSON.stringify(FormData);
I don't like jQuery, but:
var $inputs = $('form[name="myForm"]').find('input');
var res = {};
Array.prototype.forEach.call($inputs, function($item, index) {
res[ $item.getAttribute('name') ] = $item.value;
});
var FormData = JSON.stringify(res);
alert(FormData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>