Don't reload webpage after flask ajax request - javascript

I have this ajax request
$(function() {
$('#left').bind('click', function() {
var form = $('form#data')[0]; //
var formData = new FormData(form);
$.ajax({
url: "{{ url_for('encode') }}",
type: 'POST',
data: formData,
async: false,
success: function (data) {
$("#img-2").attr("src", "{{url_for('static', filename='encoded.png')}}");
$("#diff").show();
},
cache: false,
contentType: false,
processData: false
});
});
});
And this flask function runs when the button is clicked.
#app.route('/encode', methods=['GET', 'POST'])
def encode():
a = request.form['text']
img = request.files['files']
img.save("./static/original.png")
secret = lsb.hide(img, a)
secret.save("./static/encoded.png")
return "ok"
The problem I am having is that the webpage becomes for a split second as it should be the image is set and the button diff is shown. But after that the webpage reloads and resets to the index page. And I do not really know how to prevent that from happening. What am I doing wrong?

Blind guess : your button may be part of a form, so its default behaviour when clicked is to submit the form and reload the page. You can prevent that by using event.preventDefault() :
$('#left').bind('click', function(event) {
event.preventDefault()
......

Related

ajax refresh php code on submit without refresh page

I use form for input date to DB. After submit form I need refresh php code (because when form is submit then I need display this value sent, instead of this form.)
I've script:
$(document).on('submit','#form_create_user',function(e){
e.preventDefault();
var fd = new FormData(this);
var obj = $(this);
fd.append('course_id', "<?php echo $this->uri->segment(4); ?>");
obj.find('input[type="submit"]').val("Tworzenie...")
$.ajax({
url: $(this).attr("action"),
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
// obj.find('input[type="submit"]').val("Confirm user")
}
});
$.ajax({
url: "<?php echo site_url('home/saveValues/'); ?>",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
toastr.success("Success created user.");
obj.find('input[type="submit"]').val("Potwierdź")
}
});
})
I can implement to this code refresh page below script:
document.getElementById("form_create_user").onsubmit = function(){
window.location.replace("<?php echo $course_details_url_back; ?>");
}
But the problem is, I have main tab and togle switch tabs with end url #user #domain etc.
example:
- mydomain.com/course
- mydomain.com/course#user
- mydomain.com/course#domain
When I run url in browser: mydomain.com/course#user then still is displayed main tab with url mydomain.com/course
This working only on switch tabs (without directly run url) So when I use above solution this stil reload page and back to main mydomain.com/course
So I need to find any solution for implement to above script refresh php code without reload page. Can anyone help me?

Ajax post submitting form multiple-times

I am using this code for data sent by Ajax. I am using summernote editor. My problem is when I submit by missing any field, my from shows 'required alert' and then when I fill all fields and press submit button then the form sends an Ajax request two times. Until it happens every time I miss required field.
<script type="text/javascript">
jQuery(document).ready(function (e) {
jQuery('#btnSubmit').click(function(){ //btnSubmit is submit button id
jQuery("#my_form").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = jQuery(this).attr("action"); //get form action url
var request_method = jQuery(this).attr("method"); //get form GET/POST method
var form_data = new FormData(this); //Creates new FormData object
jQuery.ajax({
url: "/demo/wp-admin/admin-ajax.php?action=theme_submit",
type: request_method,
data : form_data,
contentType: false,
cache: false,
processData:false,
success:function(data){
alert ('Data Successfully Inserted');
//location.reload();
//top.location.href="admin.php?page=data_list";
},
})
});
})
});
</script>
You can extract the submit out of the click. Write a function that would submit the form, and call it when the #btnSubmit is clicked. Below is the code to help you:
jQuery('#btnSubmit').on('click', function(event) {
event.preventDefault(); //prevent default action
submitForm();
})
function submitForm() {
var post_url = jQuery("#my_form").attr("action"); //get form action url
var request_method = jQuery("#my_form").attr("method"); //get form GET/POST method
var form = $('form').get(0);
var form_data = new FormData(form) //Creates new FormData object
jQuery.ajax({
url: "/demo/wp-admin/admin-ajax.php?action=theme_submit",
type: request_method,
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert('Data Successfully Inserted');
//location.reload();
//top.location.href="admin.php?page=data_list";
},
})
}

Button click event only works when page is reloaded or alert in function

It seems that a couple of buttons I have on my HTML page only work when there is an alert in the function of the event, or when I navigate to another page and then back to the home page. From other similar problems I've read about, it seems as though the home page is attempting to finish some task and that the alert is buying it more time. However, I am not sure that is true in my case.
I have a Javascript file actions.js that is loaded by the HTML page in the header as a source. The file is as follows (only showing relevant code) :
$(document).ready(function() {
//This function only works with an alert before the Ajax call or when page is reloaded
$("button[name='delete_deck']").click(function() {
var id = this.id;
$.ajax({
url: "delete_decks.php",
type: "GET",
data: {selection:JSON.stringify(id)},
async: false,
success: function(data) {
location.reload();
}
});
});
//This function is for a button on the same page, but works fine without the alert or reloading the page
$("#study").click(function() {
var selection = getDeckSelections();
if(selection.length > 0) {
//Get the selected side of the card
var selected_side = $('input[name=side_selection]:checked', '#side_selection_form').val();
//Store the selected side in session storage
sessionStorage.setItem("selected_side", selected_side);
//Ajax call to get cards from database
$.ajax({
url: "get_cards.php",
type: "GET",
data: {selection:JSON.stringify(selection)},
cache: false,
async: false,
success: function(data) {
json = JSON.parse(data);
//Store the cards in session storage
sessionStorage.setItem("cards", JSON.stringify(json));
}
});
}
});
}
$(document).on('click',"button[name='delete_deck']",function() {
var id = this.id;
$.ajax({
url: "delete_decks.php",
type: "GET",
data: {selection:JSON.stringify(id)},
async: false,
success: function(data) {
location.reload();
}
});
});

JQuery form submit not calling success

After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});

AJAX Multiple Form Submission

I'm not a Javascript master however I tried hard to prevent this. This script keeps randomly sending multiple posts. I couldn't manage to stabilize it. Usually works fine and sends one post per click. However sometimes it just decides that it should be posted like 5-6 times... Note that using async: false did not really make any difference. And it prevents me from disabling the button after the submission and its not because of "number of clicks" either. Thanks in advance!
$('#submit').click(function () {
$('#submit').attr("disabled", true);
var personal_text_data = document.getElementById('personal_text').value;
var lang_option_data = document.getElementById('language_option').checked;
$.ajax({
type: "POST",
url: 'send.php',
cache: false,
// async: false,
data: ({
notification_type: notification_type_data,
customer_id: customer_id_data,
personal_text: personal_text_data,
language_option: lang_option_data
}),
success: function () {
delete customer_id_data;
delete personal_text_data;
delete notification_type_data;
delete lang_option_data;
location.reload();
}
});
});
Use e.preventDefault(); to avoid the ajax submission and normal form submit from happening. Also change the click event and make it $('[yourForm]').submit().
$('[selectorToYourForm]').submit(function (e) {
$('#submit').prop("disabled", true);
e.preventDefault();
var personal_text_data = document.getElementById('personal_text').value;
var lang_option_data = document.getElementById('language_option').checked;
$.ajax({
type: "POST",
url: 'send.php',
cache: false,
// async: false,
data: ({
notification_type: notification_type_data,
customer_id: customer_id_data,
personal_text: personal_text_data,
language_option: lang_option_data
}),
success: function () {
location.reload();
}
});
});

Categories

Resources