as I recently updated several htaccess in my wordpress site, I observed that the php/ajax code is no more working. I do not understand why
here is my button
$generer_liste_all_plongeurs ='<table><tr>
<td><form>
<button type="submit" id="btn-submit_all">Générer une liste de TOUS les plongeurs</button>
<input type="hidden" id="eventid_all" value="NO_ID" />
<input type="hidden" id="eventdate_all" value="NO_DATE" />
</form></td>
<td><div id="response">
<!-- Nous allons afficher un retour en jQuery au visiteur -->';
/* si le fichier existe, on va l'afficher */
//https://asmtplongee.org/wp-content/FdP/Tous_les_plongeurs.csv
$fichier="Tous_les_plongeurs.csv";
if (file_exists($dir . "/" . $fichier)) {
$generer_liste_all_plongeurs .= '' . 'Liste de plongeurs générée le ' . date ("F d Y H:i:s", filemtime($dir . "/" . $fichier)) . "";
}
$generer_liste_all_plongeurs.= '
</div></td></tr></table>';
and the code to treat this
//script pour ajax
$o .='<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>$(document).ready(function(){
$("#btn-submit_all").click(function(e){
e.preventDefault();
$.post(
"' . get_site_url() . '/wp-content/plugins/alex/creation_csv_palanq.php",
{
eventid : "NO_ID",
eventdate : "NO_DATE",
},
function(data){
$("#response").html("<p>" + data + "</p>");
},
"text"
);
});
});
</script>';
//fin du chapitre ajax
I want the page creation_csv_palanq.php to be called with the below args and their values
eventid : "NO_ID",
eventdate : "NO_DATE",
the content of the htaccess located in wp-content is:
# Alternative to prevent directory listing
IndexIgnore *
# Hide the information from server
ServerSignature Off
# Bloque les accès directs aux fichiers PHP (Merci à Sucuri)
<FilesMatch "\.(?i:php)$">
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
</FilesMatch>
Related
Where is the possible problem, I have a service that returns a json, use this returns to ride my table.
If I leave the statisc record it works the plugin as confirmation code below:
<td><strong>Fatura Abril</strong><br /> Este é um aviso de que sua fatura do mÊs 04 está vencendo</td>
<td class="text-right"></a>
<a data-toggle="confirmation" class="label label-danger" type="button" id="not-basic"><i class="fa fa-times"></i></a>
</td>
But if you use function to return and assemble the data via json, the table is monstada but the plugin confirmation does not work.
<script type="text/javascript">
$(document).ready(function(){
var url="phptabela.php"; // PHP File
//var url="getposts.json"; // JSON File
$.getJSON(url,function(data){
console.log(data);
$.each(data.data, function(i,post){
var newRow =
"<tr>"
+"<td><strong>"+post.titulo+"</strong><br />" +post.texto+"</td>"
+"<td class='text-right'></a> "
+"<a data-toggle='confirmation' class='btn btn-default label label-danger' type='button' id='not-basic'> "
+"<i class='fa fa-times'></i></a> "
+"</td>"
+"</tr>" ;
$(newRow).appendTo("#json-data");
});
});
});
</script>
I am using this plugin:
http://bootstrap-confirmation.js.org/
After you receive the data from ajax and append it to json-data you need to initialise the new confirmation
From doc I can see that you need to do this :
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
// other options
});
I'm making a user registration form in PHP - MYSQL, AJAX jQuery and Codeigniter and loading the web page of records, Google chrome console launches a series of unlimited answers every second, the image here.
Note: There are also some slightly unusual behavior in Google Chrome I want to know the reason to solve them.
Selection in yellow: the answers are automatically generated limitless.
Selection in purple: Are the result or answer to that selected answer.
Selection Green: Other errors that I would like to know to be.
Code HTML:
<div class="ctn">
<h3>Upload file content ajax</h3>
<form action="" method="POST" id="form_file" name="form_file" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="imagex" id="imagex">
</div>
<button type="submit" id="btn_form" class="btn btn-primary">Subir imagen</button>
<div id="mensaje_status"></div>
</form>
</div><!--End ctn-->
Code AJAX:
$(function() {
//Empty content alert message
$('.alert .close').on('click', function(event) {
event.preventDefault();
$('.alert .msg').html('');
});
$('#form_file')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
imagex: {
validators: {
notEmpty: {
message: 'Obligatorio!'
},
file: {
extension: 'jpg,jpeg,png',
type: 'image/jpg,image/jpeg,image/png',
//maxSize: 9097152, // 2048 * 1024
message: 'imagen no válida ( JPG, JPEG, PNG ) | Max 9MB'
}
}
}
}
})
.on('success.form.fv', function (e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation'),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="imagex"]')[0].files;
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
formData.append('imagex', files[0]);
formData.append('id', Math.random());
$.ajax({
//Star preloader
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Convertimos el porcentaje en valor entero
var porcentageRound = percentComplete * 100;
//Mostramos la ventana modal
$('#modal_progress').modal('show');
//Limpiamos el área de mensaje en caso de que tenga información
$('#form_file #mensaje_status').html('');
//Width bar progress
$('.progress-bar').css({
width: percentComplete * 100 + '%'
});
$(".progress-bar").html('<div id="progress-status">' + Math.round(porcentageRound) +' %</div>');
//Ocultamos el loader
if (percentComplete === 1) {
//Podemos manipular los elementos del DOM
//Ocultamos la barra de progreso
$('.progress').addClass('oculto');
//Reseteamos la barra de progreso
$('.progress-bar').css('width', '0%');
//Mostramos un mensaje mientra recibimos respuesta del servidor
$('#modal_progress .mensaje').html('<i class="fa fa-cog fa-spin font20"></i> Procesando espere por favor!');
}
}
}, false);
return xhr;
},
url: '/upload_ajax_full/do_upload/',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
var data = $.parseJSON(data);
if (data.respuesta == true) {
//Limpiamos el área de mensaje en caso de que tenga información
$('#form_file #mensaje_status').html('');
//Cerramos la ventana modal
$('#modal_progress').modal('hide');
//Habilitamos la barra de progreso
$('.progress').removeClass('oculto');
//Limpiamos mensaje
$('#modal_progress .mensaje').html("");
//Limpiamos el campo de imagen
$('#imagex').replaceWith($('#imagex').clone( true ));
//Mostramos mensaje del servidor
$('#form_file #mensaje_status').append(data.mensaje);
}
if (data.respuesta == false) {
//Limpiamos el área de mensaje en caso de que tenga información
$('#form_file #mensaje_status').html('');
//Cerramos la ventana modal
$('#modal_progress').modal('hide');
//Habilitamos la barra de progreso
$('.progress').removeClass('oculto');
//Limpiamos mensaje
$('#modal_progress .mensaje').html("");
//Limpiamos el campo de imagen
$('#imagex').replaceWith($('#imagex').clone( true ));
//Mostramos mensaje del servidor
$('#form_file #mensaje_status').append(data.mensaje);
}
// You can reset the form if you want
fv.resetForm(true);
// You can enable the submit button
// to allow the user to add new record
fv.disableSubmitButtons(true);
}
});
});
});
I'm trying to make a Wordpress page where the user can point to a location by writing the adress or browsing a map`.
As you can see in the page (http://www.levinor.es/pruebas/pagina-ejemplo/) the map isn't loading and I don't know why... I checked the API Key, and the allowed domains (.levinor.es/) of the key... Please I need some help...
To do so I created this javascript (google-maps.js) and placed it in the script folder of my theme:
//Declaramos las variables que vamos a user
var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;
jQuery(document).ready(function(){
//obtenemos los valores en caso de tenerlos en un formulario ya guardado en la base de datos
lat = jQuery('#lat').val();
lng = jQuery('#long').val();
//Asignamos al evento click del boton la funcion codeAddress
jQuery('#pasar').click(function(){
codeAddress();
return false;
});
//Inicializamos la función de google maps una vez el DOM este cargado
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
//Si hay valores creamos un objeto Latlng
if(lat !='' && lng != '')
{
var latLng = new google.maps.LatLng(lat,lng);
}
else
{
//Si no creamos el objeto con una latitud cualquiera como la de Mar del Plata, Argentina por ej
var latLng = new google.maps.LatLng(37.0625,-95.677068);
}
//Definimos algunas opciones del mapa a crear
var myOptions = {
center: latLng,//centro del mapa
zoom: 15,//zoom del mapa
mapTypeId: google.maps.MapTypeId.ROADMAP //tipo de mapa, carretera, híbrido,etc
};
//creamos el mapa con las opciones anteriores y le pasamos el elemento div
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//creamos el marcador en el mapa
marker = new google.maps.Marker({
map: map,//el mapa creado en el paso anterior
position: latLng,//objeto con latitud y longitud
draggable: true //que el marcador se pueda arrastrar
});
//función que actualiza los input del formulario con las nuevas latitudes
//Estos campos suelen ser hidden
updatePosition(latLng);
}
//funcion que traduce la direccion en coordenadas
function codeAddress() {
//obtengo la direccion del formulario
var address = document.getElementById("direccion").value;
//hago la llamada al geodecoder
geocoder.geocode( { 'address': address}, function(results, status) {
//si el estado de la llamado es OK
if (status == google.maps.GeocoderStatus.OK) {
//centro el mapa en las coordenadas obtenidas
map.setCenter(results[0].geometry.location);
//coloco el marcador en dichas coordenadas
marker.setPosition(results[0].geometry.location);
//actualizo el formulario
updatePosition(results[0].geometry.location);
//Añado un listener para cuando el markador se termine de arrastrar
//actualize el formulario con las nuevas coordenadas
google.maps.event.addListener(marker, 'dragend', function(){
updatePosition(marker.getPosition());
});
} else {
//si no es OK devuelvo error
alert("No podemos encontrar la dirección, error: " + status);
}
});
}
//funcion que simplemente actualiza los campos del formulario
function updatePosition(latLng)
{
jQuery('#lat').val(latLng.lat());
jQuery('#long').val(latLng.lng());
}
I placed the next code into the funcionts.php file for referencing the js (I doubled checked the page ID and my API Key):
add_action('template_redirect','carga_archivos');
function carga_archivos(){
if( is_single(2)) // tu número de post o slug
{
wp_enqueue_script( 'google-api','http://maps.googleapis.com/maps/api/js?key={MY API KEY}&sensor=true', array( 'jquery' ) );
wp_enqueue_script( 'google-maps', get_bloginfo('stylesheet_directory') . '/js/google-maps.js', array( 'google-api' ) );
}
}
And added to my header.php:
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key={MY API KEY}&sensor=true"></script>
The code of the page is:
<form id="google" action="#" name="google"><label>Número de Revista</label>
<input id="numerorevista" type="int" name="numerorevista;" value="0" />
<label>Dirección donde será liberada</label>
<input id="direccion" type="text" name="direccion" />
<button id="pasar">Pasar al mapa</button>
<!-- div donde se dibuja el mapa-->
<div id="map_canvas" style="width: 450px; height: 300px;"></div>
<!--campos ocultos donde guardamos los datos-->
<input id="lat" type="text" name="lat" />
<input id="long" type="text" name="lng" />
</form>
I will be very gratefull if someone can help me. Thanks!
Google has disabled the use pt the Maps API for this application. The key you used is not valid or is not authorized for Google maps JavaScript API.
If you obtained this key you still need to enable the use of the JavaScript API
Go to this link for more info:
https://developers.google.com/maps/documentation/javascript/tutorial
I have a HTML form with 6 textboxes that the user needs to fill and before register those values I'd like that the user Preview-them in the same webpage.
It's like a preview of the values inserted above.
The thing is I don't know how to pass those values to another variable (or the same one) and preview them.
HOpe somebody can help me.
Here's my code so far.
<script type="text/javascript">
function validarForm(formulario) {
if(formulario.filmid.value.length==0) { //comprueba que no esté vacío
formulario.filmid.focus();
alert('No has escrito la clave');
return false; //devolvemos el foco
}
if(formulario.nombre.value.length==0) { //comprueba que no esté vacío
formulario.nombre.focus();
alert('No has escrito el nombre');
return false;
}
if(formulario.sinopsis.value.length==0) { //comprueba que no esté vacío
formulario.sinopsis.focus();
alert('No has escrito ninguna consulta');
return false;
}
if(formulario.genero.value.length==0) { //comprueba que no esté vacío
formulario.genero.focus();
alert('No has escrito el genero');
return false; //devolvemos el foco
}
if(formulario.anio.value.length==0) { //comprueba que no esté vacío
formulario.anio.focus();
alert('No has escrito el año');
return false;
}
if(formulario.precio.value.length==0) { //comprueba que no esté vacío
formulario.precio.focus();
alert('No has escrito ninguna consulta');
return false;
}
return true;
}
</script>
<html>
<body>
<?php include 'header.php' ?>
<?php
//variables generales
if(isset($_POST['filmid']) && isset($_POST['nombre']) && isset($_POST['sinopsis']) && isset($_POST['genero']) && isset($_POST['anio']) && isset($_POST['precio'])){
$insertid=$_POST["filmid"];
$insertnombre=$_POST["nombre"];
$insertsinopsis=$_POST["sinopsis"];
$insertgenero=$_POST["genero"];
$insertanio=$_POST["anio"];
$insertprecio=$_POST["precio"];
$insercion=$insertid."|".$insertnombre."|".$insertsinopsis."|".$insertgenero."|".$insertanio."|".$insertprecio."|A\n";
InsertaPelicula($insercion);
}
?>
Registrar nueva pelicula:
<form action="registro.php" method="post" onsubmit="return validarForm(this);">
<table border="1"><tr><td>Clave:</td><td><input type="text" name="filmid"></td></tr>
<tr><td>Nombre:</td><td><input type="text" name="nombre"></td></tr>
<tr><td>Sinopsis:</td><td><input type="text" name="sinopsis"></td></tr>
<tr><td>Genero:</td><td><input type="text" name="genero"></td></tr>
<tr><td>Ańo</td><td><input type="text" name="anio"></td></tr>
<tr><td>Precio</td><td><input type="text" name="precio"></td></tr>
<tr><td><input type="submit" value="Registrar"></td><td></td></tr>
</table>
</form>
<form>
<input type="button" name="Cancel" value="Cancelar" onclick="window.location='index.php'">
</form>
<?php include 'footer.php' ?>
</body>
</html>
Grep the value using e.g. onchange event and set it as content where you like it using e.g. innerHTML. Would be easier with jQuery or another js Framework.
Raw Javascript example:
//HTML:
<input type="text" name="nombre" onchange="passValue(this, 'preview_nombre')"/>
<span id="preview_nombre">before</span>
//Javascript:
function passValue(e, target){
document.getElementById(target).innerHTML = e.value;
}
http://jsfiddle.net/ya5Ty/
I've been searching all around here, but haven't found the way to do this :( And I'm not capable of adapting the existing answers available for this problem.
What I'm doing right now is:
1) When a user clicks on a button, colorbox gets triggered and opens the href attribute, in this case "contact-form.html"
<span class="button green">19.999 € (kit)</span>
$('a.contacto').colorbox({
href:function(){ return $(this).attr('href'); },
width:function(){
if (window.innerWidth > 750) {return '60%';}
else if (window.innerWidth > 481) {return '75%';}
else {return '90%';}},
onComplete:function(){
var ruta = document.location.protocol + "//" + document.location.host + document.location.pathname;
$('input[name=web]').val(ruta);
}
});
2) The form gets displayed in the colorbox
<div id="contactForm">
<h4>Póngase en contacto con nosotros</h4>
<form name="formulario" id="formulario" method="post" action="contact-form.php">
<inputs>........
<input type="reset" name="reset" id="resetbtn" class="resetbtn button" value="Limpiar datos">
<input type="submit" name="submit" id="submitbtn" class="submitbtn button green macro" tabindex="7" value="Enviar consulta!">
<br>
</form>
</div><!--Fin del contactForm-->
3) Once the user completes the form and hits submit, the contact-form.php is triggered (some validation, and the mail sending itself. At the end I inserted a header("Location: " + original-pathname-from-where-the-form-was-sent)
<?php
$errors = ''; /*Para comprobar si ha habido errores*/
/*Retrieve variables from $_POST.......*/
if (empty($emailField)) {
$errors .= "\n Error: Se requiere un correo electrónico";
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $emailField)) {
$errors .= "\n Error: Correo electrónico inválido";
}
$header = /*Prepare the MAIL HEADERS TO BE SENT*/
$mensaje = /*Prepare the MESSAGE........*/
if (empty($errors)) /*Some validation*/
{
if (mail($mi_email, $asuntoEmail, utf8_decode($mensaje), $header)) {
header("Location: $pageRefresh");
}
else {
echo '<script type="text/javascript">';
echo 'alert("Ha habido algun error en el envio. Por favor, vuelva a intentarlo")';
echo '</script>';
}
}
else
{
echo '<script type="text/javascript">';
echo 'alert("Ha habido algun error en el envio:'.$errors.'")';
echo '</script>';
echo '<p>Ha habido algun error:' .$errors. '</p>';
}
?>
EVERYTHING UP UNTIL THIS POINT is done correctly. The mail is sent to my account, with all the variables filled correctly, and the user is relocated to the original page where the form (colorbox) was opened.
What I can't manage to do is:
I would like the form to be submitted via AJAX, not to have to redirect the user to the same page... OR... if that isn't possible, be able at least, to give the user an alert message that the message/mail was sent successfully or not.
Help very much appreciated! Sorry again if this is a repeated question, but I just can't adapt/solve this on my own :(
If you want to submit the form via AJAX, instead of submitting and loading the action url, you can do this using jQuery's serialize function.
There are a few changes to make to your code. First, you need to get rid of the submit button. Do this by changing its type to button:
<input type="button" name="button" id="submitbtn" class="submitbtn button green macro" tabindex="7" value="Enviar consulta!">
Next, we need code to submit the form via AJAX:
<script type="text/javascript">
$('#submitbtn').click(function() {
$.post('contact-form.php', $('#formulario').serialize());
});
</script>
This will submit the form fields, via AJAX, without loading a new URL.
If you want to do something like show a success notification after submission, you can do this:
<script type="text/javascript">
$('#submitbtn').click(function() {
$.post('contact-form.php', $('#formulario').serialize(), function(){
// Anything here is executed if the post is successful
alert('success');
}
);
});
</script>