Ajax back to previous page - ajax

I have a form inserted by jQuery Ajax to a page's div (say, 'content') and when the user finishes filling the form and hits 'submit' button, the result will be shown for further verification. The html and ajax code are as follows:
HTML:
<form id="userForm" action="..." method="post">
...
...
</form>
Ajax:
$(document).ready(function() {
$('#userForm').ajaxForm({
success: function(returnData) {
$('#content').html(returnData);
}
});
});
The 'returnData' is the filled form (without input fields) for further confirmation. Now, how do I implement a 'back' button such that the user may go back and modify the previously entered data?
I am working on Google App Engine with Python. Thanks.

I wouldn't replace the form with new HTML.
I would rather hide the form with display: none and add the new HTML for viewing alongside. If you want to go back, then you can just hide the "viewing div" and show again the form, without the need to refill any input elements.
Something along these lines should work
HTML:
<div id="content">
<div id="user-form-container">
<form id="userForm" ...>...</form>
</div>
<div id="viewing-container"></div>
</div>
CSS:
#viewing-container {
display: none;
}
The viewing part contains some sort of back-button, which hides the viewing area and shows the form again
jQ:
$(document).ready(function() {
$('#userForm').ajaxForm({
success: function(returnData) {
$('#viewing-container').html(returnData);
$('#user-form-container').hide();
$('#viewing-container').show();
$('#viewing-container #back-button').click(function() {
$('#user-form-container').show();
$('#viewing-container').hide();
});
}
});
});

Related

Show Loader when submitting form In laravel collective

I am submitting a form directly without using Ajax request, I want to show loader when getting a response from the backend.
How is it possible?
{!! Form::open(['route' => ['patient_signup'], 'method' => 'post', 'name' => 'sign_up_form']) !!}
and in controller
public function patient_signup()
{
if ($result) {
return redirect(route('home'))->with('success', $message);
} else {
return Redirect::back()->withInput()->with('error', $message);
}
}
Everything working fine but I want to show loader when getting a response from the backend.
Please provide me a better solution.
You can add div tag after body tag like below
<body>
<div class="pageLoader" id="pageLoader"></div>
In css
.pageLoader{
background: url(../images/loader.gif) no-repeat center center;
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 9999999;
background-color: #ffffff8c;
}
then in JavaScript
$(window).on('beforeunload', function(){
$('#pageLoader').show();
});
$(function () {
$('#pageLoader').hide();
})
Updated
return redirect(route('home'))->with('success', $message)->with('loader',true);
then in JavaScript
$(window).on('beforeunload', function(){
#if(isset($loader))
$('#pageLoader').show();
#endif
});
$(function () {
$('#pageLoader').hide();
})
It feels like you're fudging this a little. Spinners typically work with ajax requests as the spinner provides a visual feedback that an action is ongoing. The action being a request has been sent to the server by the browser and the browser is now waiting on a response. The response is required in order to remove the spinner (response could also be a failure or timeout etc.) and the spinner is removed without a page refresh.
In your use case, the response from the server is in fact redirecting the user to another page, or back to the form page with errors.
So basically what you want to do is have a loading indicator (spinner, words, etc.) which is initially hidden and you display when the form is submitted and it will automatically disappear if the user is redirected back to your form page.
As an example:
<div class="relative grid place-items-center h-screen">
<form id="some-form">
<button id="form-submit" class="px-4 py-2 bg-gray-800 rounded text-white">Submit</button>
</form>
<div id="loader" class="hidden" style="display: none">
Loading ...
</div>
</div>
Then your javascript:
let form = document.querySelector('#some-form');
let loader = document.querySelector('#loader')
form.addEventListener('submit', function (event) {
event.preventDefault();
// using non css framework method with Style
loader.style.display = 'block';
// using a css framework such as TailwindCSS
loader.classList.remove('hidden');
// pretend the form has been sumitted and returned
setTimeout(() => loader.style.display = 'none', 1000);
});
You could use jQuery or whatever you want but you get the idea. Example jsFiddle here.

Google reCAPTCHA v3: can't submit the form in data-callback

When I click the "submit" button, the form is not submitted. Why?
I got it straight from Google's sample code, all I added was one line:
document.getElementById("myform").submit();
The "thanks" message was shown.
If I click the "submit without validate" button, the form is submitted.
<html>
<head>
<script>
function onSubmit(token) {
alert('thanks ' + document.getElementById('name').value);
document.getElementById("myform").submit();
}
function validate(event) {
event.preventDefault();
if (!document.getElementById('name').value) {
alert("You must add text to the required field");
} else {
grecaptcha.execute();
}
}
function onload() {
var element = document.getElementById('submit');
element.onclick = validate;
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="/Second/Save" method="post" id="myform">
Name: (required) <input id="name" name="name">
<div id='recaptcha' class="g-recaptcha"
data-sitekey="6LexWMMZAAAAAGpLECkk-pfZ-sYuQ9qDu7wiMJ3M"
data-callback="onSubmit"
data-size="invisible"></div>
<button id='submit'>submit</button>
<button onclick="onSubmit();">Submit Without Validate</button>
</form>
<script>onload();</script>
</body>
</html>
The issue is that you have a button in the form with the id "submit". Any element in the form with a name or an id is reflected in a form attribute with that name. So if you have the form object will have an "elephants" attribute. In this case the submit button is accessible via form.submit, but this masks the submit() function.
If a form control (such as a submit button) has a name or id of submit, this method will mask the form's submit method.
MDN Web docs
Please check your site key, this error is mainly formed when your domain does not match your site key.
You can create your own google captcha key of your domain with your google account it's free of cost from the link given below
https://www.google.com/recaptcha/admin/create

Can't re open the modal after closing it using ajax

I have a modal that is triggered when the button is clicked in the main page. It works and the success modal is displayed and the url modal is closed. But my problem is that if I click the button again, url modal cannot be displayed. Here's my code.
<button class="btn pink apply_btn" type="submit" name="button">Apply</button> //my apply button in the page
<form class="search_form" action="" method="">
#csrf
<label>
<input type="url" required id="instagramLink" value="" placeholder="Instagram Post URL (Paste Here)">
<p>
<span class="alert"></span>
</p>
</label>
<div class="flex_box">
<button class="btn pink" type="button" id="save">Apply</button>
</div>
</form>
<script src="{{ url('/assets/js/modal.js') }}"></script>
And this is my ajax code in closing the url modal.
success: function(store) {
$(".apply_modal").hide();
$(".applyfnsh_modal").toggleClass("open");
$('.alert').html('');
},
error: function() {
$('.alert').html('Error occured while applying. Please try again.');
}
In my modal.js
//apply pop up
$(".apply_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$("body").toggleClass("open");
});
$(".modal_close").on("click", function(){
var modal = $(this).parent("div").parent("div");
modal.toggleClass("open");
$("body").toggleClass("open");
});
$(".apply_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.apply_box').length) {
$(".apply_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
So when the url is valid, save to db and display the success modal, which works, but clicking again the apply button in the page, is not displaying the url modal again. I have tried the answers here but nothing is working.
Ok, so here's what I'm thinking is happening... $(".apply_modal").hide(); is setting your modal's style to "display: none;" directly onto the DOM element. In order to display your modal, your code is simply applying a class of "open" to the modal. Any local styles to a DOM element override any styles from CSS. What this means is that the CSS styles applied to the class "open" don't matter because the div itself has a style attribute in it, and that style attribute contains "display: none". To fix this, wherever there is an instance of .toggleClass("open");, add a "show" declaration (.toggleClass("open").show();). You should do some serious refactoring if this works, but it'll at least let you know if we're on the right track.

Ajax form perfect until inside another page

I have a page which uses ajax to submit a comment form, add it to a db, then redisplay the page, hopefully without reloading the page its on.
If I access the script on it's own it works great, yet when I load it into another page it doesn't add the data and also refreshes the page on submit, which I want to avoid, which is the whole point of doing things this way.
Anyway, here's how I load the page:
<div id="wall_comments" class="msgs_holder"></div>
<script type="text/javascript">
$('#wall_comments').load('/pages/comment.php', { wl_id:"<?=$wl_id?>" });
</script>
and then the page itself with jquery code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<div style="width:100%; overflow:auto;">
<form method=post>
<input type="text" class="inp" name="comment" id="comment">
<input type=submit value="do it" name="action" onclick="update()">
<input type=hidden name="wl_id" value="<?=$_REQUEST[wl_id]?>" id="wl_id">
<input type=hidden name="user_id" value="<?=$userfromcookie?>" id="user_id">
</form>
</div>
<script type="text/javascript">
function update(){
var wl_idVal = $("#wl_id").val();
var commentVal = $("#comment").val();
var user_idVal = $("#user_id").val();
$.ajax({
type: "POST",
url: "/pages/comment.php",
cache: false,
data: { submit: "", wl_id: wi_idVal, comment: commentVal, user_id: user_idVal }
});
}
</script>
And finally enter info into db (I know this should be mysqli and it will be)
if(isset($_POST['action'])){
$wl_id = mysql_real_escape_string($_POST['wl_id']);
$comment = mysql_real_escape_string($_POST['comment']);
$user_id = mysql_real_escape_string($_POST['user_id']);
$addcomment = mysql_query("insert into list_wall (
event_id,
user_id,
comment
) VALUES (
'$wl_id',
'$user_id',
'$comment'
) ",$db);
if(!$addcomment) { echo 'result error add comment'; echo mysql_error(); exit; } // debug
}
The problem is when you click the submit button, the page is submitted and the function update couldn't work. You have to cancel the default submit mechanism by using return false;
<input type=submit value="do it" name="action" onclick="update() return false;">
Another thing.
The onclick on the submitbutton will not work as excpected if the submit is caused without clicking the button.
For example mobile safari on iPhone can submit forms directly without triggering the button.
If you add UmairP's version of the onclick to the form element as an onsubmit method you should get the same result on every platform as far as I know.
You can see more details on iPhone forms in my own question on another issue.
How can I prevent the Go button on iPad/iPhone from posting the form

Multiple AJAX Callbacks and Creating a List

I'm sure this is a common question but I have an input field and a button. Whenever the button is pressed an ajax call is performed returning a string. I understand that if you attach it to a div in the original file, that div will erase any strings or numbers in it and replace with the returned string. What would be the most efficient way to allow for every single callback to be displayed on the screen real time? I attempted it but it appears that dynamically changing the javascript variable that assigns which div tag the ajax callback inserts into does not work. Does anyone know either what is wrong with this code or a more efficient way to write this code, i.e. with php, etc.
<div id="part1">
<input type="text" id="text"/>
<input type="button" value="button" id="button"/>
</div>
<div id="hidden" class="2"></div>
<div id="part2"></div>
<div id="part3"></div>
<div id="part4"></div>
<div id="part5"></div>
<script type="text/javascript" >
$('#button').click(function () {
var text = $('#text').val();
$.post('ajaxskeleton.php', {
red: text
}, function(){
var number = $('#hidden').attr("class");
$('#part' + number).html(text);
var number = number+1;
var class_name = $('#hidden').attr('class')
$('#hidden').removeClass(class_name);
$('#hidden').addClass(number);
$('#text').val('');
});
});
</script>
Instead of erasing its contents with .html(), you could append the new results to an existing div . For example, suppose you want to append the results to a div with id results:
$('#button').click(function () {
var text = $('#text').val();
$.post('ajaxskeleton.php', { red: text }, function() {
$("<li>" + text + "</li>").appendTo($("#results"));
});
});​
Here's a DEMO.
I think something like the following would work.
<div id="container">
<input type="text" id="text"/>
<input type="button" value="button" id="button"/>
</div>
<ol id="responses"></ol>
$("#button").click(function() {
$.post('ajaxskeleton.php', {red:text}, function(data) {
$("#responses").append("<li>" + data + "</li>");
});
});
This just builds up an ordered list with the responses that come back from the Ajax calls, which I think is what your aiming to do.

Resources