Skip to content

Instantly share code, notes, and snippets.

@georgymh
Last active August 29, 2015 14:25
Show Gist options
  • Save georgymh/7c55446b36060d41f9b6 to your computer and use it in GitHub Desktop.
Save georgymh/7c55446b36060d41f9b6 to your computer and use it in GitHub Desktop.
Sending form data (and image file) through AJAX to PHP.
<?php
require __DIR__ . '/../vendor/autoload.php';
use Respect\Validation\Validator as v;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// First, get the data from the POST request.
$firstName = $_POST["form-first-name"];
$lastName = $_POST["form-last-name"];
$email = $_POST["form-email"];
$password = $_POST["form-password"];
$repeatPassword = $_POST["form-repeat-password"];
$organizationName = $_POST["form-organization-name"];
$description = $_POST["form-description"];
$logo = $_FILES["logo"];
$tagsArray = explode(",", $_POST["form-tags"]);
$address1 = $_POST["form-address1"];
$address2 = $_POST["form-address2"];
$city = $_POST["form-city"];
$state = $_POST["form-state"];
$zipcode = $_POST["form-zipcode"];
$phone = $_POST["form-phone"];
$website = $_POST["form-website"];
$multipleLocations = $_POST["one-or-many-locations"];
// Extra
$typeOfUser = "BusinessCreator";
// Second: before sending to parse.com, validate the data.
// Create validators.
$namesValidator = v::alpha()->length(1,20);
$emailValidator = v::email();
$passwordValidator = v::length(8,50)->string()->not(v::lowercase());
$organizationNameValidator = v::length(3,100);
$descriptionValidator = v::length(8,1000);
$cityValidation = v::alpha();
$stateValidation = v::length(2,2)->alpha();
$zipcodeValidation = v::length(5,5)->numeric();
$phoneValidation = v::phone();
$websiteValidation = v::url();
// Test validators.
var_dump($namesValidator-> validate($firstName));
var_dump($namesValidator-> validate($lastName));
var_dump($emailValidator-> validate($email));
var_dump($passwordValidator-> validate($password));
var_dump($organizationNameValidator-> validate($organizationName));
var_dump($descriptionValidator-> validate($description));
var_dump($cityValidation-> validate($city));
var_dump($stateValidation-> validate($state));
var_dump($zipcodeValidation-> validate($zipcode));
var_dump($phoneValidation-> validate($phone));
var_dump($websiteValidation-> validate($website));
// Fields validation.
// Check individually every validator and return appropriate error.
// If True,
// Keep on
// If False,
// Return error
// Maybe: "please verify your ... in step #"
// Tags validation.
// If there are less than 1 tag
// Return error
// Else
// Traverse array and check if tags are alpha and length between 3 and 20
// If problem with any tag
// Remove tag from array and continue
// Logo validation.
// If there is any picture
// If it's supported
// Continue
// Else (If not supported)
// Return error
// If it's too big
// Shrink and continue
if (fileIsSupported($logo)) {
echo "File is supported.";
} else {
echo "File is unsupported or no file";
}
// Third, create Parse.com objects with the data.
// Lastly, create the new user and store all the data into the Database.
// NOTE: deleted these two steps because they are irrelevant to the GIST :)
} else {
echo "Access Prohibited.";
}
/*
Helper methods.
*/
function fileIsSupported($file) {
switch(strtolower($file['type'])) {
//allowed file types
case 'image/png':
case 'image/gif':
case 'image/jpeg':
case 'image/pjpeg':
return true;
break;
default:
return false;
}
}
?>
$('.registration-form').on('submit', function(e) {
e.preventDefault();
var allow_submit = true;
// We can do some extra validation here if needed.
if ( allow_submit == true ) {
// JSON Object approach (unimportant, just skip).
// var businessInfoJSONObject = {
// "stepOne" :
// {
// "first-name" : $("#form-first-name").val(),
// "last-name" : $("#form-first-name").val(),
// "email" : $("#form-email").val(),
// "password" : $("#form-password").val(),
// "repeat-password" : $("#form-repeat-password").val()
// }
// ,
// "stepTwo" :
// {
// "organization-name" : $("#form-organization-name").val(),
// "description" : $("#form-description").val(),
// "tags" : $("#form-tags").tagsinput('items') // array (bootstrap-tagsinput)
// }
// ,
// "stepThree" :
// {
// "multiple-locations" : ($('#one-or-many-locations').val() == "one") ? false : true, // boolean value
// "address1" : $("#form-address1").val(),
// "address2" : $("#form-address2").val(),
// "city" : $("#form-city").val(),
// "state" : $("#form-state").val(),
// "zipcode" : $("#form-zipcode").val(),
// "phone" : $("#form-phone").val(),
// "website" : $("#form-website").val()
// }
// };
// FormData() approach.
var formData = new FormData($('form')[0]);
formData.append('logo', $('#form-logo')[0].files[0]);
$.ajax({
type: "POST",
url: "register.php",
cache: false,
contentType: false, // THESE TWO
processData: false, // ARE NEEDED.
data: formData,
success: __handleBusinessRegistration
});
}
});
var __handleBusinessRegistration = function Business$HandleBusinessRegistration(replyObj) {
// Right now, we only log the PHP response to the console.
console.log(replyObj);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment