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);
}
});
});
});
Related
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
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>
I have form that has one text input field and a button. On submit form, I take the value from the text field user and make an ajax call to ajax.php to then have the server return the userID. The server is indeed returning a value as shown in the console. But I am not sure why the ajax call is failing on each request after submitting the form. What can I correct or change to have a success?
index.php
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
var getUser = $.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
dataType:'text'
});
getUser.done(function( data ) {
alert(data);
});
getUser.fail(function( jqXHR, textStatus, data ) {
alert( "Request failed: " + textStatus );
});
});
<form id="search" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="GET">
<label for="user"> Username:</label><input type="text" name="user" id="user" value="<?php echo $user ?>"><br>
<button type="submit" id="search">Search</button>
</form>
ajax.php
if(!empty($_GET['user'])){
$user = $_GET['user'];
echo getInstaID($user); // this prints a numeric value like 2057821
}
Perhaps the data is being returned as json or jsonp? You have specified dataType: 'text'. If the return datatype is different it will error out. If you are using a fairly recent version (I think 2.0 or better) leaving out dataType or specifying dataType:"auto" will allow the call to succeed. Then you can debug to figure out how to handle the response.
You might try adding a success function like the following:
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
success:function(data){//begin success function
//do something with the data returned from ajax.php file
alert(data);
}//end success function
});
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.
I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});