Why could this dropzone.js not be uploading to a live server? - javascript

This implementation of dropzone.js works on my local host, but when I move it to live the files don't end up on the server:
Here's the form:
<form action="submit.php" enctype="multipart/form-data" method="POST">
<label for="fname">First name: </label>
<input type="text" name="fname" id="fname" required />
<label for="lname">Surname:</label>
<input type="text" name="lname" id="lname" required />
<div class="dropzone" id="file-upload"></div>
<button type="submit" id="submit-all">Submit</button>
</form>
I am using AJAX to submit the form:
$(document).ready(function() {
Dropzone.options.fileUpload = {
url: '/submit.php',
autoProcessQueue: false,
paramName: 'file',
uploadMultiple: true,
parallelUploads: 1,
maxFiles: 1,
maxFilesize: 10,
acceptedFiles: 'image/*,.mp4,.mkv,.avi',
addRemoveLinks: true,
init: function() {
dzClosure = this;
document.getElementById("submit-all").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("fname", jQuery("#fname").val());
formData.append("lname", jQuery("#lname").val());
});
}
}
});
});
submit.php
<?php
require_once "db.php";
$target_dir = "uploads/";
echo '<pre>';
if (move_uploaded_file($_FILES["file"]["tmp_name"][0], $target_dir.$_FILES['file']['name'][0])) {
$status = 1;
echo 'uploaded, ';
}
else {
echo 'not uploaded, ';
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
if(mysqli_query($conn, "INSERT INTO CF_form(fname, lname
) VALUES('" . $fname . "', '" . $lname . "')")) {
echo 'sent';
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn);
As I said, this all works on my local host but on the live site the file doesn't appear. I get the 'sent' message and the debugging info is like this:
uploaded, Here is some more debugging info:
Array
(
[file] => Array
(
[name] => Array
(
[0] => IMG_1129.JPG
)
[type] => Array
(
[0] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpriOyPQ
)
[error] => Array
(
[0] => 0
)
[size] => Array
(
[0] => 2181000
)
)
)
sent
The uploads directory is set to 777. Just can't figure out why I'm not getting the files.

Related

How to pass first name and last name parameters to Paystack

I want to store more customer information from my Paystack form such as first name, last name and shipping address, but only email and amount is stored. I discovered this can be done using metadata but I really don't know how to go about it. I'd be glad if anyone can help.
The HTML payment form
<form class="container" id="paymentForm">
<h3>Please fill the form below</h3>
<div class="form-group">
<label for="first_name">First Name</label>
<input class="form-control" type="text" id="first-name" required />
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input class="form-control" type="text" id="last-name" required />
</div>
<input type="text" class="amount" id="amount" value="" hidden>
<div class="form-group">
<label for="email">Email Address</label>
<input class="form-control" type="email" id="email-address" required />
</div>
<div class="form-group">
<label for="address">Shipping Address</label>
<input class="form-control" type="text" id="shipping-address" required />
</div>
<div class="form-submit">
<button type="submit" class="btn btn-primary btn-lg" onclick="payWithPaystack()"> Pay </button>
</div>
</form>
Here's Paystack Js code
const paymentForm = document.getElementById('paymentForm');
paymentForm.addEventListener("submit", payWithPaystack, false);
function payWithPaystack(e) {
e.preventDefault();
let handler = PaystackPop.setup({
key: 'pk_test_xxxxxxxxxx', // Replace with your public key
email: document.getElementById("email-address").value,
amount: document.getElementById("amount").value * 100,
//these three values (first_name, last_name and address) aren't retrieved
first_name: document.getElementById("first-name").value,
last_name: document.getElementById("last-name").value,
address: document.getElementById("shipping-address").value,
ref: 'CLE-BPS' + Math.floor((Math.random() * 1000000000) + 1), // generates a pseudo-unique reference. Please replace with a reference you generated. Or remove the line entirely so our API will generate one for you
// label: "Optional string that replaces customer email"
onClose: function() {
window.location = "https://my-url/?transaction=cancelled";
alert('Transaction cancelled.');
},
callback: function(response) {
let message = 'Payment complete! Reference: ' + response.reference;
alert(message);
window.location = "https://my-url/verify_transaction.php?reference=" + response.reference;
}
});
handler.openIframe();
}
verify_transaction.php
<?php
$ref = $_GET['reference'];
if ($ref == "") {
header("Location: javascript://history.go(-1)");
exit();
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($ref),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer SECRET_KEY",
"Cache-Control: no-cache",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
$result = json_decode($response);
}
if ($result->data->status == 'success') {
$status = $result->data->status;
$reference = $result->data->reference;
$amount = $result->data->amount;
$l_name = $result->data->customer->last_name;
$f_name = $result->data->customer->first_name;
$fullname = $f_name . " " . $l_name;
$customer_email = $result->data->customer->email;
$shipping_address = $result->data->customer->address;
$customer_id = $result->data->customer->id;
$date = date('d-m-Y H:i:s');
include "config.php";
$stmt = $link->prepare("INSERT INTO transactions (status, reference, fullname, amount, customer_email, shipping_address, customer_id, date_purchased) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssss", $status, $reference, $fullname, $amount, $customer_email, $shipping_address, $customer_id, $date);
$stmt->execute();
if (!$stmt) {
echo "Oops...Something went wrong";
} else {
header("Location: https://my-url/success.php?status=success");
exit();
}
$stmt->close();
$link->close();
} else {
header("Location: error.php");
exit();
}
modify your paystack js code to look like this:
metadata:{
custom_field:[
{
first_name: document.getElementById("first-name").value,
last_name: document.getElementById("last-name").value,
address: document.getElementById("shipping-address").value,
}
]
}
so from the code above, I am creating a property, metadata and value is an object, and inside of the object, I am creating another property, custom_field and the value is an array. Place the additional fields you want to add in an object and place it inside of the custom_field property defined. You can place an many object as you want inside the custom_field array defined.
modify your verify_transaction.php to get the values;
After $result = json_decode($response);
$first_name = $result->data->metadata->custom_field[0]->first_name,
$last_name = $result->data->metadata->custom_field[0]->last_name,
$address = $result->data->metadata->custom_field[0]->address,
However, you can echo $response to see where the defined metadata is.

ajax wp remote send form on submit

I am making a newsletter integration with external api , and it works fine but on submit my entire page redirects to admin post php , i have tried to use it without action and adding ajax script to footer but don't exactly know how to use my wp_remote method to send data without refreshing or redirecting my page
<?php
namespace SalesManago;
if (!defined('ABSPATH')) {
die;
}
/**
* Class ZH_SalesmanagoNewsletter
*/
class ZH_SalesmanagoNewsletter extends ZH_Salesmanago {
public function __construct() {
add_shortcode( 'sm_newsletter', array($this, 'newsletter_form' ));
add_action('admin_post_nopriv_newsletter', array($this, 'saveDataNewsletter'));
add_action('admin_post_newsletter', array($this, 'saveDataNewsletter'));
}
public function newsletter_form() {
return "
<div style='height: 300px; display: block; position: relative'></div>
<form id='ajax-newsletter-form' action='". esc_url( admin_url('admin-post.php') ) . "' method='post'>
<label for='email'>Email</label>
<input type='email' name='email' id='email' required>
<input type='hidden' name='action' value='newsletter'>
<input type='submit' name='sm-submit' value='>'>
</form>";
}
public function prepareDefaultNewsletterData()
{
$clientId = SALESMANAGO_CLIENTID;
$apiKey = SALESMANAGO_APIKEY;
$apiSecret = SALESMANAGO_APISECRET;
$data = [
'clientId' => $clientId,
'apiKey' => $apiKey,
'requestTime' => time(),
'sha' => sha1($apiKey . $clientId . $apiSecret),
];
return $data;
}
public function parseNewsletterData(){
$email = $_POST['email'];
$set[0]['contact'] = array(
'email' => $email,
);
return $set;
}
public function saveDataNewsletter(){
if (isset($_POST['sm-submit'])) {
$set = $this->parseNewsletterData();
$params = array(
"upsertDetails" => $set,
"owner" => SALESMANAGO_OWNER,
);
$data = array_merge($this->prepareDefaultSalesData(), $params);
$headers = [
'Content-Type' => 'application/json'
];
$result = wp_remote_post( SALESMANAGO_ENDPOINT .'/api/contact/batchupsertv2',
array(
'method' => 'POST',
'headers' => $headers,
'sslverify' => false,
'body' => json_encode($data)
)
);
}
}
}

Create post and upload image with Ajax (axios) in Wordpress

So I want my users to be able to create a post in the frontend and upload an image with a form I've created.
When the image is uploaded I want to update an ACF-field with the uploaded image.
I've seen some posts on this but none of them are explained any good.
I want to use Ajax and I want to use axios, so please no jQuery. I also use Qs.
The image itself is never uploaded but the file name is inserted in the media library.
Thank you!
HTML
<form enctype="multipart/form-data" method="post" id="register-store-form">
<fieldset class="store-images mb-3">
<label for="store-images">Add images</label>
<input type="file" id="store_images" name="store_images" accept="image/png, image/jpeg">
</fieldset>
<button class="btn btn-primary" id="update-store">Save store</button>
</form>
JS
const Qs = require('qs');
const axios = require('axios');
const saveStoreBtn = document.querySelector('#update-store');
const addStore = document.querySelector('#add-one-more-store');
function saveStore(e) {
const storeName = document.querySelector('#store-name');
const storeImages = document.querySelector('#store_images');
const storeImageFile = storeImages.files[0];
const ajaxData = {
action : 'create_store',
security : shkGlobal.addStore,
name : storeName.value,
image_name : storeImageFile.name,
image_type : storeImageFile.type,
description : storeDescription.value
};
axios.post(shkGlobal.adminUrl, Qs.stringify(ajaxData))
.then(function(response) {
saveStoreBtn.innerHTML = "Thank you";
})
.catch(err => console.log('Not working', err));
};
updateStoreBtn.addEventListener('click', saveStore);
PHP
function create_store() {
check_ajax_referer('add_store', 'security');
$name_value = $_POST['name'];
$image_name = $_POST['image_name'];
$image_type = $_POST['image_type'];
$post_data = array(
'post_type' => 'store',
'post_title' => htmlentities($name_value),
'post_content' => $_POST['description'],
'post_status' => 'draft'
);
$post_id = wp_insert_post( $post_data );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES[$image_name];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ($movefile) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'].'/'.$image_name,
'post_mime_type' => $image_type,
'post_title' => $image_name,
'post_content' => 'File '.$image_name,
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $movefile['file']);
update_field('field_602019eba7767', $attach_id, $post_id);
}
echo json_decode($response);
exit;
}
add_action('wp_ajax_create_store', 'create_store');
add_action('wp_ajax_nopriv_create_store', 'create_store');
There are two problems in your case, first one that you are uploading multiple files, so structure of $_FILES will be different. Second one is that you specified store_images instead store_images[] for multiple file upload.
So in html change <input type="file" name="store_images" multiple> to <input type="file" name="store_images[]" multiple>
And in php, change your code accordingly to example below.
$files = $_FILES['store_images];
foreach ($files as $key => $value) {
if ($files['name']) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
wp_handle_upload($file);
}
}
}

How to submit image input file with dropzone.js and php

I have a Wordpress website that users can submit posts from the front-end. Im trying to integrate dropzone.js so users can submit images via drag and drop and sort images from featured image and gallery images kinda like what craigslist has.
My question is how do I get the featured image to get added to a file input
<input id="fileUpload" type="file" name="feat-img" accept="image/*" value="">
and the gallery image get added to
<input id="gallery-photo-add" type="file" name="muti_files[]" accept="image/*" multiple>
Heres my code
Html
<div class="dropzone" drop-zone="" id="file-dropzone"></div>
<ul class="visualizacao sortable dropzone-previews" style="border:1px solid #000"></ul>
<div class="preview" style="display:none;">
<li>
<div class="dz-preview dz-file-preview">
<img data-dz-thumbnail />
<input id="fileUpload" type="file" name="feat-img" accept="image/*" value="">
<input id="gallery-photo-add" type="file" name="muti_files[]" accept="image/*" multiple>
</div>
</li>
</div>
Javascript
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>
<script type="text/javascript">
var $ = jQuery
$(document).ready(function(){
$('.sortable').sortable();
});
$.getScript('https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/dropzone.min.js',function(){
$('#file-dropzone').dropzone({
url: "/",
maxFilesize: 100,
paramName: "uploadfile",
maxThumbnailFilesize: 99999,
previewsContainer: '.visualizacao',
previewTemplate : $('.preview').html(),
init: function() {
this.on('completemultiple', function(file, json) {
$('.sortable').sortable('enable');
});
this.on('success', function(file, json) {
alert('aa');
});
this.on('addedfile', function(file) {
console.log('File1',file);
});
this.on('drop', function(file) {
console.log('File2',file);
});
}
});
});
$(document).ready(function() {});
</script>
PHP
if( ! empty( $_FILES ) ){
$featured_image = $_FILES['feat-img'];
$attachment_id = upload_user_file( $featured_image, $post_id);
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$filee = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $filee);
foreach ($_FILES as $filee => $array) {
$newupload = my_handle_attachment($filee, $post_id);
}
}
}
}
if ( ! empty( $_FILES['muti_files'] ) ) {
$files = $_FILES['muti_files'];
foreach ($files['name'] as $key => $value){
if ($files['name'][$key]){
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
}
$_FILES = array("muti_files" => $file);
$i=1;
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attachment_id = media_handle_upload($file, $post_id);
$vv .= $attachment_id . ",";
$i++;
}
update_post_meta($post_id, '_product_image_gallery', $vv);
}
}
All this works fine if i dont use dropzone.js and just the <input type="file"> here is a codepen so you can see what im trying to do https://codepen.io/T-SEA/pen/OdqQOw

DataTables Server Side Processing Adding html content select tag not triggering javascript

I have implemented successfully the datatables server side processing on one of my tables just that the $('.select_users').change(function(event){ doesn't work anymore on my select tab, despite the fact it shows correctly. When I try to select an option from the select tag it should action to the jquery function but it doesn't.
EDIT 28 NOV 2014
I have found that there is an issue with the events and server side processing:
http://www.datatables.net/examples/advanced_init/events_live.html.
So how can I convert script BLOCK #1 to match the script from the above link.
I added the
$('#dataTables-ss').on('click', 'tr', function () {
var name = $('td', this).eq(0).text();
alert( 'You clicked on '+name+'\'s row' );
} );
And this was getting triggered.
BLOCK #1 => Jquery - on change of select it should trigger this function
$('.select_users').change(function(event){
var selected_value = this.value;
var id = $(this).find('option:selected').attr('class');
var id = id.split('-');
var select_id = id[1];
$.ajax({
type: 'post',
url: 'includes/ajax.html',
data: {
action: 'confirm_notconfirm_subscribers',
selected_value: selected_value,
select_id: select_id
},
success: function(data) {
$('#message').html(data).fadeIn(1000).fadeOut(1000);
},
error: function() {
$("#result").html('There was an error');
}
});
});
BLOCK #2 => PHP important part
public function read_subscriber_table() {
$table = 'subscribers';
$primaryKey = 'ID';
$columns = array(
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'email', 'dt' => 2 ),
array( // issue is here in the third array where I create the select string.
'db' => 'confirmed',
'dt' => 3,
'formatter' => function( $d, $row ) {
if ($d == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($d !== '1') { $selected = 'selected'; } else { $selected = ''; }
$string = '<select class="select_users form-control" name="status-users">
<option class="opt-'.$row["ID"].'" value="1" '.$selected.'>Confirmed</option>
<option class="opt-'.$row["ID"].'" value="0" '.$selected.'>Not Confirmed</option>
</select>';
return $string;
}
),
array(
'db' => 'date',
'dt' => 4,
'formatter' => function( $d, $row ) {
return date( 'd-m-Y', strtotime($d));
}
),
array(
'db' => 'ID',
'dt' => 5,
'formatter' => function( $d, $row ) {
return '<input type="checkbox" class="checkbox_subscribers" value="'.$d.'" >';
}
)
);
$sql_details = $this->dtss_processing();
require( 'ssp.class.php' );
$result = SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns );
$start=$_REQUEST['start'] + 1;
foreach($result['data'] as &$res){
$res[0]=(string)$start;
$start++;
}
echo json_encode($result);
}
BLOCK #3 => Datatables initialized script
$(document).ready(function() {
$('#dataTables-ss').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "includes/data_tables.html?action=read_subscriber_table",
"aaSorting": [[4, 'desc']]
} );
} );
BLOCK #4 => EDIT - before implementing server side the function was looking like this and it was working well.
public function read_subscriber_table() {
$col_names = array('ID', 'name', 'email', 'confirmed', 'date');
$this->read_table('subscribers', $col_names);
$i = 0;
foreach ($this->results as $item) {
$i++;
if ($item->confirmed == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($item->confirmed !== '1') { $selected = 'selected'; } else { $selected = ''; }
?>
<tr id="tablerow-<?php echo $item->ID; ?>">
<td><?php echo $i; ?></td>
<td><?php echo $item->name; ?></td>
<td><?php echo $item->email; ?></td>
<td>
<select class="select_users form-control" name="status-users">
<option class="opt-<?php echo $item->ID; ?>" value="1" <?php echo $selected ?>>Confirmed</option>
<option class="opt-<?php echo $item->ID; ?>" value="0" <?php echo $selected ?>>Not Confirmed</option>
</select>
</td>
<td><?php echo $item->date; ?></td>
<td><input type="checkbox" class="checkbox_subscribers" value="<?php echo $item->ID; ?>" ></td>
</tr>
<?php
}
?>
<?php
}
Follwing on from comments...
Using that updated code as a starting point, change $('#dataTables-ss').on('click', 'tr', function () { to $('#dataTables-ss').on('change', '.select_users', function(event){

Categories