How to merge two ajax requests into one - javascript

I'm editing the form-edit-account.php template. This template contains a form that allows users to change account settings (name, surname, age etc ..). Originally the form had no ajax requests, so I added them to save data without page refresh. Everything works fine but I have some doubts about how I could refine the code.
When click on submit button of my form, in google console network tab I see that there are two requests, one belongs to Ajax Handling Error, while the other belongs to Ajax Save settings.
Ajax Handling Error allows me to view messages when form fields are not respected or success messages if all goes well.
Ajax save settings
actually saves the data without reloading the page.
What I would like to do is get a single request (saves settings and shows error messages). It's possible merge ajax hanling error code and ajax save settings code in a single request instead of two ?
Js at the end of the form
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
$.post($form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.woocommerce-notices-wrapper').html(data);
}, 'json');
//Ajax Save settings
jQuery.ajax({
type: "POST",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
wc_add_notice("<b>Nome</b> รจ un campo obbligatorio", "error");
$response = wc_print_notices(true);
} else{
wc_add_notice("Modifiche salvate con successo", "success");
$response = wc_print_notices(true);
}
echo json_encode($response);
exit();
}

I found a solution, I don't know how right it can be, I'm just a fan and not a programmer. With this solution I only see a request in google console network card. Also everything works fine, the data is saved and the messages are ok. I post the solution below for anyone who is in the same situation as me.
I just changed the script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
jQuery.post(
$form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.woocommerce-notices-wrapper').html(data);
}, 'json'
);
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
});
});
});

Related

automatically getting data as it is posted without refreshing with ajax

I am trying to create a conversation system with php jQuery and ajax.
I am using the following jQuery to handle the ajax post together with php.
function replyToStatus(sid,user,ta,postuser){
var data = $('#'+ta).val();
if(data.trim() == ""){
alert("Please type a reply before you submit.");
return false;
}else{
var dataString = 'action=status_reply&sid='+sid+'&user='+user+'&postuser='+postuser+'&data='+data;
$.ajax({
type: "POST",
url: location.href,
data: dataString,
cache: false,
success: function(response){
$('#'+ta).val("");
$( "#conrep_"+sid ).append( '<li><div class="comment-user-image-container"><div class="user-image" style="background:url(\'imagesrc.jpg\');"></div></div><div class="comment-content"><h5>admin '+data+'</h5><img class="scaledImageFitWidth img" src="userimagesrc.jpg"></div></li>');
}
});
}
}
This code appends and displays the post immediately to the current user(user1) making the post.However to all the other users viewing the same page whom have not refreshed the page after this user(user1) has posted ,this post won't appear until they have refreshed.
My question is how do I make a system that will automatically show this post to all users or how do I deal with this problem otherwise.
Thanks for the reply in advance:)

submit form without refresh page and load output into html [duplicate]

This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 7 years ago.
I want to submit a form information to another php script without leaving the page and show the output in that same page.
Here's my ajax function to load php output in html without leaving the page. It doesn't do that if my form has a submit button. It only works with a normal clickable button.
$('#btnLoad').click(function(){
$.ajax({
type: 'POST',
url: 'page1.php',
success: function(data){
if(data != null) $('#content').text(data);
}
});
});
The problem is that I need to send POST variables to my PHP script but when I do, it goes to my PHP script page. I just want the script to receive the POST variables, run the script and then show the output in my HTML page.
Here's the script that doesn't go to PHP script page. I don't know if the PHP script runs with this function.
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('page1.php', $(this).serialize(), function (data) {
}).error(function() {
});
e.preventDefault();
});
});
How can I combine these two scripts into one, to submit my variables via POST, run the script and show the output in my HTML page?
Combining both Ajax
$("#btnLoad").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "page1.php",
data: $('#myForm').serialize(),
success: function (msg) {
$("#thanks").html(msg);
},
error: function (msg) {
$("#error").html(msg);
}
});
});
HTML to show success message
<div id="thanks"></div>
HTML to show error message
<div id="error"></div>
PHP Server Side
<?php
if (isset($_POST['submit'])) { //assuming you have input with name="submit"
//Do what ever you like to do next
//If everything good
echo "<strong>Success!</strong> This Is Success Thanks Message. If everything go exactly as Planned.";
} else {
echo "<strong>Error!</strong> This Is Error Message. If anything goes south.</div>";
}
?>
Edited: OP asked to show messages in jQuery modal dialog
In Ajax after success call, try like this
success: function(msg) {
$("#thanks").html(msg);
$("#modalId").dialog({
autoOpen:true,
width:500,
title:"Your Error Message",
},
And same for error function
Note: I haven't test this so not sure it will work out of the box or need any debugging.
Why do you not replace the submit buttons with normal buttons then?
What you could do in jQuery is:
$(formSelector).on('submit',function (e) {
e.preventDefault()
//Place your ajax here.
})
you can do something like
$('#btnLoad').click(function(){
$.ajax(url,
{
data: { variable1: $("#variable1").val(), variable2: $("#variable2").val() },
type: "POST",
success: function(data) {
if(data != null) $('#content').text(data);
}
});
});
And normally I don't use a form if I need to send data via ajax, I use just JS.

How to send variables with GET without reloading page

What I'm trying to accomplish is the following. I have a php page which loads some variables from an mysql db. Then I want to send these variables using GET to another page without opening the page where the variables are being send to.
At first I really didn't know how to do this until I came across the following:
$( document ).ready(function()
{
$.ajax({
url: 'the_url',
type: 'GET',
data: {Gender:Male,DateOfBirth:1968-07-21},
success: function(data) {
//called when successful
alert("Succes");
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert("Failed");
}
});
}
The $test and $test1 are php variables which I would like to send to the other page. But apparently i'm doing something wrong. Not even the alerts are being triggered so there is probaly something wrong with my syntax.
I'm using the following jquery version: jquery-2.1.4.min.js
If there is something wrong in the way I asked this question please let me know and give me the help to update the question.
Just assign PHP variables to JS variables and also change the data sending part as well there is no need of ' for data sending.
$( document ).ready(function()
{
var test = '<?php echo $test; ?>';
var test1 = '<?php echo $test1; ?>';
$.ajax({
url: 'the_url',
type: 'POST', //change type to POST rather than GET because this POST method of sending data
data: {test:test,test1:test1},
success: function(data) {
//called when successful
$('#ajaxphp-results').html(data);
alert("succes");
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert("failed");
}
});
}

Form not submitting with AJAX

=====UPDATE AGAIN==== (if anyone cares!)
the solution I posted before stopped working for whatever reason. I included a beforeSend in my ajax request and pasted the portion of my js that validates my form into it. Works like a charm now!
$('#form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh
$.ajax({
type: "post",
beforeSend: function(){ // check that form is complete
},
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you'); hide_request();window.location = "#top";
}
});
});
EDIT
See my answer below, using 2 .preventDefault!
I have read through many pages / examples of this, but for some reason I can't get it to work on "my" form.
I'm simply trying to submit my form without refreshing the page or opening a new page / tab for the confirmation message.
The form:
<form id="form" name="Configurator" method="post" action="">
.... //Client configures his product, display an image if they choose, and request a quote.
<button id="submit_button" type="submit" name="Submit" >Request</button>
</form>
The client_config_send2.php works, it simply pulls a bunch of parameters from the form (configuration, contact info) and puts it into an email. This part works fine before I try to integrate the ajax.
The JS:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
The validateForm() function also works, it checks if the configuration is valid, if the email / contact info is complete, etc.
At this point, the validateForm works: if info is missing, the alert pops up. However when validateForm() returns true, the form doesn't submit, nothing happens.
I have tried success instead of done, return false instead of true in the JS, and many other things I found online but I am lost. Never used AJAX before so I'm not 100% confident with the subtleties of the language!
Thanks in advance!
"client_config_send2.php" is a filename. The URL you give to Ajax needs to be, well, a URL like http://example.com/client_config_send2.php.
Change done to success:
success: function(data){
success only fires after your request got response and the response code is OK(http 200).
Update the code below:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
var formdata = $(this).serialize();
$.ajax({
type: "post",
url: "http://www.example.com/client_config_send2.php",
data: formdata,
success: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
Could you try removing/commenting event.preventDefault();
If this method is called, the default action of the event will not be triggered. (http://api.jquery.com/event.preventdefault/)
Try coding in the following format. The logic uses an if/else statement to make the ajax call.
$('form').on('submit', function(e) {
//If form could not be validated
if(!validateForm(this)){
//prevent the form form submitting
alert("Your form is not valid for submission!");
e.preventDefault();
}
//else
else{
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
}
});
});
Here is the final code that does exactly what I want:
- the validateForm() function works as it should. If the form is not complete, it returns false, an alert pops up and the form does not submit
- if validateForm() returns true, the form gets submitted, the confirmation alert pops up and the page does NOT refresh. Users can then build a new configuration and submit a new request without re-entering all the contact info.
The 2 .preventDefault did the trick!
$('form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh when form is submitted
//If form could not be validated
var x = validateForm();
if(x == false){
//prevent the form form submitting
e.preventDefault();
}
//else
else {
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you! we will get back to you within 24 hours. Please check your junk / spam folder if you do not receive a response within that time.');
}
});
}
});
Thanks everyone for your help!

Jquery form ajax call trouble

I'm having trouble submitting an ajax request.
I've tried to set it up pretty simply just to see if i can get a response
Here is my js:
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
type: "POST",
url: "processform_ajax.php",
data: $(this).serializeArray(),
dataType: "json",
sucess: function (data) {
alert("data" . data);
//$("#response").append(data);
},
error: function(error, txt) {
alert(error.status);
}
});
});
});
My php is simply this
<?php
$errors = array ('a' => 'TEST!');
echo json_encode($errors);
?>
When I try to run this with the firebug extension i'm seeing the post looks okay. (which it shouldn't matter at this point, because my php just echo's out something)
On the response side I'm seeing this error : NS_ERROR_NOT_AVAILABLE
Which leads me to believe it can't find processform_ajax.php, but when i've tried the absolute url in url: "" option above. I can also hit the the php script through the browser's address bar and get the json response
Any clues?
Thanks
NS_ERROR_NOT_AVAILABLE seems like a Firefox "bug/feature" where it tries to submit the call twice.
Try this... add a return false in your code, like this:-
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
...
});
return false;
});
});
This way, once the form is submitted through your JS code, the return false will prevent your "Submit" button from submitting the same request again.
Is sucess a typo in your code, or just on SO?

Categories