I what create custom wordpress reply comment form and send data via ajax js , but when i send data to back are comments not show in admin panel. But status sending data is "OK" ( i cheked chrome console -> network ), how i can connect correctly front whith backend ? Whehere my mistake in this code ?
html
<div class="reply_comments respoond" style="display: none;">
<a class="cancel-comment-reply-link" style="display:none;">Cancel</a>
<form class="comment-form fcommentform">
<div class="comment-form-field-plus">
<label>Name:</label>
<input type="text" class="author" name="name">
<label>Email:</label>
<input type="text" class="email" name="email">
<textarea name="comment" class="comment" rows="5" cols="5" required></textarea>
</div>
<div class="form-footer">
<input class="like-post-button submit-comment-button rsubmit" type="button" value="<?php echo __('POST MY REVIEW', 'slotstory.com'); ?>" />
</div>
</form>
</div>
js
$('.rsubmit').on('click', function() {
$(this).closest('.fcommentform').submit();
});
$('.fcommentform').on('submit', function(e){
var errors = {
'name' : true,
'email' : true,
'comment' : true
};
e.preventDefault();
$(this).find('[name]').each(function( index ) {
var name = $( this ).attr('name');
var functionName = false;
switch(name){
case 'name':
functionName = _validateField;
break;
case 'email':
functionName = _validateEmail;
break;
case 'comment':
functionName = _validateComment;
break;
}
if (functionName) {
functionName.call(this);
$( this ).on('input', functionName.bind(this));
}
});
function _validateEmail(){
if(this != document) {
$element = $( this );
var reg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!reg.test($element.val())) {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
function _validateField(){
if(this != document) {
$element = $( this );
if ($element.val() == '') {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
function _validateComment(){
if(this != document) {
$element = $( this );
if ($element.val().length <= 10) {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
if (Object.keys(errors).length == 0) {
console.log('success');
}
$.ajax({
type : 'POST',
url: ajaxactionurl,
data: $(this).serialize() + '&action=ajaxcomments',
error: function (request, status, error) {
if( status == 500 ){
alert( 'Error while adding comment' );
} else if( status == 'timeout' ){
alert('Error: Server doesn\'t respond.');
} else {
var wpErrorHtml = request.responseText.split("<p>"),
wpErrorStr = wpErrorHtml[1].split("</p>");
alert( wpErrorStr[0] );
}
},
});
return false;
});
php
add_action( 'wp_ajax_ajaxcomments', 'custom_submit_ajax_comment' );
add_action( 'wp_ajax_nopriv_ajaxcomments', 'custom_submit_ajax_comment' );
function custom_submit_ajax_comment() {
global $wpdb;
$comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
if ( is_wp_error( $comment ) ) {
$error_data = intval( $comment->get_error_data() );
if ( ! empty( $error_data ) ) {
wp_die( '<p>' . $comment->get_error_message() . '</p>', __( 'Comment Submission Failure' ), array( 'response' => $error_data, 'back_link' => true ) );
} else {
wp_die( 'Unknown error' );
}
}
$comment_data = array(
'comment_post_ID' => $comment_post_ID,
'comment_content' => $comment,
'comment_parent' => $comment_parent,
'comment_date' => $time,
'comment_approved' => 0,
'user_id' => $current_user->ID,
);
exit();
}
The status is 200 ok because you don't send anything in the php.
I suggest checking the body of the response, not just the status code.
Start debugging there. Good luck.
Related
Currently I have a form with dropzone.js and it works correctly, but the form must be 2 times on the same page, only the styles change when I insert the second form only the first one remains working
I don't know what changes I should make
Currently I have a form with dropzone.js and it works correctly, but the form must be 2 times on the same page, only the styles change when I insert the second form only the first one remains working
I don't know what changes I should make
script
<code>
var Onyx = {
defaults: {
debug: true
},
/**
* Function to print results in the console if the above debug is true
**/
log: function() {
if (Onyx.defaults.debug === true) {
var argsArray = [],
printOut = "console.log(args)";
for ( var i = 0; i < arguments.length; i++ ) {
argsArray.push("args[" + i + "]");
}
printOut = new Function( "args", printOut.replace( /args/, argsArray.join(",") ) );
printOut(arguments);
}
},
/**
* Firing functions and bindings and other important stuff
**/
init: function(e) {
if ( $("#the-planner-form").length ) {
Onyx.projectPlanner();
if ( $("body").data("form-completed") == "yes" ) {
setTimeout(function() {
Onyx.plannerShowSuccess(true)
}, 800)
}
}
},
/**
* Project planner
**/
projectPlanner: function() {
Onyx.initDropzone();
var checkedValues = [];
// Add default checked service
$('input[name="planner_project_type_checkbox"]:checked').each(function() {
$(this).val();
checkedValues.push($(this).val())
});
$('input[name="planner_project_type"]').val(checkedValues.join(", "));
$('div.type-selection').each(function() {
$(this).on("click", function(e) {
e.preventDefault();
if ( $(this).find('input[checked]').length ) {
checkedValues.splice( $.inArray($(this).find('input[checked]').val(), checkedValues), 1 );
$(this).find('input[checked]').removeAttr('checked');
$('input[name="planner_project_type"]').val(checkedValues);
Onyx.log($.inArray($(this).find('input[name="planner_project_type_checkbox"]').val(), checkedValues));
Onyx.log(checkedValues);
} else {
$(this).find('input[name="planner_project_type_checkbox"]').attr('checked', true);
checkedValues.push($(this).find('input[name="planner_project_type_checkbox"]').val());
$('input[name="planner_project_type"]').val(checkedValues.join(", "));
Onyx.log(checkedValues);
Onyx.log($.inArray($(this).find('input[name="planner_project_type_checkbox"]').val(), checkedValues));
}
});
});
var sendingForm = false;
$("form#the-planner-form").bind("submit", function(e) {
e.preventDefault();
// Check every thing is valid
$('form#the-planner-form').find(".validate").each(function() {
sendingForm = 0 != Onyx.plannerValidate($(this));
});
if (sendingForm) {
$(".error-msg").stop().animate({
opacity: 0
}, 300, function () { $(this).hide() });
if ( matchMedia("only screen and (max-height: 1023px)").matches || matchMedia("only screen and (max-width: 600px)").matches ) {
$("html,body").stop().animate({
scrollTop: 0
}, 500);
}
Onyx.plannerShowSpinner();
$.ajax({
type: "POST",
url: window.location + "/send_form.php",
data: $("#the-planner-form").serialize()
}).done(function (status, textStatus, jqXHR) {
Onyx.log("Planner form status: " + status);
Onyx.log("Planner form textStatus: " + textStatus);
Onyx.log(jqXHR);
if ( jqXHR.status == 200 && textStatus == 'success' ) {
Onyx.plannerShowSuccess();
} else {
Onyx.plannerShowSpinner(false);
alert("Something went wrong");
}
});
} else {
$(".error-msg").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300), false
}
});
},
plannerShowSpinner: function(showSpinner) {
if ("undefined" == typeof showSpinner) var showSpinner = true;
if ( showSpinner ) {
$(".form-controls, .fields-group").stop().animate({
opacity: 0
}, 400, function() {
$(this).hide();
$(".form-spinner").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300)
});
} else {
$(".form-spinner").stop().animate({
opacity: 1
}, 300, function() {
$(this).hide();
$(".form-controls, .fields-group").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 400)
});
}
},
plannerShowSuccess: function(showSuccess) {
if ("undefined" == typeof showSuccess) var showSuccess = false;
var showThankyou = function() {
$(".form-spinner").stop().animate({
opacity: 0
}, 150, function() {
$(this).hide();
$(".form-thankyou-wrap").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300)
})
};
showSuccess ? $(".form-controls").stop().animate({
opacity: 0
}, 400, function() {
$(this).hide(), showThankyou()
}) : showThankyou()
},
/**
* Upload button
**/
dropzone_active: false,
updateDropzoneCount: function() {
var uploadedCount = $(".dz-preview.dz-success").length,
finalText = "";
if ( uploadedCount == 1 ) {
finalText = uploadedCount + " Archivo Subido.";
} else if ( uploadedCount == 0 ) {
finalText = "No subiste ningún archivo.";
} else {
finalText = uploadedCount + " Archivos Subidos.";
}
$(".total-uploaded").text(finalText)
},
initDropzone: function(e) {
Dropzone.autoDiscover = false;
Dropzone.options.plannerFilesDropzone = {
paramName: "form_file",
maxFilesize: 10,
maxFiles: 5,
acceptedFiles: "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pages,.odt,.rtf",
url: window.location + "/file-upload.php",
addRemoveLinks: true,
forceFallback: false,
clickable: true,
/**
* The text used before any files are dropped.
*/
dictDefaultMessage: "Drop files here to upload.", // Default: Drop files here to upload
/**
* The text that replaces the default message text it the browser is not supported.
*/
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", // Default: Your browser does not support drag'n'drop file uploads.
/**
* If the filesize is too big.
* `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
*/
dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.", // Default: File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.
/**
* If the file doesn't match the file type.
*/
dictInvalidFileType: "You can't upload files of this type.", // Default: You can't upload files of this type.
/**
* If the server response was invalid.
* `{{statusCode}}` will be replaced with the servers status code.
*/
dictResponseError: "Server responded with {{statusCode}} code.", // Default: Server responded with {{statusCode}} code.
/**
* If `addRemoveLinks` is true, the text to be used for the cancel upload link.
*/
dictCancelUpload: "Cancel upload.", // Default: Cancel upload
/**
* The text that is displayed if an upload was manually canceled
*/
dictUploadCanceled: "Upload canceled.", // Default: Upload canceled.
/**
* If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
*/
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", // Default: Are you sure you want to cancel this upload?
/**
* If `addRemoveLinks` is true, the text to be used to remove a file.
*/
dictRemoveFile: "Remove file", // Default: Remove file
/**
* If this is not null, then the user will be prompted before removing a file.
*/
dictRemoveFileConfirmation: null, // Default: null
/**
* Displayed if `maxFiles` is st and exceeded.
* The string `{{maxFiles}}` will be replaced by the configuration value.
*/
dictMaxFilesExceeded: "You can not upload any more files.", // Default: You can not upload any more files.
/**
* Allows you to translate the different units. Starting with `tb` for terabytes and going down to
* `b` for bytes.
*/
dictFileSizeUnits: {tb: "TB", gb: "GB", mb: "MB", kb: "KB", b: "b"},
init: function() {
Onyx.dropzone_active = true;
$("input[name=form_file]").remove();
this.on("addedfile", function(file) {
$('button[type="submit"]').attr("disabled", "disabled");
Onyx.updateDropzoneCount();
});
this.on("removedfile", function(file) {
Onyx.log('Start removing file!');
$.ajax({
type: "POST",
url: window.location + "/file-upload.php",
data: {
target_file: file.upload_ticket,
delete_file: 1
},
sucess: function(jqXHR, textStatus){},
complete: function(jqXHR, textStatus){
var response = JSON.parse(jqXHR.responseText);
// Handle success
if (response.status === 'success') {
Onyx.log('Success: ' + response.info);
}
// Handle error
else {
Onyx.log('Error: ' + response.info);
}
}
});
var inputField = $("input[name=form_files_list]"),
filesArray = inputField.val().split(","),
fileIndex = $.inArray(file.upload_ticket, filesArray);
fileIndex !== -1 && filesArray.splice(fileIndex, 1);
inputField.val(filesArray.length > 0 ? filesArray.join(",") : "");
Onyx.updateDropzoneCount();
});
this.on("success", function(file, response) {
let parsedResponse = JSON.parse(response);
file.upload_ticket = parsedResponse.file_link;
var inputField = $("input[name=form_files_list]"),
filesArray = [];
Onyx.log(file.upload_ticket);
if ( "" != inputField.val() ) {
filesArray = inputField.val().split(",");
}
filesArray.push(file.upload_ticket);
inputField.val(filesArray.length > 0 ? filesArray.join(",") : "");
// Something to happen when file is uploaded
});
this.on("complete", function(file) {
if ( 0 === this.getUploadingFiles().length && 0 === this.getQueuedFiles().length ) {
$('button[type="submit"]').removeAttr("disabled");
}
Onyx.updateDropzoneCount()
});
this.on("error", function(file, t, a) {
this.removeFile(file);
});
}
};
$("#planner-files-dropzone").dropzone();
$("#planner-files-dropzone .instructions").click(function(e) {
var t = Dropzone.forElement("#planner-files-dropzone");
t.hiddenFileInput.click();
e.preventDefault()
})
},
plannerValidate: function(e) {
if ("" == e.val()) return e.addClass("error"), false;
if (!e.is('[type="email"]')) return e.removeClass("error"), true;
var t = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e.val());
return t ? void 0 : (e.addClass("error"), false)
}
};
$(function() {
Onyx.init();
});
<?php
$delete_file = 0;
if(isset($_POST['delete_file'])){
$delete_file = $_POST['delete_file'];
}
$targetPath = dirname( __FILE__ ) . '/uploads/';
// Check if it's an upload or delete and if there is a file in the form
if ( !empty($_FILES) && $delete_file == 0 ) {
// Check if the upload folder is exists
if ( file_exists($targetPath) && is_dir($targetPath) ) {
// Check if we can write in the target directory
if ( is_writable($targetPath) ) {
/**
* Start dancing
*/
$tempFile = $_FILES['form_file']['tmp_name'];
$targetFile = $targetPath . $_FILES['form_file']['name'];
// Check if there is any file with the same name
if ( !file_exists($targetFile) ) {
// Upload the file
move_uploaded_file($tempFile, $targetFile);
// Be sure that the file has been uploaded
if ( file_exists($targetFile) ) {
$response = array (
'status' => 'success',
'file_link' => $targetFile
);
} else {
$response = array (
'status' => 'error',
'info' => 'Couldn\'t upload the requested file :(, a mysterious error happend.'
);
}
/*$response = array (
'status' => 'success',
'file_link' => 'Just a test, don\'t take it seriously.'
);*/
} else {
// A file with the same name is already here
$response = array (
'status' => 'error',
'info' => 'A file with the same name is exists.',
'file_link' => $targetFile
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'The specified folder for upload isn\'t writeable.'
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'No folder to upload to :(, Please create one.'
);
}
// Return the response
echo json_encode($response);
exit;
}
// Remove file
if( $delete_file == 1 ){
$file_path = $_POST['target_file'];
// Check if file is exists
if ( file_exists($file_path) ) {
// Delete the file
unlink($file_path);
// Be sure we deleted the file
if ( !file_exists($file_path) ) {
$response = array (
'status' => 'success',
'info' => 'Successfully Deleted.'
);
} else {
// Check the directory's permissions
$response = array (
'status' => 'error',
'info' => 'We screwed up, the file can\'t be deleted.'
);
}
} else {
// Something weird happend and we lost the file
$response = array (
'status' => 'error',
'info' => 'Couldn\'t find the requested file :('
);
}
// Return the response
echo json_encode($response);
exit;
}
?>
<form action="#" method="post" id="the-planner-form" enctype="multipart/form-data">
<div class="text-cotizador">
<h1>COTIZADOR ONLINE</h1>
</div>
<div class="img-cotizador">
<img src="images/barrita-dorada.png" alt="ubicacion" width="35" height="5">
</div>
<div class="text-cotizador">
<p>Envíenos la foto de la joya a cotizar, y un tasador especializado<br>
la analizará y le brindará <b>el mejor precio del mercado.</b>
</p>
</div>
<div class="fields-group clearfix">
<div class="fields-group-controls1">
<div class="form-field half first">
<input type="text" name="planner_name" id="name" class="validate" placeholder="Nombre">
</div>
</div>
<div class="fields-group-controls2">
<div class="form-field half first">
<input type="email" name="planner_email" id="email" class="validate" placeholder="E-mail">
</div>
<div class="form-field half last">
<input type="tel" name="planner_phone" id="phone" class="validate" placeholder="Telefono">
</div>
</div>
<div class="fields-group-controls">
<div class="form-field">
<textarea name="planner_project_description" id="description" class="validate" placeholder="Comentarios"></textarea>
</div>
<div class="form-field">
<div id="files-wrap">
<div id="planner-files-dropzone">
<div class="dropzone-foo">
<div class="instructions is-desktop">ARRASTRA Y SUELTA AQUÍ LOS ARCHIVOS</br>o</div>
<div class="instructions is-touch">Subi los archivos</div>
</div>
<div class="total-uploaded">No se ha seleccionado ningún archivo</div>
</div>
<input type="hidden" value="" name="form_files_list" />
<input type="file" name="form_file" id="pp-file" />
</div>
<div class="text-formatos">
<p>Puede seleccionar hasta 5 imágenes | Tamaño máximo por imagen: 100 MB<br>Formatos admitidos: gif, png, jpg, jpeg
</p>
</div>
</div>
</div>
</div>
<div class="form-spinner-container">
<div class="form-spinner"></div>
</div>
<div class="form-thankyou-wrap">
<div class="form-thankyou-wrap-inner">
<div class="form-thankyou-content">
<h2><em>Gracias!</em> su mensaje ha sido enviado correctamente.</h2>
<p>Te contactaremos en poco tiempo..</p>
Go back to home page
</div>
</div>
</div><!-- .form-thankyou-wrap -->
<div class="form-controls">
<button aria-label="Send" type="submit">Enviar</button>
<div class="error-msg">Debe diligenciar toda la información. ↑</div>
</div>
</form>
I am currently creating a login form in PHP PDO and I am using ajax to display the relevant messages on screen, e.g.
"Logging in..."
"Some input fields are empty"
"Your username is required"
"Your password is required"
Validation such as checking if input fields are empty is working fine along with when login credentials appear to be incorrect however when I login with correct credentials I just get message "Logging in..." and nothing happens, I don't even think it sets the session. I have also added a token to prevent CSRF and was just wondering if i'm using it correctly.
I'm unsure of what is causing my code not to proceed with logging in.
my ajax script:
<script type='text/javascript'>
$(document).ready(function () {
var submitButton = $("#btn-login");
submitButton.on('click', function (e) {
e.preventDefault();
// Get input field values of the contact form
var loginFormInputs = $('#login-form :input'),
userName = $('#txt_uname_email').val(),
userPassword = $('#txt_password').val(),
token = $('#token').val(),
alertMessage = $('#login-alert-message');
// Disable Inputs and display a loading message
alertMessage.html('<p style="opacity: 1"><i class="fa fa-spinner fa-spin text-success"></i> Logging in..</p>');
submitButton.html('<i class="fas fa-spinner fa-spin"></i>');
loginFormInputs.prop("disabled", true);
// Data to be sent to server
var post_data = {
'form': 'loginForm',
'userName': userName,
'userPassword': userPassword,
'token': token
};
// Ajax post data to server
$.post('./api', post_data, function (response) {
// Load jsn data from server and output message
if (response.type === 'error') {
alertMessage.html('<p><i class="fa-lg far fa-times-circle text-danger"></i> ' + response.text + '</p>');
submitButton.html('Login');
loginFormInputs.prop("disabled", false);
} else {
alertMessage.html('<p><i class="fa-lg far fa-check-circle text-success"></i> ' + response.text + '</p>');
submitButton.html('Login');
window.location = "dashboard";
}
}, 'json');
});
});
</script>
My login function (class.user.php) which is used in api.php:
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM `settings` LIMIT 1");
$stmt->execute();
$mainten=$stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass, status FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['user_pass']))
{
session_regenerate_id(false);
return ["correctPass"=>true, "banned"=> ($userRow['status']== 1) ? true : false, "maintenance"=> ($mainten["maintenance"]== 1) ? true : false];
}
else
{
return ["correctPass"=>false];
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
api.php:
//include class.user.php here and set $login = new USER();
//set $uname, $umail, $upass, $token vars here
if( $_POST && $_POST["form"] === 'loginForm' ) {
// Use PHP To Detect An Ajax Request code is here
// Checking if the $_POST vars well provided, Exit if there is one missing code is here
// PHP validation for the fields required code is here
$validation = $login->doLogin($uname,$umail,$upass);
if($validation["correctPass"]){
if($validation["maintenance"]){
if (!in_array($uname, array('admin'))){
$output = json_encode(
array(
'type' => 'error',
'text' => 'Website under maintenance.'
));
die($output);
}
}
if($validation["banned"]){
$output = json_encode(
array(
'type' => 'error',
'text' => 'User has been banned.'
));
die($output);
}else{
if(Token::check($_POST['token'])) {
$stmtt = $login->runQuery("SELECT user_id FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmtt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmtt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_session'] = $userRow['user_id'];
$output = json_encode(
array(
'type' => 'message',
'text' => 'Logged in successfully.'
));
die($output);
//$success = "Logged in successfully, redirecting..";
//header( "refresh:3;url=ab" );
//$login->redirect('dashboard');
} else {
$output = json_encode(
array(
'type' => 'error',
'text' => 'Unexpected error occured.'
));
die($output);
}
}
}
else{
$output = json_encode(
array(
'type' => 'error',
'text' => 'Incorrect username or password.'
));
die($output);
}
}
I try to display an error message but it does'nt work.
When the email does'nt exist,
I have this message : Thank you : your email is added
But if the email is always in mailchimp or other error, I haven't message under the button submit.
Do you have an idea to resolve this point ?
Thank you
The detail of the error come from server.
string(88) "400: ****** is already a list member. Use PUT to insert or update list members."
array(5) {
["type"]=>
string(77) "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/"
["title"]=>
string(13) "Member Exists"
["status"]=>
int(400)
["detail"]=>
string(83) "********* is already a list member. Use PUT to insert or update list members."
["instance"]=>
string(0) ""
}
my javascript is
$footer .= '
<script>
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("<div class=\"alert alert-info\" style=\"padding:05px; margin-top:5px;\" role=\"alert\">Thank you : your email is added</div>");
$.ajax({
url: 'ext/api/mailchimp_v3/subscribe.php', // proper url to your "store-address.php" file
type: 'POST', // <- IMPORTANT
dataType: 'json',
data: $('#signup').serialize() + '&ajax=true',
success: function(msg) {
var message = '';
var result = '';
message = $.parseJSON(msg);
if (message.status === 'pending') { // success
result = '<div class=\"alert alert-success\" role=\"alert\">Thank you: an email has sent you for confirmation</div>';
} else { // error
result = '<div class=\"alert alert-danger\" role=\"alert\">Error ' + message.detail + '</div>';
}
},
complete: function(message) {
$('#message').html('<div> ' + message.title + '</div>'); // display the message
}
});
$('#fname').attr('value',''); // reset input field
$('#lname').attr('value',''); // reset input field
$('#email').attr('value',''); // reset input field
return false;
});
});
</script>';
PHP code
if ( isset($_POST['anonymous'])) {
$list_id = MODULES_HEADER_TAGS_MAILCHIMP_LIST_ANONYMOUS;
$merge_vars = [
'FNAME' => '',
'LNAME' => ''
];
} else {
$list_id = MODULES_HEADER_TAGS_MAILCHIMP_LIST_CUSTOMERS;
$merge_vars = [
'FNAME' => $_POST['firstname'],
'LNAME' => $_POST['lastname']
];
}
$array = [
'email_address' => $_POST['email'],
'merge_fields' => $merge_vars,
'status' => MODULES_HEADER_TAGS_MAILCHIMP_STATUS_CHOICE
];
if (MODULES_HEADER_TAGS_MAILCHIMP_STATUS_CHOICE == 'pending') {
$status = 'pending';
} else {
$status = 'subscribed';
}
$mc = new \MailChimp($key);
// add the email to your list
$result = $mc->post('/lists/' . $list_id . '/members', $array);
//send
json_encode($result);
// If being called via ajax, run the function, else fail - console
if ( MODULES_HEADER_TAGS_MAILCHIMP_DEBUG == 'True') {
if ($_POST['ajax']) {
var_dump($result); // send the response back
} else {
var_dump('Method not allowed - please ensure JavaScript is enabled in this browser');
}
}
I have a bug with my Custom Post Type Image Uploader i can't get my head around.
My image uploader is working perfectly fine, when i upload my images all at once, but if i need to edit a post then my issue comes. When i press the update button in Wordpress admin, all my images are deleted and only a broken image is left.
The Images is only saved if i have used the media uploader, before pressing update. So if i want to edit a post i have to uploade the images every time, and i need to fix that.
I have two files: image_uploader.php and image_upload.js.
First one image_upload.js and second image_uploader.php
var addButton = document.getElementById( 'image-upload-button');
var deleteButton = document.getElementById( 'image-delete-button');
var img = document.getElementById( 'image-tag');
var hidden = document.getElementById( 'img-hidden-field');
var customUploader = wp.media({
title: 'Choose an image',
button: {
text: "Use this Image"
},
multiple: false
});
addButton.addEventListener( 'click', function() {
if ( customUploader ){
customUploader.open();
}
} );
customUploader.on( 'select', function() {
var attachment = customUploader.state().get('selection').first().toJSON();
img.setAttribute( 'src', attachment.url );
hidden.setAttribute( 'value', JSON.stringify( [{ id: attachment.id, url: attachment.url }]) );
toggleVisibility( 'ADD' );
} );
deleteButton.addEventListener( 'click', function(){
img.removeAttribute( 'src' );
hidden.removeAttribute( 'value' );
toggleVisibility( 'DELETE' );
});
var toggleVisibility = function( action ) {
if ( 'ADD' === action ) {
addButton.style.display = 'none';
deleteButton.style.display = '';
img.setAttribute( 'style', 'width: 100%;' );
}
if ( 'DELETE' === action ) {
addButton.style.display = '';
deleteButton.style.display = 'none';
img.removeAttribute('style');
}
};
window.addEventListener( 'DOMContentLoaded', function() {
if ( "" === customUploads.imageData || 0 === customUploads.imageData.length ) {
toggleVisibility( 'DELETE' );
} else {
img.setAttribute( 'src', customUploads.imageData.src );
hidden.setAttribute( 'value', JSON.stringify([ customUploads.imageData ]) );
toggleVisibility( 'ADD' );
}
} );
// Second Image
var addButton2 = document.getElementById( 'image-upload-button2');
var deleteButton2 = document.getElementById( 'image-delete-button2');
var img2 = document.getElementById( 'image-tag2');
var hidden2 = document.getElementById( 'img-hidden-field2');
var customUploader2 = wp.media({
title: 'Choose an image',
button: {
text: "Use this Image"
},
multiple: false
});
addButton2.addEventListener( 'click', function() {
if ( customUploader2 ){
customUploader2.open();
}
} );
customUploader2.on( 'select', function() {
var attachment2 = customUploader2.state().get('selection').first().toJSON();
img2.setAttribute( 'src', attachment2.url );
hidden2.setAttribute( 'value', JSON.stringify( [{ id: attachment2.id, url: attachment2.url }]) );
toggleVisibility2( 'ADD2' );
} );
deleteButton2.addEventListener( 'click', function(){
img2.removeAttribute( 'src' );
hidden2.removeAttribute( 'value' );
toggleVisibility2( 'DELETE2' );
});
var toggleVisibility2 = function( action ) {
if ( 'ADD2' === action ) {
addButton2.style.display = 'none';
deleteButton2.style.display = '';
img2.setAttribute( 'style', 'width: 100%;' );
}
if ( 'DELETE2' === action ) {
addButton2.style.display = '';
deleteButton2.style.display = 'none';
img2.removeAttribute('style');
}
};
window.addEventListener( 'DOMContentLoaded', function() {
if ( "" === customUploads2.imageData2 || 0 === customUploads2.imageData2.length ) {
toggleVisibility2( 'DELETE2' );
} else {
img2.setAttribute( 'src', customUploads2.imageData2.src );
hidden2.setAttribute( 'value', JSON.stringify([ customUploads2.imageData2 ]) );
toggleVisibility2( 'ADD2' );
}
} );
<?php
// Meta box 1
function register_metaboxes() {
add_meta_box('image_metabox', 'Billeder','image_uploader_callback');
}
add_action( 'add_meta_boxes','register_metaboxes' );
// Meta box 2
function register_metaboxes2() {
add_meta_box('image2_metabox', 'Billeder2','image2_uploader_callback');
}
add_action( 'add_meta_boxes','register_metaboxes2' );
function register_admin_script() {
wp_enqueue_script( 'wp_img_upload', 'image-upload.js', array('jquery', 'media-upload'), true );
wp_localize_script( 'wp_img_upload', 'customUploads', array( 'imageData' => get_post_meta( get_the_ID(), 'custom_image_data', true ) ) );
wp_localize_script( 'wp_img_upload', 'customUploads2', array( 'imageData2' => get_post_meta( get_the_ID(), 'custom_image2_data', true ) ) );
add_action( 'admin_enqueue_scripts', 'register_admin_script' );
function image_uploader_callback( $post_id ) {
wp_nonce_field( basename( __FILE__ ), 'custom_image_nonce' ); ?>
<div id="metabox_wrapper">
<img id="image-tag">
<input type="hidden" id="img-hidden-field" name="custom_image_data">
<input type="button" id="image-upload-button" class="button" value="Add Image">
<input type="button" id="image-delete-button" class="button" value="Delete Image">
</div>
<?php
}
function image2_uploader_callback( $post_id ) {
wp_nonce_field( basename( __FILE__ ), 'custom_image2_nonce' ); ?>
<label>Andet billede</label>
<div id="metabox_wrapper2">
<img id="image-tag2">
<input type="hidden" id="img-hidden-field2" name="custom_image2_data">
<input type="button" id="image-upload-button2" class="button" value="Add Image">
<input type="button" id="image-delete-button2" class="button" value="Delete Image">
</div>
<?php
}
function save_custom_image( $post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'custom_image_nonce' ] ) && wp_verify_nonce( $_POST[ 'custom_image_nonce' ], basename( __FILE__ ) ) );
$image_data = ['id','src'];
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
if ( isset( $_POST[ 'custom_image_data' ] ) ) {
$image_data = json_decode( stripslashes( $_POST[ 'custom_image_data' ] ) );
if ( is_object( $image_data[0] ) ) {
$image_data = array( 'id' => intval( $image_data[0]->id ), 'src' => esc_url_raw( $image_data[0]->url
) );
}
update_post_meta( $post_id, 'custom_image_data', $image_data );
}
}
add_action( 'save_post', 'save_custom_image' );
// Image 2
function save_custom_image2( $post_id ){
$is_autosave2 = wp_is_post_autosave( $post_id );
$is_revision2 = wp_is_post_revision( $post_id );
$is_valid_nonce2 = ( isset( $_POST[ 'custom_image2_nonce' ] ) && wp_verify_nonce( $_POST[ 'custom_image2_nonce' ], basename( __FILE__ ) ) );
// Exits script depending on save status
if ( $is_autosave2 || $is_revision2 || !$is_valid_nonce2 ) {
return;
}
if ( isset( $_POST[ 'custom_image2_data' ] ) ) {
$image_data2 = json_decode( stripslashes( $_POST[ 'custom_image2_data' ] ) );
if ( is_object( $image_data2[0] ) ) {
$image_data2 = array( 'id' => intval( $image_data2[0]->id ), 'src' => esc_url_raw( $image_data2[0]->url
) );
} else {
$image_data2 = [];
}
update_post_meta( $post_id, 'custom_image2_data', $image_data2 );
}
}
add_action( 'save_post', 'save_custom_image2' );
I am not sure what do you try to accomplish there and it's quite hard to debug your code without setting up new installation, but I think there is better way to do that.
Wordpress have very useful extension called ACF https://www.advancedcustomfields.com/ which gives you possibility to add custom meta fields to one or multiple post types. I highly recommend it, even free version is enough for most of the cases.
<?php
// Edit this ->
define( 'MQ_SERVER_ADDR', 'XX.XXX.XXX.XXX' );
define( 'MQ_SERVER_PORT', 25565 );
define( 'MQ_TIMEOUT', 1 );
// Edit this <-
// Display everything in browser, because some people can't look in logs for errors
Error_Reporting( E_ALL | E_STRICT );
Ini_Set( 'display_errors', true );
require __DIR__ . '/status/MinecraftQuery.class.php';
$Timer = MicroTime( true );
$Query = new MinecraftQuery( );
try
{
$Query->Connect( MQ_SERVER_ADDR, MQ_SERVER_PORT, MQ_TIMEOUT );
}
catch( MinecraftQueryException $e )
{
$Exception = $e;
}
$Timer = Number_Format( MicroTime( true ) - $Timer, 4, '.', '' );
?>
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<div class="spanx"><p>
<h1>Login</h1>
Username:<br />
<input type="text" name="username" style="height: 30px; style="width: 220px; value="" />
<br/>
<button>Submit</button>
<?php // Example from PHP.net
$string = '<?php if( ( $Players = $Query->GetPlayers( ) ) !== false ): ?>
<?php foreach( $Players as $Player ): ?>';
if(stristr($string, 'Thisshouldbethestringfromthetextbox') === FALSE) {
echo 'Player is not online';
}
?>
Is my code. Basically what I am trying to do is query my Minecraft server. Check if a player is online by the text form on button click, and if not, deliver a message that says the player is not online, otherwise, keep the person logged in as they browse the site (dunno how to do this either...)
The external query file is:
<?php
class MinecraftQueryException extends Exception
{
// Exception thrown by MinecraftQuery class
}
class MinecraftQuery
{
/*
* Class written by xPaw
*
* Website: http://xpaw.ru
* GitHub: https://github.com/xPaw/PHP-Minecraft-Query
*/
const STATISTIC = 0x00;
const HANDSHAKE = 0x09;
private $Socket;
private $Players;
private $Info;
public function Connect( $Ip, $Port = 25565, $Timeout = 3 )
{
if( !is_int( $Timeout ) || $Timeout < 0 )
{
throw new InvalidArgumentException( 'Timeout must be an integer.' );
}
$this->Socket = #FSockOpen( 'udp://' . $Ip, (int)$Port, $ErrNo, $ErrStr, $Timeout );
if( $ErrNo || $this->Socket === false )
{
throw new MinecraftQueryException( 'Could not create socket: ' . $ErrStr );
}
Stream_Set_Timeout( $this->Socket, $Timeout );
Stream_Set_Blocking( $this->Socket, true );
try
{
$Challenge = $this->GetChallenge( );
$this->GetStatus( $Challenge );
}
// We catch this because we want to close the socket, not very elegant
catch( MinecraftQueryException $e )
{
FClose( $this->Socket );
throw new MinecraftQueryException( $e->getMessage( ) );
}
FClose( $this->Socket );
}
public function GetInfo( )
{
return isset( $this->Info ) ? $this->Info : false;
}
public function GetPlayers( )
{
return isset( $this->Players ) ? $this->Players : false;
}
private function GetChallenge( )
{
$Data = $this->WriteData( self :: HANDSHAKE );
if( $Data === false )
{
throw new MinecraftQueryException( 'Offline' );
}
return Pack( 'N', $Data );
}
private function GetStatus( $Challenge )
{
$Data = $this->WriteData( self :: STATISTIC, $Challenge . Pack( 'c*', 0x00, 0x00, 0x00, 0x00 ) );
if( !$Data )
{
throw new MinecraftQueryException( 'Failed to receive status.' );
}
$Last = '';
$Info = Array( );
$Data = SubStr( $Data, 11 ); // splitnum + 2 int
$Data = Explode( "\x00\x00\x01player_\x00\x00", $Data );
if( Count( $Data ) !== 2 )
{
throw new MinecraftQueryException( 'Failed to parse server\'s response.' );
}
$Players = SubStr( $Data[ 1 ], 0, -2 );
$Data = Explode( "\x00", $Data[ 0 ] );
// Array with known keys in order to validate the result
// It can happen that server sends custom strings containing bad things (who can know!)
$Keys = Array(
'hostname' => 'HostName',
'gametype' => 'GameType',
'version' => 'Version',
'plugins' => 'Plugins',
'map' => 'Map',
'numplayers' => 'Players',
'maxplayers' => 'MaxPlayers',
'hostport' => 'HostPort',
'hostip' => 'HostIp'
);
foreach( $Data as $Key => $Value )
{
if( ~$Key & 1 )
{
if( !Array_Key_Exists( $Value, $Keys ) )
{
$Last = false;
continue;
}
$Last = $Keys[ $Value ];
$Info[ $Last ] = '';
}
else if( $Last != false )
{
$Info[ $Last ] = $Value;
}
}
// Ints
$Info[ 'Players' ] = IntVal( $Info[ 'Players' ] );
$Info[ 'MaxPlayers' ] = IntVal( $Info[ 'MaxPlayers' ] );
$Info[ 'HostPort' ] = IntVal( $Info[ 'HostPort' ] );
// Parse "plugins", if any
if( $Info[ 'Plugins' ] )
{
$Data = Explode( ": ", $Info[ 'Plugins' ], 2 );
$Info[ 'RawPlugins' ] = $Info[ 'Plugins' ];
$Info[ 'Software' ] = $Data[ 0 ];
if( Count( $Data ) == 2 )
{
$Info[ 'Plugins' ] = Explode( "; ", $Data[ 1 ] );
}
}
else
{
$Info[ 'Software' ] = 'Vanilla';
}
$this->Info = $Info;
if( $Players )
{
$this->Players = Explode( "\x00", $Players );
}
}
private function WriteData( $Command, $Append = "" )
{
$Command = Pack( 'c*', 0xFE, 0xFD, $Command, 0x01, 0x02, 0x03, 0x04 ) . $Append;
$Length = StrLen( $Command );
if( $Length !== FWrite( $this->Socket, $Command, $Length ) )
{
throw new MinecraftQueryException( "Failed to write on socket." );
}
$Data = FRead( $this->Socket, 2048 );
if( $Data === false )
{
throw new MinecraftQueryException( "Failed to read from socket." );
}
if( StrLen( $Data ) < 5 || $Data[ 0 ] != $Command[ 2 ] )
{
return false;
}
return SubStr( $Data, 5 );
}
}
I would like to solve this in any way that I can. Thanks in advance and ask any questions you need :D.
You can create a form pointing to the same URL to accomplish that.
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post">
Username: <input type="text" name="username" />
<button type="submit">Send</button>
</form>
When the form is sent, you can access your input content by accessing $_POST['username']
if (isset($_POST['username'])) {
// your code here
echo 'Username: ' . $_POST['username'];
}