How to upload image while using serialize Array in JavaScript? - javascript

I am working on a form which need to insert some data with an image without reloading the page. In my side everything is working fine when there is no image filed in the form, but if there is an <input type="file"> in my form, then my code is not passing the file/image information. Can you guys please teach me what to add in my code to upload or pass image please?
My Code
HTML Form
<form action="action.php" method="POST" enctype="multipart/form-data" id="myform">
<input type="hidden" value="access" name="label">
<input type="text" name="one">
<input type="text" name="two">
<input type="file" name="image">
<button type="submit" id="mybtn">Add Data</button>
</form>
<div id="myresult"></div>
My JavaScript
$('#mybtn').click( function(){
$.post(
$('#myform').attr('action'),
$('#myform:input').serializeArray(),
function(result) {
// Some Stuff...
}
);
});
My PHP
include 'database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$label = ["access"];
if (in_array($_POST['label'], $label)) {
switch ($_POST['label']) {
case 'access':
$one = $_POST['one'];
$two = $_POST['two'];
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_temp = $_FILES['image']['tmp_name'];
$error = [];
$valid = [];
$flag1 = $flag2 = $flag3 = false;
if (!empty($one)) {
// Some validation
$flag1 = true;
} else {
$flag1 = false;
}
if (!empty($two)) {
// Some validation
$flag2 = true;
} else {
$flag2 = false;
}
if (!empty($file_name)) {
// Some validation
$flag3 = true;
} else {
$flag3 = false;
}
if ($flag1 && $flag2 && $flag3) {
// move_uploaded_file() + Insert All data
if ($result) {
$valid[] = "Data added successfully!";
} else {
$error[] = "Please try again later!";
}
} else {
$error[] = "Something went wrong!";
}
// ALERT MESSAGE [error] and [valid]
if (!empty($error)) {
foreach ($error as $value) {
echo json_encode($value);
}
}
if (!empty($valid)) {
foreach ($valid as $value) {
echo json_encode($value);
}
}
break;
default:
# code...
break;
}
}
}
This code works perfectly without reloading page while there are no input type file. I want to know what code I have to add in my JavaScript section to execute the code successfully with an input type file.

$('#dataBtnIMG').click( function(){
var form = $('#dataFormIMG');
var formData = new FormData($('#dataFormIMG')[0]);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: formData,
cache: false,
contentType: false,
processData: false,
success:function(result) {
// Some Stuff
}
});
});

Related

why required not working while uploading image with cropper js in php

Hello guys i am building a project where i have used cropper js to crop the uploaded image everything is working fine with my codes like file is getting cropped getting uploaded to database as well but the problem is while i want to check that the file field should not be empty i am using the required but its not working i am pasting the codes that i have used till now can you guys please see what do i need to do to rectify the errors please.
HTML
<form id="partyins" class="needs-validation" action="" method="post" enctype="multipart/form-data" novalidate>
<div class="col-md-12" style="padding:5%;">
<input type="file" id="image" class="form-control" required>
<input type="hidden" name="product_id" id="product_id" value="<?php if(isset($_GET['product_id'])){ echo $_GET['product_id']; } ?>">
<button type="submit" class="btn btn-success btn-block btn-upload-image mt-4" style="margin-top:2%">Upload Image</button>
</div>
</form>
JS PART
var resize = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: { // Default { width: 100, height: 100, type: 'square' }
width: 64,
height: 64,
type: 'circle' //square
},
boundary: {
width: 300,
height: 300
}
});
$('#image').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
resize.croppie('bind',{
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$("#partyins").submit(function(e){
e.preventDefault();
var prod_id = $('#product_id').val();
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
if(img == ''){
toastr.error("Please upload a file",'Error');
}
$.ajax({
url: "model/product_image/product_image.php?insertimg&imgid="+prod_id,
type: "POST",
data: {"image":img},
success: function (data) {
var res = data;
if(res==8){
toastr.error("Sorry! There is an error",'Error');
}else if(res==9){
toastr.error("Please upload a file",'Error');
}else{
toastr.success(data,'Update');
$('#partyins')[0].reset();
}
}
});
});
});
PHP
if(isset($_GET['insertimg']) && isset($_GET['imgid'])){
$id = $_GET['imgid'];
$image = $_POST['image'];
list($type, $image) = explode(';',$image);
list(, $image) = explode(',',$image);
$image = base64_decode($image);
$image_name = 'product_id'.$id.'_'.time().'.png';
file_put_contents("../../../upload_products/".$image_name, $image);
if(!$image == ''){
$sql_inst = "UPDATE $tb_products SET `p_upload`='$image_name' WHERE id='$id'";
$res_inst = mysqli_query($conn,$sql_inst);
if($res_inst){
echo "Updated Successfully";
}else{
echo 8;
}
}else{
echo 9;
}
}
You can do it in this way I hope it may work
var image = $('#image').val();
if(image == ''){
toastr.error("Please upload a file",'Error');
}else{
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
$.ajax({
url: "model/product_image/product_image.php?insertimg&imgid="+prod_id,
type: "POST",
data: {"image":img},
success: function (data) {
var res = data;
if(res==8){
toastr.error("Sorry! There is an error",'Error');
}else if(res==9){
toastr.error("Please upload a file",'Error');
}else{
toastr.success(data,'Update');
$('#partyins')[0].reset();
}
}
});
});
}

Problem with uploading a image via Ajax Call in php?

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:
HTML File:
<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">
<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>
Ajax Call:
<script>
function createDocsVerify () {
var data = {
'photo1' : jQuery('#photo1').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/sellerdocsverify.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Php File: sellerdocsverify.php
if (isset($_POST['photo1'])) {
$photo1 = sanitize($_POST['photo1']);
// var_dump Output: string(20) "C:\fakepath\0553.jpg"
}
$errors = array();
$required = array(
'photo1' => 'Please select Photo 1',
);
// check if all required fileds are fill out
foreach ($required as $field => $display) {
if (empty($_POST[$field]) || $_POST[$field] == '') {
$errors[] = $display.'.';
}
}
$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();
**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**
$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];
$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];
$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;
if ($mimeType != 'image') {
$errors[] = 'The file must be an image.';
}
if (!empty($errors)) {
echo display_errors($errors);
}else{
echo 'passed';
// upload file and insert into database
if ($photoCount > 0) {
move_uploaded_file($tmpLoc1, $uploadPath1);
}
$insertSql = "INSERT INTO docTable (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);
$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
}
?>
Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.
Any idea or suggestion would be welcome.
You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false. Your javascript should look like this:
<script>
function createDocsVerify() {
var formdata = new FormData();
var file = jQuery('#photo1').prop('files')[0];
formdata.append('photo1', file);
//Ajax call Start Here
jQuery.ajax({
url: '/myproject/adminseller/sellerdocsverify.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
That should upload the photo.

Using AJAX to authorise form with database value

I have a form that requires 'authorization' - where the user needs to enter one of the authorization codes stored in a database to be able to submit the form (basically a password). I'm trying to use AJAX with PHP to both display (using Bootstrap's feedback glyphicons) a tick or cross depending on whether or not the user entered a valid value and allow or prevent form submission. If the user did not enter a valid value, form submission is prevented.
My code below currently isn't working, any help would be greatly appreciated.
HTML:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>
<form name="auth_form" id="auth_form" method="post" action="action.php">
<p>Please enter authorisation code.</p>
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<input class="form-control" id="auth_code_input" autocomplete="new-password" name="auth_code_input" type="password" required>
<span class="form-control-feedback glyphicon" id="statusIcon"></span>
</div>
<button class="btn btn-success btn-ok" name="Submit" id="submit" type="Submit">Submit</button>
</form>
JS:
<script>
$(document).ready(function() {
// Validate on blur and display 'cross' icon in span if invalid, tick if valid
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// Validate on submit and prevent form submission if invalid
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
})
});
// AJAX to check the auth-code server-side
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
var response = valid;
if valid = '1' {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
</script>
checkauth.php
<?php
error_reporting(E_ALL);
ini_set( 'display_errors', 1);
$given_code = $_REQUEST['given_code'];
include 'pdo_config.php';
$valid = '0';
try {
$conn = new PDO($dsn, $user, $pass, $opt);
$stmt = $conn->prepare("SELECT instructor_id, auth_code FROM tbl_instructors WHERE auth_code = :given_code;");
$stmt->bindParam(':given_code', $given_code);
$stmt->execute();
$row = $stmt->fetchColumn();
if ($row == 1) { // row equals one, means auth-code corresponds to an instructor and is valid
$valid = '1';
} else {
$valid = '0';
}
echo valid;
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
found some errors in your js, function ValidateInput() {, plz update your code from below one.
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
if (response == '1') {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
if it still not work, then plz add async: true in your ajax call like this,
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code,
async: true
});
It will work definitely

Successful ajax script doesn't give me response

The general problem is that I cannot get back echo or return through ajax from another file.The alert(msg) is empty. Does that prevent.default stop sending the GET? I am not very fluent in programming, could you please help me in this?
I have my simple form:
<form class='findAndBlock1' method="GET" action="">
<input type='text' name="nameToBlock1" placeholder=" who do you want to block?" class='nameInput'>
<input type='submit' value="Search" class='submitInput1'>
</form>
After clicking it, the ajax script starts:
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg);
},
error : function(error) {
alert('error');
}
});
});
</script>
It is directed to the script that is routed like this:
Route::any('/searchFriendsToBlock', 'SettingsController#searchFriendsToBlock');
Here is the script that is run through ajax:
public function searchFriendsToBlock() {
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
echo "hello";
return Response::json($newArr);
}
Use dataType parameter in ajax request as you are sending response in json format the default dataType is set to html in jQuery.ajax()
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg.type);
},
error : function(error) {
alert('error');
}
});
});
</script>
And Your script should be like this
public function searchFriendsToBlock()
{
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
$response = array();
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
$response['type'] = 'sussess';
$response['data'] = $newArr;
return Response::json($response);
}

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

Categories

Resources