Redirecting After a Form Submission - javascript

How can I make this form redirect the user to an external site, for example http://amaze.bg, after the user submits the form with the "Register" button and after the form sends the e-mail to antoniya.p#amaze.bg with the entered by the user details?
Here is the PHP code (contact_process.php):
<?php
usleep(500000);
$to = "antoniya.p#amaze.bg";
$author = "";
$email = "";
$comment = "";
$class = "FORM CONTACT ";
if (isset($_POST['input_name']))
$author = $_POST['input_name'];
if (isset($_POST['input_email']))
$email = $_POST['input_email'];
if (isset($_POST['input_class']))
$class = $_POST['input_class'];
if (isset($_POST['input_message']))
$comment = $_POST['input_message'];
$sub="Alumni registration recieved - ".$date1;
$name=$authorlast."< ".$email." >";
$msg = '';
if (#mail($to,$sub,$body,"Content-Type: text/html; charset=iso-8859-1"))
{
$msg = 'Your registration was sent successfully';
//echo '<div class="alert success pngfix">'. $msg .'</div>';
}
else{
$msg = 'Email failed to be sent (mail function not work)';
//echo '<div class="alert error pngfix">'. $msg .'</div>';
}
echo $msg;
?>
And here is the .js part:
jQuery.validator.addMethod(
"math",
function(value, element, params) {
if (value==='')
return false;
return this.optional(element) || value == params[0] + params[1];
},
jQuery.format("Please enter the correct value for {0} + {1}")
);
$('.form-register').validate({
rules: {
input_name: {
minlength: 3,
required: true
},
input_email: {
required: true,
email: true
},
input_message: {
minlength: 0,
required: false
}
,
submitHandler: function(form) {
var a=$('.form-register').serialize();
$.ajax({
type: "POST",
url: "contact_process.php",
data:a,
complete:function(){
},
beforeSend: function() {
},
success: function(data){
if (data=='success') {
$('.form-register').find("input[type=text], textarea").val("");
alert('You have successfully registered. Thank you for being active alumni!');
} else {
alert(data);
}
},
error : function() {
}
});
return false;
}
});
});
Thank you for the help.

After some experiments and help from Charlie I managed to find where and what exactly to add to the code, so that the form sends the information to the server and them redirects the user to another website. The change should be made in the .js file with the addition of the following line:
location = "http://amaze.bg/"
But it should be added under "else" in the .js file, with the "alert" being under "success" for everything to work properly:
success: function(data){
if (data=='success') {
alert(data);
} else {
location = "http://amaze.bg/"
}
},
error : function() {
}

In Your Success Callback, Add location = "http://amaze.bg"
success: function(data) {
// if you echo "success" in your php script when the mail is sent
if (data === 'success') {
$('.form-register').find("input[type=text], textarea").val("");
alert('You have successfully registered. Thank you for being active alumni!');
// Now redirect
location = "http://amaze.bg"
} else {
// if you echo "Some Error Message" from your php script
alert(data);
}
},
Ultimately, You should be sending the proper headers from php so that the success hook in your $.ajax fires on a 200 Status Code and the error hook fires in your $.ajax when a 400 - 500 Status Code is encountered. Please look into HTTP Status Codes and Sending Proper Headers in PHP

Related

How to fix 'JSON Parse Error: unexpected identifier array' when making an AJAX Request

I'm setting up a Contact Form Validation and i need the variable $msg from a php script 'sendEmail.php'. The actual mailing system is working, the script is receiving the form input's from index.php and is working(Successfully sending emails)...
The thing is the 'success: function(data)' isn't working, and have been couple days trying to figure out what i'm doing wrong
I've tried to change to $.post function, compared a lot of examples similar, debugging with the 'error:' function...
The error displays on the console 'console.log(errorThrown)'
I'm using Safari and i get this from the XHRs folder from the sendEmail.php:
Output:
array(3) {
["name"]=>
string(12) "asfasfasfasf"
["email"]=>
string(9) "asfasfasf"
["message"]=>
string(0) ""
}
{"code":404,"msg":"Please fill in all fields"}
// AJAX Call
$.ajax({
type: "POST",
url: "php/sendEmail.php",
dataType: "json",
data: {
name: name,
email: email,
message: message
},
success: function(data) {
if (data.code == '200') {
$('.alert-success').html(data.msg);
$('.alert-success').css('display', 'block');
} else {
$('.alert-danger').html(data.msg);
$('.alert-danger').css('display', 'block');
}
},error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
// Error Message
$msg = '';
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
// Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
var_dump($_POST);
// Verifications
if (!empty($name) && !empty($email) && !empty($message)) {
// Name Check
if (strlen($name) <= 4 || strlen($name) >= 30) {
$msg = 'Please type a name between 4 and 30 characters';
} else {
// Email Check
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = 'Please provide a valid email';
} else {
// Message Check
if (strlen($message) < 10) {
$msg = 'Please provide a message superior to 10 characters';
} else {
// Send Email
$msg = 'Email was sent successfully...';
echo json_encode(['code' => 200, 'msg' => $msg]);
exit;
} catch (Exception $e) {
$msg = 'Error: Email was not sent...';
}
}
}
}
} else {
$msg = 'Please fill in all fields';
}
}
echo json_encode(['code' => 404, 'msg' => $msg]);
``
After checking you code and this:
array(3) {
["name"]=>
string(12) "asfasfasfasf"
["email"]=>
string(9) "asfasfasf"
["message"]=>
string(0) ""
}
{"code":404,"msg":"Please fill in all fields"}
I realize that you have a var_dump in your code at this point:
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
// Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
var_dump($_POST); // <---- Remove this and everything should be okay
Hope it hepls

How to send file information when uploading img via ajax

I am attempting to split up image file uploading to an ajax method. All of the html and JS is in one file and then I made up a PHP file that contains all of the PHP.
What I am struggling with is I am not sure how to send the image file info over to the php file and then for the rest of the php to work as it used to.
As of now, this line of code $p_img = $_POST['file']; is getting an undefined index error. However, even if that is populating, I am not sure if this will work correctly with the files being seperated.
Is there anyway that I can leave my first PHP function, UploadFile in the file with the HTML and JS and then send the function over to the PHP file?
IF not, what can I do?
HTML
<form action="" method="POST" id="projectForm" enctype="multipart/form-data">
<label>Project Name</label>
<input type="text" class="input block" name="p_name">
<label>Project Img</label>
<input type="file" id="file" name="file" class="file-input block">
<button id="submit">Submit Project</button>
</form>
JS
$('#projectForm').validate({
ignore: [],
rules: {
p_name: {
required: true,
minlength: 5
},
p_alt: {
required: true,
minlength: 2
}
},
messages: {
p_name: {
required: "Please enter the project name",
minlength: "The project name is too short"
},
p_alt: {
required: "Please enter the alt text",
minlength: "Your alt text is too short"
}
},
submitHandler: function (form, e) {
e.preventDefault();
var formData = new FormData(form);
category = $(this).data('category');
console.log(category);
$.ajax({
url: '/php/projectSend.php',
type: 'POST',
data: formData,
success: function (data) {
console.log(data);
},
contentType: false,
processData: false,
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
alert('There are currently no project images for this selection');
}
});
}
});
PHP
ini_set('display_errors', 1);
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$p_name = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$p_img = $_POST['file'];
$p_alt = trim(htmlspecialchars($_POST['p_alt']));
$category = trim(htmlspecialchars($_POST['categoryName']));
$creator = trim(htmlspecialchars($_POST['creatorName']));
$status = $_POST['status'];
function UploadFile($fileArray = array(), $destinationFolder = '../project_images/') {
$filename = $fileArray['file']['name'];
$tmp_name = $fileArray['file']['tmp_name'];
$filesize = $fileArray['file']['size'];
$file_error = $fileArray['file']['error'];
$file = $fileArray['file'];
// Save all the default data.
$return['error'] = true;
$return['success'] = false;
$return['file']['dest'] = $destinationFolder.$filename;
$return['file']['size'] = $filesize;
if($file_error == 0)
$return['error'] = false;
if(!is_dir($destinationFolder))
mkdir($destinationFolder,0755,true);
// If your filename is not empty, return success or fail of upload
if (!empty($filename))
$return['success'] = (move_uploaded_file($tmp_name, $destinationFolder.$filename));
return $return;
}
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function SaveToDb($con,$filename = false) {
// Return fail immediately if the connection is false or image is invalid
if(empty($filename) || !$con)
return false;
$project_sql = "
INSERT INTO quotes
(p_name, p_img, p_alt, category, creator, status, date_added)
VALUES(?, ?, ?, ?, ?, ?, NOW())
";
if ($project_stmt = $con->prepare($project_sql)) {
$project_stmt->execute(array($p_name, $p_img, $p_alt, $category, $creator, $status));
return true;
$proj_succ = "Success";
echo json_encode($proj_succ);
}
return false;
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['create'])) {
// Try uploading
$upload = UploadFile($_FILES);
// If upload fails
if(!$upload['success']) {
echo '<h3>Sorry, an error occurred</h3>';
}
else {
// Try to save it
$saveToDb = SaveToDb($con,$upload['file']['dest']);
// Get the profile from image name
$profPic = ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;
}
}
I think your form object you are sending to FormData is not what FormData expects.
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function() {
var oOutput = document.querySelector("div"),
oData = new FormData(form);
}
you can read more
That's because you're trying to access the uploaded file via the $_POST array, which doesn't include files. What you're looking for is $_FILES.
Reference

Unable to use callback to get response from ajax call

I'm using the jQuery Validator plugin to try to check whether an email address getting entered into the form is unique after an ajax call which passes the email to a script which checks to see if the email is already in the database. I'm using a callback function to try to get the results of the ajax query but the function always returns undefined. I'm not sure what I'm doing wrong. Here is the code:
jQuery.validator.addMethod("unique", function () {
function foo(callback) {
$.ajax({
type: 'POST',
async: true,
url: '/form_processor',
data: 'action=email_validate&email=' + $("#email").val(),
success: callback
});
}
var return_value = foo(function (result) {
if (result !== 'g') {
return false;
} else {
return true;
}
});
alert(return_value);
}, "Email address taken. Choose another.");
If you are using jquery validator, in built method is their to validate, So your validate code will like,
$(document).ready(function(){
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "form_processor",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
},
messages:
{
email:
{
required: "Please enter your email address.",
remote: "Email already taken"
}
}
});
})
In server side you have to return (print) true or false code will be (if you are using php)
<?php
$email = $_POST['email'];
$query = "SELECT ID FROM users WHERE user_email = "$email" LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>

Login validation not working on HTML using JSON and PHP

I am making a login form on HTML using JSON and PHP but all of the if statements on success are not working but the beforeSend and error is working. Can you help me check my mistakes?
I dont know know what is wrong with the function on success. The alerts are not popping up. For example response.success == true is supposed to pop up ' You are successfully logged in... '
<script>
$(document).ready(function(){
$('#loginForm').on('submit',function(e){
var myForm = new FormData($(this)[0]);
$.ajax({
type:'POST',
url: 'connections/login.php',
data : new FormData($(this)[0]),
cache: false,
contentType:false,
processData: false,
beforeSend: function(){
$("div#divLoading").show();
},
success: function(response){
$("div#divLoading").hide();
console.log(response);
if(response.success == true)
{
alert(' You are successfully logged in... ')
}
else if( response.success == false ){
alert('please enter a correct email & password');
}
else{
if(response.matric){
alert('email is wrong');
}
if(response.password){
alert('password is wrong');
}
}
},
error: function(data){
alert('error');
$("div#divLoading").hide();
}
});
return false;
});
});
</script>
Here is my PHP:
<?php
require_once('connect.php');
session_start();
header('Content-Type: application/json');
if (!empty($_POST['matric']))
{
$matric=$_POST['matric'];
$password=$_POST['password'];
$pass= $dbh->prepare("SELECT * FROM users WHERE matric=:matric AND password=:password");
$pass->bindParam(':matric', $matric);
$pass->bindParam(':password', $password);
$pass->execute();
if($pass->fetch(PDO::FETCH_NUM) > 0)
{
$_SESSION['matric']=$matric;
$response = array(
'success' => true,
'message' => 'Login successful');
}
else
{
$response = array(
'success' => false,
'message' => 'Login fail');
}
}
echo json_encode($response);
echo json_encode($_POST);
?>
You have
echo json_encode($response);
echo json_encode($_POST);
which is going to issue corrupted JSON. e.g. your output is going to be
{"success":true,"message":"Login successful"}Array
^^^^^^---corruption
Since your JSON is corrupted, it won't decode properly, and response WON'T be what you think it is.
Remove this line:
echo json_encode($_POST);

codeigniter ajax loader error

I have a problem with my ajax loader in CI.
This is what I have tried so far:
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('.username').val(),
password : $('.password').val(),
};
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'message'
});
loader.insertAfter($(this));
//.removeClass().addClass('loader').html('<img src="assets/img/ajax-loader.gif">').fadeIn(1000);
$.ajax({ //
url: "<?php echo site_url('login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}
});
return false;
});
});
</script>
c_login.php controller
function ajax_check() {
//if($this->input->post('ajax') == '1') {
if($this->input->is_ajax_request()){
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user) {
echo 'login successful';
//echo '<img src="assets/img/loader-bar.gif"> Hello!';
//$this->load->view('welcome');
} else {
echo 'unknown user'; //
//echo ' <img src="assets/img/icon_error.gif"> Username or password not valid';
}
}
}
}
UPDATE:
The problem is, it's just displaying the loader infinitely.
What I want to do is, if the user is valid, will show the loader.gif and then redirect to main page else will display the username or password incorrect. What is wrong with my code? Any ideas? Thanks.
It seems that you named your loader as "message" instead of creating a "message" new element and name your loader as "ajax_loader".
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'ajax_loader'
});
var message = ...
...
'id':'message'
.
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}

Categories