POST php form using jquery - php

I need any jQuery code to send form data without refreshing the page.
Method (POST): after submit form show "loading..." message or "loading image". If process.php = 1 (true) hide form and display ok message, and if process.php = 2 ( false ) not hide form and display any error message.

var data = new Object();
data['formData'] = $('#form').serializeArray();
$.ajax({
type: 'post',
url: 'process.php',
dataType: 'json',
success: function(response) {
if (response.result == 1) {
$('#form').hide();
} else {
alert('error');
}
}
});
process.php:
//...
echo json_encode(array('result' => 0)); // OR 1

You need to add form ID or any other identificator.
so, if your form is
<div id="message"> </div>
<form method="post" action="" id="myForm">
<input type="submit" name="send" id="sendData" />
</form>
jQuery:
$(document).ready(function() {
$("#sendData").click(function() {
$("#message").html("loading ...");
$.post("process.php", {
submit: 1 //and any other POST data you separate with comma
}, function(response) {
if(response == 1) {
$("#myForm").hide();
$("#message").html("OK");
} else {
$("#message").html("error message");
}
});
});
});
now, after submit form you will get message "loading ..." while posting "process.php", then if process.php returns 1 the form will be hide and display OK else you get an error message.

Related

Trying to save value from ajax/jquery submit form in database

I have CSS Pie chart which when I click on one of the pies, it opens a simple submit form.
The problem is that when I click submit button nothing goes into the database. Just shows thank you message and this is it. Nothing in the console.
I have put the pie chart front part here: https://jsfiddle.net/096hgmqd/. When you click on Button 1 it opens the form below.
Here is the jquery/ajax part
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://res.cloudinary.com/positionrelativ/raw/upload/v1492377595/jquery.rwdImageMaps_lq5sye.js'></script>
<script src="script.js"></script>
<script>
// validate form on keyup and submit
var formData = new FormData(form);
$("#loadingmessage").show();
$.ajax({
url: "submit.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
if(data == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
}
if(data == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
},
error: function(){}
});
</script>
And the PHP part - submit.php
$connect = new PDO("mysql:host=localhost;dbname=MYDBNAME", "DBUSERNAME", "DBPASSWORD");
$message = '';
if(isset($_POST["saveAnswers"])) {
$query = "INSERT INTO clarity (name) VALUES (:name)";
$user_data = array( ':name' => $_POST["name"] );
$statement = $connect->prepare($query);
if($statement->execute($user_data)) {
$message = '<div class="alert alert-success"> Registration Completed Successfully </div>';
} else {
$message = '<div class="alert alert-success"> There is an error in Registration</div>';
}
}
Can anyone help here?
UPDATE: current code:
$( document ).ready(function() {
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
if(data.result == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
} else if(data.result == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
},
error: function(){}
});
});
});
And PHP
if(isset($_POST["saveAnswers"]))
{
sleep(5);
$query = "INSERT INTO clarity (name) VALUES (:name)";
$user_data = array(
':name' => $_POST["name"]
);
$statement = $connect->prepare($query);
$response = 'error';
if($statement->execute($user_data)) {
$response = 'success';
}
echo json_encode(array('result' => $response));
}
HTML form
<form class="form-wrapper" action="" method="post" id="submitForm1">
<fieldset class="section is-active">
<h3>What is your name?</h3>
<input type="text" name="name" id="name" placeholder="Your Name">
<button type="submit" class="button" name="saveAnswers" id="saveAnswers">Submit</button>
</fieldset>
</form>
you need to submit your form.Your ajax request will fire as soon as the page loads not on form submit.
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
if(data == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
}
if(data == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
},
error: function(){}
});
});
For the DB problem, you first need to fix the communication between PHP and JS. Also, you can debug the data with console.log(form) in JS. You can also debug at the server-side, you can return the debugging data, especially the $_POST like this:
$debug = var_export($_POST, true);
echo json_encode(array('debug' => $debug);
And you can view the response in the Developer Console of your browser, to see whether the information is received by the PHP or not.
Your PHP does not return anything. You just saved the output to a variable named $message. In your jQuery AJAX call, you expect there are some data returned, either success or error, but your PHP script does not provide these.
Try to change the PHP if-else clause to:
$response = 'error';
if($statement->execute($user_data)) {
$response = 'success';
}
echo json_encode(array('result' => $response));
and add the following line to the very first line of PHP:
header('Content-Type: application/json');
Last, in your jQuery call, change the if-else clause in the success handler to:
if(data.result == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
} else if(data.result == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
You have mentioned that you don't see anything on the Network tab. This means that there is "no connection" between your Ajax/jQuery and PHP parts and I believe that the actual problem is in your Ajax part. You can try like this. (I have tested it and it works just fine).
HTML part
<p id="show_message" style="display: none">Form data sent.</p>
<span id="error" style="display: none"></span>
<form class="form-wrapper" action="" method="post" id="submitForm1">
<fieldset class="section is-active">
<h3>What is your name?</h3>
<input type="text" name="name" id="name" placeholder="Your Name">
<button type="submit" class="button" name="saveAnswers" id="saveAnswers">Submit</button>
</fieldset>
</form>
Ajax part
<script type="text/javascript">
$(document).ready(function($){
// hide messages
$("#error").hide();
$("#show_message").hide();
// on submit...
$('#submitForm1').submit(function(e){
e.preventDefault();
$("#error").hide();
// if name is required
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
// ajax
$.ajax({
type:"POST",
url: "submit.php",
data: $(this).serialize(), // get all form field value in serialize form
success: function(){
$("#show_message").fadeIn();
}
});
});
return false;
});
</script>

Form not submitting without redirecting

I want to send sms on click without page reload and redirecting but the form not working without redirecting to action page. Here is my code.
Page containing form
<div class="blog">
<form method="post">
<input type="hidden" name="message" value="whatever">
<input type="text" name="tono" maxlength="10">
<input type="submit" value="SEND SMS" id="sendit">
</form>
<script>
$(document).ready(function(){
$("#sendit").click(function(){
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize();
}).done(function(response) {
alert(response);
});
return false;
});
});
</script>
</div>
example.php
<?php
error_reporting(E_ALL);
ob_implicit_flush(true);
include_once "class.curl.php";
include_once "class.sms.php";
include_once "cprint.php";
$smsapp=new sms();
$smsapp->setGateway('way2sms');
$myno='XXXXXXX';
$p='XXXXXXXX';
$tonum=$_POST['tono'];
$mess=$_POST['message'];
cprint("Logging in ..\n");
$ret=$smsapp->login($myno,$p);
if (!$ret) {
cprint("Error Logging In");
exit(1);
}
print("Logged in Successfully\n");
print("Sending SMS ..\n");
$ret=$smsapp->send($tonum,$mess);
if (!$ret) {
print("Error in sending message");
exit(1);
}
print("Message sent");
?>
This reloads the page but doesn't submit the form and if i add action attribute to form it redirects to example.php and successfully sends sms.
I see you are returning false in the handler, which is basically the same as using event.preventDefault(), but this is not working because you have a syntax error (a semicolon that should not be there):
$(document).ready(function () {
$("#sendit").click(function () {
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize() // You have ";" here, and it's causing the rest of the code to fail.
}).done(function (response) {
alert(response);
});
return false;
});
});

Input validation through AJAX

I have the following AJAX in my index.php:
$(document).ready(function() {
$('.buttono').click(load);
});
function load() {
$.ajax({
url: 'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data) {
$('#content').append(data);
});
}
HTML (part of index.php):
<form method="POST" action="">
<input type="text" name="input">
<input type="submit" name="submit" class="buttono" value="Convert">
</form>
<div id='content'></div>
And in my ajaxRequest.php I have the following PHP snippet:
if ($_POST['input'] == 'dog') {
echo 'Status 1';
} else if ($_POST['input'] == 'cat') {
echo 'Status 2';
}
How can I perform the PHP check through AJAX? So that if I click the submit button and have typed 'dog', to return the string Status 1?
Well what I see in your code is that:
first you have not specified your request method,
second you have not set $_POST['dog']
I would have gone with this ajax:
$.ajax({
type : "POST",
url : 'to/url',
data : { input : $("input[name='input']").val() },
success : function(data){
// do whatever you like
}
});
What you have to do is make the user fill out the form and then instead of clicking a type="submit" button just make them click a regular button. Then when that person clicks the regular button submit. You can do this by:
<!-- HTML -->
<form method="POST">
<input type="text" id="type"/>
<button id="submit">Sumbit</button>
</form>
<!-- JS -->
$(document).ready(function(){
$('#submit').click(onSubmitClicked);
});
function onSubmitClicked(){
var data = {
"input": $('#type').val()
};
$.ajax({
type: "POST",
url: "url/To/Your/Form/Action",
data: data,
success: success
});
function success(data){
if(data == 'status 1'){
//Do something
}
}
}
Try this:
in you php file:
$res = array();
if ($_POST['input'] == 'dog') {
$res['status'] = '1';
} elseif ($_POST['input'] == 'cat') {
$res['status'] = '2';
}
echo json_encode($res);
Then in your jquery:
function load(){
$.ajax({
type : "POST",
data : { input : $("input[name='input']").val() },
url:'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data){
$('#content').append(data.status);
});
}

Callback message for php form

I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>

Submit form (jquery) and show results in colorbox

I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>

Categories