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

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.

Related

AJAX isn't setting a PHP $_POST varibale so it's returning as 'Undefined'

I'm new to AJAX and not so good at PHP. I'm trying to simply send a string saying "Hello" to my PHP page using the JQuery $.AJAX function. So far I have successfully got AJAX to send the information to the page and log it in the console but the data doesn't get stored into the POST variable.
Please keep in mind I'm not being lazy by coming to this forum and asking for help but I have no other choice because I've been searching for about 2 days now on how to fix this problem and haven't found anything that's worked.
Here's my HTML (order.html) - This isn't all my HTML but it's all you will need):
<html>
<body>
<form method="POST">
<button id="order-btn" type="submit" formaction="PHP/sendMail.php">Order</button>
</form>
<!-- JavaScript/JQuery links -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="JS/order.js"></script>
</body>
</html>
Here's my JavaScript (order.js - Once again, I'm only providing necessary code)
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "PHP/sendMail.php",
type: "POST",
data: {data: txt},
dataType: "html",
asyc: true,
success: function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
Here's my PHP(sendMail.PHP - I'm only providing necessary code)
<?php
if(isset($_POST['data'])) {
$data = $_POST['data'];
echo $data;
} else {
echo "Failed to grab data.";
}
Just to clarify, in my actual code the URL is the full URL of my website page.
Let me know in the comments if you would like to see the site to get a better understanding of how and why I need this feature to work.
UPDATE & SOLUTION:
From the help I received I now understand that AJAX will only update information on the current page (So, for example, if you have an AJAX function on index.html then you can only run AJAX on that page and can't transfer information across pages)
To solve my problem I stopped sending users to the sendMail.php page and instead changed the HTML content of the page I was currently on (order.html) in the $.ajax success method.
Here's the updated JavaScript code:
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "order.html",
type: 'POST',
data: {data: txt},
dataType: 'html',
success: function(data){
if(parseInt(data)!=0) {
$("body").html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
I'd like to thank everyone that helped :)
$.ajax({ //create an ajax request to load_page.php
type: “POST”,
url: “load-page.php”,
data: {page:url}, //with the page number as a parameter
dataType: “html”, //expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$(‘#pageContent’).html(msg); //load the returned html into
pageContet
$(‘#loading’).css(‘visibility’,’hidden’);//and hide the rotating
gif
}
});
Like in above example load-page.php is called so data returned is going to dispaly in pageContent which is the id of some div etc and this div is not on load-page.php this div is on the page from where this ajax request is sent.
may be it will make sence
reference link: Reference Link!
It's not like this way as you have called sendMail.php this file and the data returned will be available in the page from where it was called.
Let suppose with button click on page A you called sendMail.php, so the ajax response returned to page A not to sendmAil.php.
First thing, garantees that your API is working. Using a toolchain for API, like postman or insomnia.
If your api is returning what you want, then you go to your javascript code, because I don't see any problem in your code. I even used your code and worked.
Then use session
session_start(); //at the top
$_SESSION['mydata'] = $data; // something like it
but as far as I know it's necessary to refresh the page for session to work. please try it

Form Redirect Jquery Ajax

I'm working on an HTML app in which there is a form. On clicking the submit button, I make a server-side call using jquery.ajax(). However, whenever an exception is returned from the server, like a Status Code 500, I need to display an error message on the same page. However, it automatically redirects when it encounters an error. I tried using the statusCode setting in jquery.ajax() like this:
$.ajax(
{
method: 'GET',
url: 'my url',
//...
successCode: {
500: function(response) {
alert(response.getResponseHeader("xyz"));
$('some_selector').show();
}
},
success: function(){},
error: function(){}
//...
})
But this does not seem to work. It redirects me to the action link and displays the JSON error and I cannot think of a way to prevent this redirect. Any help would be appreciated.
Thanks
It seems like your ajax options are outside of the ajax call put your parameters inside like
$.ajax(){options} => $.ajax({options})
Try this,
$.ajax({url: 'your url',
type: 'GET',
success: function (response) {
//succesfull request
}
}).fail(function (response) {
//failed request
});
You should be able to find the status code in the fail using response.status
I think your submit button is triggering the redirect. Try adding
$("#myform").submit(function(event){
event.preventDefault();
});
to prevent the redirect

Sending variables from Wordpress Contact Form 7 submission to success page

I am using Contact Form 7 with Wordpress 3.5.
Currently, when a user submits the message, they are redirected to a success page by using the following in the "Additional Settings" field:
on_sent_ok: 'location.replace("http://www.example.org/success-page");'
I want to be able to customise the output of the success-page by using the input from a field, for example:
on_sent_ok: 'location.replace("http://www.example.org/success-page?name=yourname");'
I hoped that by dropping the usual Contact Form 7 shortcodes into the Additional settings, it may have sent the field value with it, but that's not the case.
Can anyone suggest how I can get the field values from contact form 7 into the url, or alternatively send as a $_POST parameter? It may require some javascript to do this, I guess.
This is possible but you need the save the posted data from the contact form to the session and show it there.
Add this to your functions.php
add_action('wpcf7_mail_sent', 'save_cf7_data');
function save_cf7_data($cf)
{
if(session_id() == '') {
session_start();
}
$current_submission = WPCF7_Submission::get_instance();
$_SESSION['cf7_submission'] = $current_submission->get_posted_data();
}
And your success page you just need to print the session var, like:
echo $_SESSION['cf7_submission']['name'];
That's all.
Another option is to use jQuery or Javascript and catch the form on submit.
After the form is caught you can serialize the params and pass them to a custom page to catch them and do things with them.
Example for jQuery:
jQuery(document).ready(function($) {
$('.wpcf7-form').each(function () {
$(this).on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST', // Can also choose GET instead
url: 'forms/getParams',
data: $(this).serialize(),
dataType: "json",
success: function (data) {
$(this)[0].reset(); // Optional in case you want to clear the form on success
},
error: function (data, errorThrown) {
console.log(errorThrown);
}
});
});
});
});
the 'additional settings' code is javascript and thus is running in the context of the browser. this means you can easily access the form data using normal javascript code
e.g. on_sent_ok: 'location.replace("http://www.example.org/success-page?name=" + jQuery("input[name=name]").val());'
i think you should use $_REQUEST['name']; for fetching your post variable on success page.

Post form to web2py function using ajax

The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});

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