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";
},
})
}
Related
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()
......
I want to send my form data and image data with ajax but I can only send one of them with my code.
My Javascript code:
$("#advertising_form2").on("submit", function (e) {
e.preventDefault();
var formObj = $("#advertising_form2");
var formData = formObj.serialize();
$.ajax({
url: "/php-ajax-upload.php",
type: "POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
alertify.success(data);
}
});
new FormData(this) in the ajax parameters contains image data to be sent with ajax.
var formData contains form data to be sent with ajax.
With the above code I can only send either new FormData(this) or formData. How can I send both?
I have a page called profile.php and on this page I have 4 form for user to update. I used .validation class for all 4 form. I used this for jQuery beforeSend(). So that when a form is press it will be show Validation... text.
Now I use user_profile_data() on 2 forms. When I update the form it's showing Validation... text on 2 form. BUT it's should be show on selected form.
Here is jQuery/Js I am using :
function user_profile_data (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: 'user_profile_data',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('.validation').val('Validating...');
$("#avator_upload").attr("disabled", true);
$('.account_validation_msg').html('<div class="alert alert-warning"><strong>Validating...</strong></div>');
},
success: function (data) {
$('.account_validation_msg').html(data);
$('#notification_bottom').val('SAVE DETAILS');
$('.account_validation_msg').show();
$("#avator_upload").attr("disabled", false);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Here is my Javascript for fetching value to input box,
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id = document.getElementById('hdn_user_id').value = userid;
alert(userid);
});
I want this value to use for SQL query in modal window which is on same page.
I fetched value in modal window but unable to use it. What the format to use it.
You can pass js variable into php page using ajax.
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id=document.getElementById('hdn_user_id').value=userid;
$.ajax({ //create an ajax request to load page.php
type: "GET",
url: "page.php",
data:"varabletophp="+u_id, //Here is the value you wish to pass in to php page
dataType: "html", //expect html to be returned
success: function(response){
alert(response);
}
});
});
No you can get this variable into your page.php (php page) using
$fromjs=$_GET['varabletophp'];
echo $fromjs;
you can use input hidden and set userid value in on this input so , post form
Varying modal content based on trigger button :
http://getbootstrap.com/javascript/#modals-related-target
var data = new FormData($('form#' + formId)[0]);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
beforeSend: function () {
},
success: function (response) {
},
error: function (response) {
}
});
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
});
});