Submit html form, stay on same page with added success content - ajax

Using html web-to-case form generated by salesforce, I want users to submit, stay on the same page and see a success message. If I add the salesforce server url to the form, it gets sent to the server but the user is redirected from the form page to that url. I've tried:
·targeting an iframe in the form tag but it doesn't submit to the
server
·using an event listener and 'setTimeout(() => form.submit()', but
that also redirects to server url (or refreshes the page if I specify a return url) (see Success Message display on submit html form)
·using ajax to send the form data but that doesn't post to the
server or do anything:
$( "form" ).on( "submit", function(e) {
var dataString = $(this).serialize();
// alert(dataString); return false;
$.ajax({
type: "POST",
url: "https://xxx-uat1.sandbox.my.salesforce.com/servlet/servlet.WebToCase?
encoding=UTF-8",
data: dataString,
success: function () {
$("#contact_form").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
});

Related

AJAX form redirecting on submit when using CKeditor

I am trying to submit an AJAX form with Laravel using the code shown below. After I submit the form, all the data is saved in the database as expected apart from the following field which is displayed as NULL in the database.
<textarea name="content" id="editor"></textarea>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form');
$.ajax({
type:'POST',
url: form.attr('action'),
data: form.serialize(),
success:function(data){
alert(data.successful);
}
});
})
});
</script>
public function addVideo(Request $request)
{
$addVideo = new cms_videos;
$addVideo->VideoStatus = $request->VideoStatus;
$addVideo->VideoTitle = $request->VideoTitle;
$addVideo->VideoStrapline = $request->VideoStrapline;
$addVideo->VideoURL = $request->VideoURL;
$addVideo->VideoDescription = $request->content;
$addVideo->VideoTags = $request->VideoTags;
$addVideo->MetaActName = $request->MetaActName;
$addVideo->MetaRegion = $request->MetaRegion;
$addVideo->MetaGenre = $request->MetaGenre;
$addVideo->MetaVenue = $request->MetaVenue;
$addVideo->VideoCoverPhoto = $request->VideoCoverPhoto;
$addVideo->save();
return response()->json(['successful'=>'Video successfully added']);
}
After doing some research I was told to add the following code to the top of the code shown above:
CKEDITOR.instances.SurveyBody.updateElement();
Now all the data is submitted to the database as expected. However when I now submit the form instead of an alert popping up saying "Successful" I am now redirected to the form action URL where it displays "Successful". How can I stop this redirection and display the alert on the page the form was submitted?
I'm not sure but I think the issue is here when you do e.preventDefault() because it works for the button click not for form submission. Try this out and hope it will help you.
Notice: you have to add upload_video class to your forms
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// If the button is type of submit you can remove this part of code
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form.upload_video');
form.submit();
})
});
//
$("form.upload_video").on('submit',function(e){
e.preventDefault();
let form = $(this),data=form.serialize();
//
let content=FCKeditorAPI.GetInstance('content').getData();
data['content']=content;
//
$.ajax({
type:'POST',
url: form.attr('action'),
data: data,
success:function(data){
alert(data.successful);
}
});
});
</script>
This part
let content=FCKeditorAPI.GetInstance('content').getData();
May not be true because I don't work with CKEDITOR right now and i can't test it but you can console.log() it before you send the ajax request and make sure the content exists in the variable as you expected.

Ajax submit an image with form - pass the FormData - trigger submit

I simply want to use ajax to submit a form with an image from a phone.
If I use the below code as a simple function - the form data is not passed.
If I use the code as is - it works but the user has to click the submit button.
How do I either pass the FormData properly to a simple $.ajax({}); submit?
OR
How do I trigger the code below when a picture is taken or selected?
I have this - it works fine when user clicks submit:
// how do I trigger this when image file is selected?
$("#Upload_Form").submit(function(e){
e.preventDefault();
// OR - how do I get FormData with image without using: '$("#Upload_Form").submit(function(e)'
var formData = new FormData(this);
$.ajax({
// POST details are here etc.
});
});
Bind the change event for the file input like below and then trigger the submit event of the form or make an ajax call right away with the FormData see below demo.
If you want to know how to submit image using FormData and ajax see this answer
$("#my-form").on('submit', function(e) {
e.preventDefault();
// OR - how do I get FormData with image without using: '$("#Upload_Form").submit(function(e)'
var formData = new FormData(this);
console.log("sending Ajax call now");
$.ajax({
// POST details are here etc.
});
});
$("#my-file").on('change', function() {
//you can either trigger the form submit here
var form = $("#my-form");
$("#my-form").submit();
//OR
//use this to send the ajax call to upload the image
// var form=$("#my-form")[0];
// var formData = new FormData(form);
// $.ajax({
// type: "POST",
// url: 'your/url',
// data: formData,
// processData: false,
// contentType: false,
// success: function (data) {
// console.log("SUCCESS : ", data);
// },
// error: function (e) {
// console.log("ERROR : ", e);
// }
// });
})
<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="my-file" id="my-file" />
<input type="submit" name="submit" value="submit" />
</form>
Update
Note: if you want to use an ajax call to send the formData you need to set the processData and contentType to false. contentType: false only available from jQuery 1.6 onwards.

Selectors not working on ajax response

I'm using ajax to submit pages and return content blocks based on user action for an onboarding sequence.
If have a page which loads and get 1 content element, the user then clicks Yes or No, which loads the next content element into the same space (via ajax).
For some reason my selectors don't seem to be working on that ajax loaded html.
Here is my ajax function which gets the form:
$.ajax({
beforeSend: function() {
$("#loader").toggleClass('progress');
},
type: 'POST',
dataType: 'json',
data: data,
url: baseUrl+'welcome/user_confirmation_form',
complete: function( response ) {
$("#loader").toggleClass('progress');
},
success: function( response ) {
console.log(response);
$("div.welcome-page > .col").html(response.response);
},
error: function( response ) {
$("#next-steps").html(response.response);
}
});
I'm then trying to access the submit button (have tried doing it as a ahref and button type=submit but nothing seems to be selecting the event.
$('div.welcome-page').on('submit', "user_complete", function(e) {
e.preventDefault();
console.log('FOund form');
var user = $(this).serializeArray();
console.log(user);
});
If I view source, the ajax returned HTML is not even in the dom, but it is when viewing the UI normally.
I'm guessing this has something to do with it?
How can I select all the form data?
Any time I click on the button or ahref it just fires the same page again.
If user_complete is a class you are assigning on your submit button in your loaded html, then you are missing a .
$('div.welcome-page').on('submit', ".user_complete", function(e) {
But this will only work if you're using a submit action as this is listening for a submit event. Maybe you want to listen for a click event?
You need to bind the events to your handlers for your newly added HTML elements. Your original call to
$('div.welcome-page').on('submit' ...
Only bound the event handler for the elements that were on the page at that point in time.
You can put your handler into a function ...
var myHandler = function(e) {
e.preventDefault();
var user = $(this).serializeArray();
}
And then after you load the new HTML you need to bind the handler to the event. So, on success with the AJAX you would ...
success: function( response ) {
$("div.welcome-page > .col").html(response.response);
$('div.welcome-page').on('submit', "user_complete", myHandler);
},

load form using jquery ajax and resubmit that form without page refresh

i want to submit form which loaded via jquery without refreshing the whole page.
but this code first load form without refreshing whole page then the form loaded via jquery refreshes whole page on submission.
how to solve this problem??
$(document).ready(function() {
$("body").on("click",".down",function(e) {
e.preventDefault();
var name = $("#down").attr("name");
var vote = $("#down").val();
var voteString = 'votedown='+ vote;
$.ajax({
type: "POST",
url: 'vote.php',
data: voteString,
cache: false,
error: function() {
$('#btn-vote').html('<p>An error has occurred</p>');
},
beforeSend: function() {
$('#load').html("<img src='../images/LoaderIcon.gif' />");
},
success: function(html) {
$("#re").html(html);
}
});
The on function takes a selector as well, that way you can use it on elements loaded with ajax. You also have to bind it to an element that exists when the page loads.
$('body').on('click', 'selector of the element created', function(){
...
})
Obviously you should not use body probably but a closer parent of the loaded element.

prevent redirection on submit to form

I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false

Resources