Posting data with Fancybox 2 - php

I'm using a form within a fancybox window post (Ajax) data to a php page.
If I run the form outside of the Fancybox it works perfectly. Insert - Check. Response - Check. That said, if I run the same page through the Fancybox I get a loading wheel (which persists after I close the overlay).
Form (form_test.php):
<form id="form" method="post" action="">
<input type="text" id="name" name="name" value="Test Name" />
<input type="text" id="email" name="email" value="email#test.com" />
<input type="submit" value="Login" />
</form>
<script type"text/javascript">
$("#form").bind("submit", function () {
$.fancybox.showLoading(); // it was $.fancybox.showActivity(); for v1.3.4
$.ajax({
type: "POST",
cache: false,
url: "test.php", // make sure your path is correct
data: $(this).serializeArray(), // your were using $(form).serialize(),
success: function (data) {
$.fancybox(data);
}
});
return false;
}); // bind
</script>
PHP (test.php):
$name=$_POST['name'];
$email=$_POST['email'];
$query=mysql_query("INSERT INTO members (firstName,email) VALUES('$name','$email')");
if($query){
echo "Data for $name inserted successfully!";
}
else{
echo "An error occurred!";
}
Ideas?

Try
$("#form").bind("submit", function () {
$.fancybox.showLoading(); // it was $.fancybox.showActivity(); for v1.3.4
$.ajax({
type: "POST",
cache: false,
url: "test.php", // make sure your path is correct
data: $(this).serializeArray(), // your were using $(form).serialize(),
success: function (data) {
$.fancybox(data);
}
});
return false;
}); // bind
Now, $.fancybox(data); will return (inside fancybox) whatever you sent from the text.php file so you could return the <div id="message"> from within that file like :
if($query){
echo "<div id='message'>Data for $name inserted successfully!</div>";
} else {
echo "<div id='message'>An error occurred!</div>";
}

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>

AJAX submit form data fails. It works using $_GET when i turn off e.preventdefault

This is my first post here. Sorry if my English appears to be bad.
I attempted to use the following codes to submit form data to my signup/submit/index.php.
Here is my sample HTML
<form name="signup_form" id="signup_form" action="submit">
<input type="text" class="form-control" placeholder="CreateUsername" name="username" id="username" autocomplete="off">
<input type="password" class="form-control" placeholder="CreatePassword" name="password" id="password"></form>
Here is my Ajax
.on('success.form.fv', function(e) {
e.preventDefault();
loadshow();
var $form = $(e.target),
fv = $form.data('formValidation');
// Use Ajax
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $('#signup_form').serialize(), //or $form.serialize()
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="2")
{
swal({
type: "success",
title: "HiHi!",
text: "GoodLuck",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
functionA(username,password).done(functionB);
});
}
else (result=="agent_na")
{
swal({
type: "error",
title: "ERROR",
text: "N/A",
animation: "slide-from-top",
showConfirmButton: true
});
Here goes my PhP
<?php
$params = array();
$gett = $_POST["username"];
parse_str($gett,$params);
print_r ($gett); // it prints an empty array
print_r ($gett); // it prints an empty array
echo $params["username"] // it shows undefined username index
?>
I have attempted to serialize $gett before parse_str it. It returns me (){}[].
Could please assist me on this?? I spent almost 20 hours on this, google and tried a lot. Am new to JS.
I try to keep it simple
HTML
<!-- Include Jquery Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="signup_form">
<input type="text" name="username" placeholder="Enter the user name" />
<input type="password" name="password" placeholder="Enter password here" />
<input type="submit" value="Login" />
</form>
<script>
/* Page loaded */
$(function(){
/* Trigger when the form submitted */
$("#signup_form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "backend.php",
data: form.serialize(), // Checkout the document - https://api.jquery.com/serialize/
success: function(data) {
// handle the return data from server
console.log(data);
}
});
e.preventDefault();
return false;
})
})
</script>
PHP (backend.php)
<?php
// Always check param exists before accessing it
if(isset($_POST['username']) && isset($_POST['password'])){
// Print all the post params
print_r($_POST);
// or by param
// echo "User Name: " . $_POST['username']. " <br />";
// echo "Password: " . $_POST['username']. " <br />";
}
?>
Hope this helps!
This is a sample of how you can debug an ajax call:
Javascript:
$(function(){
$("#signup_form").submit(function(e) {
var formData = new FormData($(this));
$.ajax({
type: "POST",
url: "backend.php",
data: formData,
success: function(data) {
console.log(data);
// if (data.length > 0) ....
}
});
e.preventDefault();
return false;
});
});
PHP:
<?php
if (isset($_POST['signup_form'])){
$params = array();
$gett = $_POST['username'];
parse_str($gett,$params);
print_r ($gett);
echo $_POST['username'];
}else{
die('No $_POST data.');
}
?>
Your php code had some problems in it, you missed a semi-colon and you tried to print from an empty array, calls through ajax won't show any run time errors, and thus you need to be very careful when you're trying to debug an ajax to php call.
Hope this helps.

Prevent submitting form in Ajax

I have a form with
<form id=myform onsubmit=return validate();>
<input type=text id=name name=name>
</form>
In my javascript file I have
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (data.exists){
return false;
}
}
});
return true;
}
This Ajax code check if the returned data has value especially the data.exists. I would like to prevent submit form based on the value of exists.
This
if (data.exists){
return false;
}
does not really work.
Your problem occurs because of async ajax function call, it returns true before ajax data returns.
I haven't checked it, But you can try something like this:
function validate(){
var self = this;
self.preventDefault();
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
self.submit();
}
}
});
return false;
}
$('#myform').submit(function() {
return false;
});
This should do the trick, now the form won't reload the page on pressing enter or a button.
EDIT:
Your form is also missing double-quotes
<form id="myform" onsubmit="return validate();">
<input type="text" id="name" name="name">
</form>
Solution:
I have changed my HTML and I have added onclick event than onsubmit
<form id="myform">
<input type="text" id="name" name="name">
<button type="submit" id="button" onclick="validate();">
</form>
Also in Javascript
I prevent the submit here
$("#button").on("click",function(event){
event.preventDefault();
});
Here is my function to check if not exists data so then submit form
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
$('#myform').submit();
}
}
});

Using jquery ajax to serialize data and submit into mysql database

The problem i have is that whenever it inserts the data into the database it doesn't redirect the user to the invoice.php page. Please guys i really need your help.
This is the html code:
<form method="POST" action="">
<input type="text" name="resident_address" id="resident_address"/>
<input type="text" name="price" id="status"/>
<input type="hidden" name="status" id="status" value="0"/>
</form>
This is the jquery code:
var dataString = $('#applyform').serialize();
$.ajax({
type: "POST",
url: "applyform.php",
cache: false,
data: dataString,
beforeSend: function()
{
$(".apply_error").hide();
},
success: function(html) {
if (html == "true")
{
// You can redirect to other page here....
window.location.href = 'invoice.php';
}
else
{
//window.location.href = 'apply.php';
$("div.apply_error").html("Wrong details").show();
}
}
});
this is the php which is the applyform.php:
if(isset($_POST['Submit']))
{
$result = mysql_query("INSERT INTO mytable (resident_address, price, status) VALUES ('$addressfields', '$price', '$status')");
if($result){
echo "true";
}
}
you are not posting a POST var called "Submit" so your
if(isset($_POST['Submit']))
will always evaluate to false and your mysql query is never executed.

send post variables via jquery(ajax) to php himself document

I'm trying to send post variables to php himself document via jQuery ajax, but after send, the post vars are not set.
the code:
if(isset($_POST['email']) && isset($_POST['pass'])){
do something
}
<form id="form_login_pv">
Email: <input type="text" name="email" id="email"><br>
Password: <input type="password" name="pass" id="pass">
<div class="send_login_button_pv">Login</div>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e){
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
});
</script>
why dont you try to use form submit jquery function.
if(isset($_POST['email']) && isset($_POST['pass']))
{
//do something
}
<form id="form_login_pv" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email: <input type="text" name="email" id="email">
Password: <input type="password" name="pass" id="pass">
<button type="submit" class="send_login_button_pv">Login</button>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e)
{
e.preventDefault(); // just to make sure it wont perform other action
$("#form_login_pv").submit(function(){
//afte server response code goes here
});
});
</script>
Make sure form must have action set.
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
Try this in jQuery ready event:
//you can also use an <input type="submit" value="login" /> instead ofusing a button!
$("#button_id").on("click",function(e){
$("#form_login_pv").submit();
return e.preventDefault();
});
$("#form_login_pv").submit(function(e) {
var email = $('input[name=email]').val();
var pass = $('input[name=pass]').val();
// validate given values here
// if bad value detected, output error and return false;
if(!email.test(YOUR REGEX HERE)) {
$('#error-message').text('Wrong E-Mail Format!');
return false;
}
if(pass.length<6) {
$('#error-message').text('Password to short! At least 6 Characters!');
return false;
}
$.ajax({
type: "POST",
url: "index.php",
data: {
email: email,
pass: pass,
},
success: function(response){
alert("mensaje enviado");
}
});
return e.preventDefault();
});
And don't forget to pervent the form from submitting via HTTP Post!
You can do this by returning false at the end of your button click event.
Or by using a method of your event object e, e.preventDefault();
I suggest to return e.preventDefault(); at the end of your click function!
You also can check if given variables are empty or validate them with javascript, before submitting via ajax!

Categories