$_POST variables not passed by form - javascript

I'm hosting a simple contact form on App Engine using PHP, trying to pass $_POST variables from a form to a PHP script that sends the email. As I can read from the logs, the $_POST variables don't seem to get through and I struggle to understand why... hence would appreciate another pair of eyes on this... thank you. Here are the various bits of (simplified) code:
Within index.html at the root:
<form method="post" action="#" id="contactform">
<div>
<label for="email">Enter your email</label>
<input type="text" class="input-field" id="email" name="email" value="">
</div>
<a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Send E-Mail</a>
<div id="success">Your message has been sent successfully!</div>
<div id="error">Unable to send your message, please try later.</div>
</form>
The PHP file, also at the root:
<?php
$send_email_to = "test#test.com";
$email_subject = "Email subject line";
function send_email($email,$email_message)
{
// using AppEngine's mail function here
}
function validate($email,$message)
{
// a simple validation function
}
if(isset($_POST['email'])) {
$email = $_POST['email']; // this doesn't seem to work
}
else
{$email = "email#email.com";} // did this to confirm the $_POST didn't seem to be passed
$return_array = validate($email,$message);
if($return_array['success'] == '1')
{
send_email(,$email,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
And the javascript that controls the error messages:
$('#button-send').click(function(event){
$('#button-send').html('Sending message...');
event.preventDefault();
$('html, body').scrollTo( $('#contact'), 'fast' );
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#contact_form').serialize(),
success: function(html) {
if(html.success == '1')
{
$('#button-send').html('Send message');
$('#success').show();
}
else
{
$('#button-send').html('Send message');
$('#error').show();
}
},
error: function(){
$('#button-send').html('Send message');
$('#error').show();
}
});
And in case this has to do with App Engine, my app.yaml looks like this:
- url: /js
static_dir: js
- url: /send_form_email.php*
script: send_form_email.php
- url: .*
script: index.html
Many thanks again – I've also put the full code on my Google Drive: https://drive.google.com/file/d/0B4yzSrEzbZ5jbk1oc2RWb2xSRWM/edit?usp=sharing

You are trying to serialise #contact_form but you have id="contactform"
The MIME type for JSON is application/json, not text/json.

Related

JavaScript Misbehaviour

I am trying to send my form data to an .php file with AJAX but JS is misbehaving
, what actually happens is that when i leave the input fields empty every thing works fine (i.e. the php program executes and make changes in my database as expected) but when i fill form data , like when i fill name , email ,password my client side page refreshes and php file dosent gets executed .
Sorry for any grammatical mistakes .
I appreciate any help from anyone !
Thanks alot !
var form = document.getElementById("form_signup");
var formdata = new FormData(form);
$('#form_signup').on('submit', function(ev) {
console.log(formdata);
ev.preventDefault();
$.ajax({
url: "./process_php/Signup1.php",
data: $('form').serialize(),
cache: false,
processData: false,
contentType: false,
type: "POST",
success: function(response) {
console.log("done" + response);
}
});
return false;
});
<?php
if (!isset($_REQUEST['username'])) {
die();
}
$username = "temp_username";
$email = "temp_email";
$password = "temp_password";
$sqlconnection = new mysqli("", "", "", "");
$insertstatement = "INSERT INTO new_users (Name , Email , Password , Subscriber ) VALUES ('$username' , '$email' , '$password' , 'Normal' ) ";
if ($sqlconnection->query($insertstatement) === TRUE) { //if entered into db successfully
echo "DONE";
}else {
//run js to inform
}
?>
<!--I have loaded jquery and also my external js file-->
<form class="font1" id="form_signup">
<!-- main content , signup form -->
<h2 id="form_name" class="font1">LOGIN</h2>
<input type="text" name="username" placeholder="Username" minlength="3" autofocus id="username"><br>
<input type="email" name="email" placeholder="Email" minlength="10"><br>
<input type="password" name="pass" placeholder="Password" minlength="8"><br>
<input type="submit" value="Confirm">
</form>
Seems problem with $('form').serialize(). Here form is not the one same as var form = document.getElementById("form_signup");
$('#form_signup').on('submit', function(ev) {
console.log(formdata);
ev.preventDefault();
$.ajax({
url: "./process_php/Signup1.php",
data: $('#form_signup').serialize(),
// rest of the code

How to obtain response from form submitted by AJAX?

I want to use Acymailing Joomla! component installed at example.com/mailer to manage subscriptions from non Joomla site on example.com
In that case I have simple script
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize(),
success: function () {
swal('Great success!');
}
});
});
});
and form
<form class="form-inline" action="https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub" method="post">
<div class="form-group">
<label class="sr-only" for="user_name">Email address</label>
<input id="user_name" type="text" name="user[name]" value="" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="user_email">Password</label>
<input id="user_email" type="text" name="user[email]" value="" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Sign Up!</button>
<input type="hidden" name="user[html]" value="1" />
<input type="hidden" name="acyformname" value="formAcymailing1" />
<input type="hidden" name="ctrl" value="sub"/>
<input type="hidden" name="task" value="optin"/>
<input type="hidden" name="redirect" value="https://example.com"/>
<input type="hidden" name="option" value="com_acymailing"/>
<input type="hidden" name="visiblelists" value=""/>
<input type="hidden" name="hiddenlists" value="1"/>
</form>
Everything works fine except success, error states...
Joomla Acymailing have sub.php file to handle ajax responses
if($config->get('subscription_message',1) || $ajax){
if($allowSubscriptionModifications){
if($statusAdd == 2){
if($userClass->confirmationSentSuccess){
$msg = 'CONFIRMATION_SENT';
$code = 2;
$msgtype = 'success';
}else{
$msg = $userClass->confirmationSentError;
$code = 7;
$msgtype = 'error';
}
}else{
if($insertMessage){
$msg = 'SUBSCRIPTION_OK';
$code = 3;
$msgtype = 'success';
}elseif($updateMessage){
$msg = 'SUBSCRIPTION_UPDATED_OK';
$code = 4;
$msgtype = 'success';
}else{
$msg = 'ALREADY_SUBSCRIBED';
$code = 5;
$msgtype = 'success';
}
}
}else{
if($modifySubscriptionSuccess){
$msg = 'IDENTIFICATION_SENT';
$code = 6;
$msgtype = 'warning';
}else{
$msg = $modifySubscriptionError;
$code = 8;
$msgtype = 'error';
}
}
if($msg == strtoupper($msg)){
$source = acymailing_getVar('cmd', 'acy_source');
if(strpos($source, 'module_') !== false){
$moduleId = '_'.strtoupper($source);
if(acymailing_translation($msg.$moduleId) != $msg.$moduleId) $msg = $msg.$moduleId;
}
$msg = acymailing_translation($msg);
}
$replace = array();
$replace['{list:name}'] = '';
foreach($myuser as $oneProp => $oneVal){
$replace['{user:'.$oneProp.'}'] = $oneVal;
}
$msg = str_replace(array_keys($replace),$replace,$msg);
if($config->get('redirect_tags', 0) == 1) $redirectUrl = str_replace(array_keys($replace),$replace,$redirectUrl);
if($ajax){
$msg = str_replace(array("\n","\r",'"','\\'),array(' ',' ',"'",'\\\\'),$msg);
echo '{"message":"'.$msg.'","type":"'.($msgtype == 'warning' ? 'success' : $msgtype).'","code":"'.$code.'"}';
}elseif(empty($redirectUrl)){
acymailing_enqueueMessage($msg,$msgtype == 'success' ? 'info' : $msgtype);
}else{
if(strlen($msg)>0){
if($msgtype == 'success') acymailing_enqueueMessage($msg);
elseif($msgtype == 'warning') acymailing_enqueueMessage($msg,'notice');
else acymailing_enqueueMessage($msg,'error');
}
}
}
And JSON looks like on Joomla side registration to the same form by index.php?option=com_acymailing&ctrl=sub
message Subscribe confirmed
type success
code 3
{"message":"Subscribe confirmed","type":"success","code":"3"}
The question is: how to obtain that submission statuses success, error, already submbited etc on external submission form (at example.com page)?
this simple change may do it for you:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize()
}
}).done(function (data) {
swal('Great success!');
});
});
});
I personally like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
swal('Great success!');
});
since your result is in JSON, that should be more like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
console.log(data); // shows full return object in console
swal('Great success!');
}, "json");
Try the following, I have explained the changes inside comments:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var formdata = $(this).serializeArray(); //i really prefer serializeArray better than serialize (up2u)
$.ajax({
type: 'post',
dataType: 'json', //because your data is json
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: formdata,
success: function (d) {//d is the return/response of your url (your question answer)
swal(
d.type+': '+d.code ,
d.message,
d.type
);
},
error: function(d){
swal(
'Oops..' ,
'Something went wrong!', //your json must be in trouble
'error'
);
console.log(d); //delete this in production stage
console.log(d.responseText); //i add this so you will know what happenned exactly when you get this error. delete this too in production stage
}
});
});
});
I don't feel your ajax had issues, what i can see from the Joomla php code, everytime when you request that joomla URL you will always get a response header status code as 200, so your javascript will always land on success block of ajax code, returning with some json based message, when i checked the joomla acymaling (version 5.8.1 for joomla 3.8.3) code for that controller, i saw on line number 74 they are checking if the request is made using ajax, but missing Access-Control-Allow-Origin in php header which will restrict your outside call so you can replace this if condition from :
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
}
to
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
header("Access-Control-Allow-Origin: *");
}
so to allow calls from any other domain as well, but do remember this can also cause vulnerabilities to you joomla code. also you need to change your HTML form as well add one more hidden field in your HTML :
<input type="hidden" name="ajax" value="1" />
so to allow ajax request by your joomla controller file.
now in your success block of ajax you can make a check something like this :
success:function(data, status, xhr){
var json = $.parseJSON(data);
swal(json.message, json.type);
}
I hope this will help you in acomplishing what you want to, Happy coding.
I also face this type of problem.for solving this type of problem i Put a variable in the success as argument html.
e.g. success(html)
and
console.log(html)
this shows all errors including notices and all. turn on errore_reporting['E_ALL'];. and do not set dataType to 'json' .
Simple solution to your question is :
success: function (data) {
$("#<id_of_tag>").html(data);
}
data : Response returned from the server to your AJAX call
id_of_tag : where you want to display your returned output.
Its just an example, you can decide, what kind of data you want to return and what you want to do with your response.
To answer your question: On Success parameter in function will contain your response.
As in my case, i am returning another JSP page, which i want to display in div tag.
Also check below link : I think it might help you
Best way to check if AJAX request was successful in jQuery

PHP validation not working after implementing AJAX

I have code that validates the input inside the form and displays an error message in the div class="error" if condition is met. However, upon using AJAX to prevent page reload, the PHP validation no longer displays the message but still functions in the background. Does anyone why this is happening? How can I make the PHP validation work again? Thank you for help.
As you can see the validation error is supposed to show in $email_error
<form class="form_pro" action="index.php" method="post" role="form">
<input type="text" class="form" name="E-mail" placeholder="E-mail" value="<?= $email ?>">
<div class="error"><?= $email_error ?></div>
<button name="submit" type="submit" class="action_button"></button>
</form>
PHP
The error message here displays inside the "div" prior to adding AJAX code
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["E-mail"])) {
$email_error = "E-mail is required";
} else {
$email = test_input($_POST["E-mail"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
}
jQuery
After adding this to prevent page reload on submit, the PHP error message no longer shows
$( document ).ready(function() {
$(".form_pro").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "php/interuni_process.php",
data: $(this).serialize(),
success: function(data) {
},
error: function() {
}
});
});
});
1) you need to echo the error message in server side and get the response from server and append it to that div
HTML :
htm_page.php
<form class="form_pro" action="index.php" method="post" role="form">
<input type="text" class="form" name="E-mail" placeholder="E-mail" value="<?= $email ?>">
<div class="error"></div>
<button name="submit" type="submit" class="action_button"></button>
</form>
PHP :destination.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email_error='';
if (empty($_POST["E-mail"])) {
$email_error = "E-mail is required";
} else {
$email = test_input($_POST["E-mail"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
echo $email_error;
}
AJAX : html_page.php
$( document ).ready(function() {
$(".form_pro").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "destination.php",
data: $(this).serialize(),
success: function(data) {
if(data.trim() !='')
{
$('.error').html('<h1>'+data+'</h1>');
}
},
error: function() {
}
});
});
});
Simple PHP error :
<div class="error"><?= $email_error ?></div>
When you simply submit the form and according to your condition the validation fails then $email_error is set and when the page is loaded , server interprets the error and print it.
When you submit through AJAX
It checks the error validate and if fail $email_error is set but as the page s not reloaded is not interpreted . SO when you need to submit through ajax instead of setting the error echo it and it will work fine
You need to modify your PHP to return a response with either success response or the error details and then inside your Javascript "success" function you need to parse the response and if it's an error response you need to update your DOM accordingly.
Simply Ajax doesn't work with PHP validation, because the Ajax error part means that the ajax side failed not the PHP validation !!! so it won't go to the error part if the PHP validation failed, how ever you can still make the submit return false and do something like this in JS&Ajax in the success part:
success: function(data) {
if(data.error)
{
alert(data.error);
return false;
}
As you have prevented the page load, you can not see the error which were rendreing on server and display in frontend.
To achieve this you need edit your jquery code
$( document ).ready(function() {
$(".form_pro").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "php/interuni_process.php",
data: $(this).serialize(),
success: function(data) {
},
error: function(data, errorThrown)
{
$('.error').html(errorThrown);
}
});
});
});

multiple file upload using same form but different input fields using jquery php

I have searched for this thing on stack overflow, I was unable to find a relevant answer to my issue. Please have a look at the code I am using to fetch data and throw it to a php file and upload files to the respective folders and store their link to database. But I am not able to store data. It shows "unable to upload data."
Jquery file:
$(document).on('click','#modalMenu', function(){
var pagename = $("#pagename").val();
var page = 'modalMenu';
var menuname = $("#menuname").val();
var nav = $("#nav").val();
var content = CKEDITOR.instances['content'].getData();
var form_data = new FormData();
var file_data = $('#file').get(0).files[0];
var logo = $('#logo').get(0).files[0];
form_data.append('file', file_data);
form_data.append('logo', logo);
form_data.append('pagename', pagename);
form_data.append('menuname', menuname);
form_data.append('content', content);
form_data.append('nav', nav);
form_data.append('page', page);
$.ajax({
url: 'insert.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
method: 'POST',
success: function(data){
alert(data);
location.reload();
}
});
});
form on some page
<form method="post" role="form" enctype="multipart/form-data" action="javascript:;">
<input type="text" class="form-control" placeholder="Page Name" id="pagename" name="pagename" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Nav Name" id="nav" name="nav" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Menu Name" id="menuname" name="menuname" style="max-width:25%; display:inline" />
<input type="file" name="logo" id="logo" title="Menu Logo" class="form-control" style="max-width:20%; display:inline"/>
<input type="text" class="form-control" placeholder="Summery Part.. Please make it crisp" id="content" name="content" style="max-width:30%; display:inline" />
<script>
var editor = CKEDITOR.replace( "content", {
uiColor: "#ffffff",
filebrowserBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html",
filebrowserImageBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Images",
filebrowserFlashBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Flash",
filebrowserUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files",
filebrowserImageUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images",
filebrowserFlashUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash"
});
CKFinder.setupCKEditor( editor, "../" );
</script>
<input type="file" name="file" id="file" class="form-control" style="max-width:25%; display:inline"/>
<input type="submit" id="modalMenu" name="modalMenu" class="btn btn-success" align="right" value="+" />
</form>
insert.php file
$pageName=$_POST['page'];
if($pageName=='modalMenu'){
$pagename=$_POST['pagename'];
$menuname=$_POST['menuname'];
$nav=$_POST['nav'];
$content=$_POST['content'];
$error=$_FILES['file']['error'];
if($error!=0)
{
echo "Error with File data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$fname=$_FILES['file']['name'];
$ftype=$_FILES['file']['type'];
$fsize=$_FILES['file']['size'];
$ftname=$_FILES['file']['tmp_name'];
$target="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target);
if($ans)
{
$error=$_FILES['logo']['error'];
if($error!=0)
{
echo "Error with Image Data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$logo_name=$_FILES['logo']['name'];
$logo_type=$_FILES['logo']['type'];
$logo_size=$_FILES['logo']['size'];
$logo_tname=$_FILES['logo']['tmp_name'];
$target2="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target2);
if($ans)
{
//save info to database
$con=mysql_connect("localhost","root","");
mysql_select_db("rcg_db",$con) or die (mysql_error());
$target=addslashes($target);
$query="INSERT INTO `modalmenu`(`pagename`, `nav`, `menuname`, `menulogo`, `content`, `readmore`) VALUES ('$pagename','$nav','$menuname','$target' ,'$content','$target2');";
$n=mysql_query($query);
if($n==1)
{
echo "File upload successful! Data is added. Please wait while page reloads";
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait..";
}
}
}
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait.";
}
}
}
Thank you in advance. In case I am not using a good way of coding please do recommend and resolve the issue.
From what I understand you want to send the ajax into PHP but PHP cant save it?
Ill give you an example
jQuery
$(#modalMenu).on('click',function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var age = $("#age").val();
$.ajax({
url: 'insert.php', //point to server-side PHP script
dataType: 'json',
type: "POST",
data:{
"fname" : fname,
"lname" : lname,
"age" : age,
"save" : true
},
success: function(yes){
if(yes.success == true){
window.location.reload(true);
}
}
});
});
PHP
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "INSERT INTO beneficiary (fname, lname, age)
VALUES ('$fname','$lname','$age')";
$result = mysql_query($sql);
echo json_encode(array(
"success" => true,
));
refer the below link, i think this is useful for you
http://www.codexworld.com/upload-multiple-images-using-jquery-ajax-php/

run full php-script in ajax/jquery

Sorry for my bad english. I'm trying to run a PHP function through an ajax script. The PHP script should run as a FULL NORMAL php script. My idea is to run a recaptcha by a Submit button WITHOUT refreshing the page. That is working, but I found no way to run a normal php script after that. Here is the part of my script.
php:
if( isset( $_REQUEST['startattack'] )){
$secret="********************";
$response=$_POST["g-recaptcha-response"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<script type='text/javascript'>alert('failed!')</script>";
} else if ($captcha_success->success==true) {
echo "<script type='text/javascript'>alert('success!')</script>";
}
}
html:
<form method='post' id="myform">
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>
ajax:
<script>
$(function () {
$('button').bind('click', function (event) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('button').serialize(),
success: function () {
alert('button was submitted');
type: 'post';
url: 'post.php';
}
});
event.preventDefault();// using this page stop being refreshing
});
});
</script>
I want to check the recaptcha here. If correct, it should echo correct in PHP and I want to add feature later. The same with the false captcha.
I think you can simplify things a bit. You don't return the response in the Ajax is your main problem.
PHP:
Just echo the returned json from the recaptcha (although I have no idea where you get the g-recaptcha-response key/value, you are not sending it anywhere).
if(isset( $_POST['startattack'] )){
$secret = "********************";
// I have added a key/value in the ajax called "sitekey",
// this might be what you are trying to retrieve?
$response = $_POST["g-recaptcha-response"];
echo file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
exit;
}
AJAX:
I think since the return from the recaptcha is json anyway, just echo it and pick it up on this side:
$(function () {
$('button').bind('click', function (event) {
var statusBlock = $('#status');
statusBlock.text('button was submitted');
$.ajax({
type: 'POST',
url: 'post.php',
data: {
// Not sure if you are trying to pass this key or not...
"sitekey":$('.g-recaptcha').data('sitekey'),
"startattack":true
},
success: function (response) {
var decode = JSON.parse(response);
var alertMsg = (decode.success)? 'Success' : 'Failed';
statusBlock.text('');
alert(alertMsg);
}
});
// using this page stop being refreshing
event.preventDefault();
});
});
Form:
Leave a spot to post the submit status so it doesn't interfere with the return alert dialog window.
<form method='post' id="myform">
<div id="status"></div>
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>

Categories