I am trying to implement a modal AJAX form. But when I press "Submit" I only receive empty body emails. I guess I have bugs in PHP code.
HTML:
<form class="form" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="text" name="phone" placeholder="Phone">
<input type="submit" value="Submit" >
</form>
Jquery:
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: form_data,
success: function (res) {
swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
}
return false;
});
PHP in feedback.php file:
parse_str($_POST['form_data'], $formdata);
$name = $formdata['name'];
$phone=$formdata['phone'];
$formcontent="From: $name \n Phone: $phone";
$recipient = "email#gmail.com";
$subject = "MAIL HEADER";
mail($recipient, $subject, $formcontent) or die("Error");
EDIT:I am also not getting a "Thank you" message for some reason.
You have an error during sending form data with ajax request. here is your code which is working fine :
JQuery :
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
alert(form_data);
//if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: {'form_data' : form_data },
success: function (res) { alert(res);
//swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
//}
return false;
});
Related
I do not know why php can return value from data.
Below are form:
<form id="emailform" method="post" >
<input type="text" name="email" id="email" value="">
<div class="result"></div>
<input type="submit" name="generate" id="generate" value="Save" >
</form>
and Ajax:
<script>
$(document).ready(function() {
$('#generate').click(function(event) {
event.preventDefault();
email = $('#email').val();
$.ajax({
url: this.href,
type: 'POST',
dataType: 'text',
data:{'email': email},
success: function(html) {
alert(email);
$('.result').html('<p>Thank you for providing email. </p>');
},
error: function() {
$('#emailform').text('An error occurred');
}
});
});
});
</script>
and PHP:
<?php
$email = $_GET['email'];
echo $email;
?>
After click Save button, I run echo $email but it returns nothing. How can you help me for this?
Thank you so much.
You can make the AJAX call like this:
$.ajax({
url: window.location.href+'?email='+email,
type: 'GET',
dataType: 'text',
success: function(html) {
alert(email);
$('.result').html('<p>Thank you for providing email. </p>');
},
error: function() {
$('#emailform').text('An error occurred');
}
});
Or for short https://api.jquery.com/jquery.get/:
$.get( this.href+'?email='+email, function( data ) {
console.log(data);
alert( "Load was performed." );
});
For the receiving PHP part I think you are better off with using: if( !empty ( $_GET ['email'] ) ). empty does the same as isset but at the same time checks if there is a value. With just isset you can still send an empty email.
Since you're sending the data to the page itself you can make it even easier. You can even delete the whole AJAX request if you just change the method in your form to get instead of post
you are using a POST request in you ajax but in the php script you are catching an $_get request try changing your php script to this:
<?php
if (isset($_POST['email']){
$email = $_POST['email'];
echo $email;
}else{
echo 'email is not set';
}
?>
or doing the reverse changing the ajax call to get like #Dj said :
<script>
$(document).ready(function() {
var url = window.location.href;
$('#generate').click(function(event) {
event.preventDefault();
email = $('#email').val();
$.ajax({
url: url+'?email='+email,
type: 'GET',
dataType: 'text',
success: function(response) {
alert(response);
$('.result').html('<p>Thank you for providing email. </p>'+response);
},
error: function() {
$('#emailform').text('An error occurred');
}
});
});
});
</script>
and the php script to :
<?php
if (isset($_GET['email']){
$email = $_GET['email'];
echo $email;
}else{
echo 'email is not set';
}
?>
Just change your $_GET['email'] to $_POST['email'] or change type in ajax call to get and it should work flawlessly.
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.
I am new to jquery and ajax. I have a script here where i need to pass variables to a php file. That php will be then encoded to div#chat-body. I am trying to pass the receiver variable to the load-messages.php via POST but I am getting the following error: "Undefined index: receiver in xxxx/scripts/load_messages.php on line 8". I think there is something wrong with my syntax or im doing this totally wrong.
script.js
$('input#send-message').on('click', function(){
alert("test");
var message = $('input#input-message').val();
var sender= $('input#sender').val();
var receiver= $('input#receiver').val();
if($.trim(message)!=''){
$.post('scripts/messaging.php', {message: message, sender: sender, receiver:receiver}, function(data){
//output after sending message
});
//load message to chat-body div
$.ajax({
url: 'scripts/load_messages.php',
type: "POST",
data: {receiver: receiver},
success: function(data){
$('#chat-body').html(data);
//$('#chat-body').scrollTop($('#chat-body')[0].scrollHeight);
}
});
}});
load-messages.php
<?php
session_start();
require('config.php');
require('chat_functions.php');
$messages = get_msg($_SESSION['user_id'], $_POST['receiver']);
foreach($messages as $message){
if($message['sender'] == $_SESSION['user_id']) {
?><div id = "you_message">
<?php echo '<strong> You: </strong><br />';
echo $message['message'].'<br /><br />';?>
</div><!--you_message-->
<?php
}
else{
?><div id="recipient_message">
<?php echo '<strong>'.get_name($_POST['receiver']).'</strong><br />';
echo $message['message'].'<br /><br />';?>
</div> <!--recipient_message -->
<?php
}
}
?>
It's just simple to pass the values to php file through AJAX call.
Change your AJAX call as shown in below
var message = $('#input-message').val();
var sender= $('#sender').val();
var receiver= $('#receiver').val();
$.ajax({
url: "scripts/load_messages.php",
method: "post",
//data: { "message":$('#input-message').val(),"sender":$('#sender').val(),"receiver":$('#receiver').val()},you can pass the values directly like this or else you can store it in variables and can pass
data: { "message":message,"sender":sender,"receiver":receiver},
success: function(data){
$('#chat-body').html(data);
},
error: function() {
alert('Not OKay');
}
});
and your load-messages.php could be like this`
$receiver = $_POST['receiver'];
echo $receiver;
You're passing an object, not a JSON string :
$.ajax({
type: 'POST',
url: 'scripts/messaging.php',
data: JSON.stringify ({receiver: receiver}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
you can try this then adapt it to your needs, as I just made it a little bit more 'basic' :
your form :
<form action="#" id="form" method="post">
<input type="text" id="sender" name="sender" />
<input type="text" id="receiver" name="receiver" />
<input type="text" id="input-message" name="input-message" />
<input type="submit" id="send-message" value="Post" />
</form>
<div id="chat-body" class="regular"></div>
the jQuery part :
$(document).ready(function(){
$("#send-message").click(function(e){
e.preventDefault(); /* to prevent form default action */
var message = $('#input-message').val();
var sender = $('#sender').val();
var receiver = $('#receiver').val();
$.ajax({
url: "load_messages.php",
method: "POST",
data: { message: message, sender: sender, receiver:receiver },
success: function(html){
alert(html); /* checking response */
$('#chat-body').html(html); /* add to div chat */
}
});
});
});
then, load_message.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$message = $_POST['message'];
echo"[ $sender / $receiver / $message ]"; /* here, you can only echo $message for instance,
then use response to append message to chat window */
?>
I am trying to get get my form to submit without having the page refreshing everytime
However, when I insert the ajax and place the php into a new file the form doesnt submit and I dont understand why?
Any advice would be appreicated!
PHP
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
//Post data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
//mail settings
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
$header = "From: $email";
if($_POST) {
if($name == '' || $email == '' || $phone == '' || $message == '') {
echo $feedback = "<font color='red'> *Please Fill in All Fields!";
}
else {
mail($to, $subject, $body, $header);
echo $feedback = "<font color='green'> *Message sent! You will receive a reply shortly!";
}
}
}
else{
echo $feedback = "<font color='red'> Missing Params";
}
?>
AJAX
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#submitBtn").click(function( event ) {
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>
HTML CODE HERE: http://www.codeply.com/go/e3jAo1WrPl
The .bind() function may be the way to go with this form, since it binds the action of clicking the button to the event handler.
It also may be beneficial to have the event.preventDefault() before your ajax call.
$(document).ready(function(){
$("#submitBtn").bind([boundElement],function( event ) {
event.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
return true;
});
});
I would recommend double-checking the syntax for the bound element in the .bind() parameters. It is single quote marks for referring to a named form element
Example HTML:
This might help you with your problem:
$(document).ready(function() {
$("#contact").submit(function(event) {
event.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
message = $('#message').val(),
occasion = $('#occasion').val(),
dataString = $(this).serialize();
$.ajax({
url: 'php.php',
type: 'post',
data: dataString,
})
.done( function( html ) {
$( '#feedback' ).html( html );
})
.fail( function( response ) {
console.log( response );
});
});
});
Firs of all, you have the form and the submit button, so when you press the button, the event 'submit' is triggered, so you prevent the event to be fired, then you do your coding, the variables, but I cannot understand why you declare all those, if you don't use them, but that's up to you.
Here is a suggestion with using a button in stead of a submit. I commented out the preventDefault, because it is unnecessary in this case -- we are not actually submitting the form. This gives us more control.
The request is submitted. In this case, it obviously fails. In your case, whether or not it fails is going to depend on what you have going on server side.
http://plnkr.co/edit/txuxaFUkgFq9SFDcqUdp
<form action="http://www.yahoo.com" id="contactForm" method="get" target="_blank">
<div class="innerForm">
<label for="name">Name:</label>
<input id="name" name="name" type="text" />
<label for="phone">Phone:</label>
<input id="phone" name="phone" type="text" />
<label for="email">Email:</label>
<input id="email" name="email" type="text" />
<label for="occasion">Occasion:</label>
<input id="occasion" type="text" name="occasion" />
<label id="messageLabel" for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button id="test">test</button>
<!--input type="submit" value="Submit" id="submitBtn" name="submit" onclick="return chk();"/ -->
</div>
<div id="feedback"></div>
</form>
$(document).ready(function(){
$("#test").click(function (event) {
//values
alert("test clicked");
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var message = document.getElementById('message').value;
var occasion = document.getElementById('occasion').value;
var dataString = $("#contactForm").serialize();
$.ajax({
type: "get",
url: "http://www.yahoo.com",
data: dataString,
success: function (html) {
alert("success");
//$('#feedback').html(html);
},
error: function(result){
alert("failure");
}
});
//event.preventDefault();
});
});
Thanks for taking the time to look, guys. I'm creating a pretty basic AJAX contact form using jQuery. The email sends, but upon opening the email there is no POST data, so I just get the strings I defined in the PHP script. On my phone's email client, the content of the email literally says 'undefined'. I've tried adding different types of header data to no avail, and a number of variations on the PHP mail() function.
I am more than willing to adopt an easier solution for a simple AJAX form, so thanks in advance for any new approaches.
Here is the form:
<section id="left">
<label for="form_name">Name</label>
<input name="form_name" id="form_name" type="text" >
<label for="form_email">Email</label>
<input name="form_email" id="form_email" type="email" >
</section>
<section id="right">
<label for="form_msg">Message</label>
<textarea name="form_msg" id="form_msg"></textarea>
<input id="submit" class="button" name="submit" type="submit" value="Send">
</section>
</form>
The jQuery AJAX:
$(function() {
$("#contact .button").click(function() {
var name = $("#form_name").val();
var email = $("#form_email").val();
var text = $("#msg_text").val();
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
return false;
});
});
The PHP script (external file 'email.php'):
<?php
if($_POST){
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
//send email
mail("email#gmail.com", "This is an email from:" .$email, $message);
}
?>
There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
Leave your email.php code the same, but replace this JavaScript code:
var name = $("#form_name").val();
var email = $("#form_email").val();
var text = $("#msg_text").val();
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
with this:
$.ajax({
type: "POST",
url: "email.php",
data: $(form).serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
So that your form input names match up.
You're using the wrong post parameters:
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
^^^^-$_POST['name']
^^^^--$_POST['name']
etc....
The javascript/html IDs are irrelevant to the actual POST, especially when you're building your own data string and don't use those same IDs.
You are using the wrong parameters name, try:
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
//send email
mail("j.andrew.sears#gmail.com", "51 Deep comment from" .$email, $message);
}
You code should be:
<section id="right">
<label for="form_msg">Message</label>
<textarea name="form_msg" id="#msg_text"></textarea>
<input id="submit" class="button" name="submit" type="submit" value="Send">
</section>
Js
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
The PHP:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
//send email
mail("email#gmail.com","My Subject:",$email,$message);
}
?>
Your PHP script (external file 'email.php') should look like this:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
//send email
mail("j.andrew.sears#gmail.com", "51 Deep comment from" .$email, $message);
}
?>