Fancybox form submit with ajax - ajax

I have fancybox, where I want to submit a form. Also I want to handle that form by PHP code which is inside the same page. Below is my code.
function lunchModal(itemID){
jQuery('.share').on('click', function(){
$data = '<div class="shareModal" ><div class="modal-header"><h3>Share Form Submission</h3></div> \
<form action="" class="shareForm" method="post">\
<div class="modal-body">\
<div class="control-group">\
<label for="inputEmail" class="control-label">Enter Share Email</label>\
<div class="controls">\
<input type="email" id="inputEmail" placeholder="Share Email" name="email">\
<input type="hidden" value="'+itemID+'" id ="documentID">\
</div>\
</div>\
</div>\
<div class="modal-footer">\
<div class="controls">\
<button type="submit" class="btn btn-primary" id="submit">\
<i class="icon icon-envelope"></i>Share</button>\
</div>\
</div>\
</form>\
</div>';
jQuery.fancybox({
height : '55%',
autoDimensions: false,
width: '70%',
scrolling: 'auto',
padding: '20px',
title: false,
content: $data,
transitionIn: 'elastic',
transitionOut: 'elastic',
easingIn : 'easeOutBack',
easingOut : 'easeInBack',
centerOnScroll: 'true',
onComplete: submitForm()
});
item_id = false;
});
};
function submitForm() {
jQuery('#submit').on('submit', function(e) {
e.preventDefault();
//var dataString = {
// 'action' : 'shareDocument'
//};
var email = jQuery('#inputEmail').val();
var id = jQuery('#documentID').val()
var dataString = 'email='+email+'&documentID='+id;
//jQuery.extend(true, dataString, form_data);
console.log(dataString);
jQuery.fancybox.showActivity();
jQuery.ajax({
url: window.location.pathname,
type: 'POST',
data: dataString,
beforeSend: function() {
console.log(dataString);
},
success: function(data) {
alert('Document shared successfully');
}
});
return true;
});
}
Now my problem is When I submitting the form, the page is reloading, although I have used ajax form submit. Can anyone help me in this regard?

button type="submit"
this will reload ur page bcz ur submitting value to the declared page.
so you have to change ur code like below
input type="button" onclick="submitForm()"
this wont reload ur page.

Related

Why my page gets refresh while deleting image on 'product edit page'?

VIEW FILE
<div class="col-sm-4">
<label>Other Images</label>
<div class="input-group control-group img_div form-group" >
<input type="file" name="image[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success btn-add-more" type="button">Add</button>
</div>
</div>
</div>
<div>#foreach($image as $image)
<p><img src="{{asset('/files/'.$image->images)}}" height="50px" id="{{$image->id}}" class="photo"/>
<button class="removeimg" data-id="{{$image->id}}" data-token="{{ csrf_token() }}">Remove</button></p>
#endforeach
</div>
AJAX
$(document).ready( function () {
$(document).on('click', '.removeimg',function(){
var confirmation = confirm("are you sure to remove this record?");
if (confirmation) {
var id = $(this).data("id");
// console.log(id)
var token = $(this).data("token");
var $obj = $(this);
$.ajax(
{
url: "{{ url('image/delete') }}/"+id,
type: 'post',
dataType: "JSON",
data: {
"id": id,
"_token": token,
},
success: function (res)
{
// $(this).parents('.photo').remove();
$obj.parents('.photo').remove();
console.log("it Work", res);
}
});
console.log("It failed");
}
});
});
CONTROLLER
public function imgdelete($id){
Image::find($id)->delete($id);
return response()->json([
'success'=> 'Image deleted successfully!'
]);
}
When I delete the image, page gets redirected to product listing. Page should not get refresh when I delete the image. Can you please help me with correction?? NOTE: This process takes place on editproduct page.
You can prevent the default event for the button:
$(document).on('click', '.removeimg',function(event){
event.preventDefault();
.....
});

How to send other variable datas along with new FormData() inside AJAX?

Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>
Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');

How to update data on a page using ajax script?

There is a script that needs to update the data on the page in a specific div. But instead of updating, the block with the div is simply hidden and in order for it to appear again, you need to reload the page. The data comes in data, but here is $ ("# userPost" + id) .html (data); something doesn't work.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
// var formData = $('#EditPostForm'+id).serialize();
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "POST",
data: formData,
success: function(data) {
console.log(data);
$("#userPost"+id).html(data);
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
processData: false,
contentType: false,
});
});
And div
<div id="userPost{{$post->id}}">
#if($post->img)
<div>
<img src="{{$post->img}}" class="img-fluid">
</div>
#endif
<br>
#if($post->title)
<div class=" mr-1 mb-3 titleleft">
<h5 style="color: black"><b>{{$post->title}}</b></h5>
</div>
#endif
#if($post->message)
<div class="text-muted text-small margins" style="white-space: pre-wrap;">{{mb_strimwidth($post->message, 0, 600, " . . . Read more")}}</div>
#endif
#if($post->videoPost)
<div class="embed-responsive embed-responsive-16by9 mt-4 mb-2">
<iframe class="embed-responsive-item" src="{{$post->videoPost}}" allowfullscreen></iframe>
</div>
#endif
</div>
Try doing this way:
$("#userPost"+id).load(url);
or
$("#userPost"+id).html(data).load(url);

Ajax Submitting form Twice

I have a form in a modal window that allows a user to resend a confirmation email. When the form is submitted, the confirmation email is sent twice, instead of once. Everything else is working exactly as it should.
Form is pretty standard:
<form enctype="multipart/form-data" id="ReMailf" name="ReMailf" role="form" data-toggle="validator">
<fieldset>
<div class="row">
<p>You may enter a different email than your original if you wish. However, the original email will remain as the main contact on your application.</p>
<label class="desc" for="prim_email"> Email </label>
<input id="prim_email" name="prim_email" type="email" class="form-control" value="<?php echo $tE['prim_email']; ?>" data-error="Please Enter A Valid Email Address" required/>
<div class="help-block with-errors"></div>
</div>
<div class="row">
<input id="submitForm" name="submitForm" class="btn btn-success" type="submit" value="Resend Conformation "/>
<input name="uniqid" type="hidden" value="<?php echo $tE['unqID']; ?>"/>
<input name="ReMAIL" type="hidden" value="ReMAIL"/>
</div>
</fieldset>
</form>
… and here's the handler:
$(document).ready(function () {
$("#ReMailf").on("submit", function(e) {
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#ReMailf").submit();
});
});
I've read a number of other post about this, and tried some of the suggestions, but nothing is working. It either doesn't submit at all, or submits twice.
This is the only form on the page...
Suggestions please?
It is because you are using a button or submit to trigger the ajax event. Use this instead:
$(document).ready(function() {
$("#ReMailf").on("submit", function(e) {
e.preventDefault(); //add this line
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
or you can just use a simple form with action and method. It will do the job

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

Resources