Wordpress Modal form ajax send - javascript

Let's see if you can help me, because I'm stuck because I can't get the ajax instruction to save the data to be executed
I have a modal window in the admin of my wordpress plugin, which I did via thickbox. The code for that modal is:
<p>Por favor, elija la configuración para <b><?php echo($_GET['title']);?></b>:</p>
<form method="post" id="ajax-form">
<label for="tipo">Introduzca el tipo de producto</label>
<select name="tipo" id="tipo">
<option value="Subscripción">Subscripción</option>
<option value="Sesion">Sesion</option>
</select><br><br>
<label for="cantidad">Introduzca el número de sesiones o de meses de subscripción</label>
<input name="cantidad" id="cantidad"></input>
<input id="id" name="id" type="hidden" value="<?php echo($_GET['id']);?>"><br>
<input type="submit">
<script type="text/javascript">
jQuery(document).ready(function(event) {
jQuery('#ajax-form').submit(ajaxSubmit);
function ajaxSubmit() {
var ajaxform = jQuery(this).serialize();
jQuery.ajax({
action: 'grabardatos_desde_modalform',
data: ajaxform,
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
success: function(data) {
alert("GUAYYYYYY");
}
});
}); }
</script>
</form>
The php code that should process the data is:
add_action('wp_ajax_grabardatos_desde_modalform' , 'grabardatos_desde_modalform');
add_action('wp_ajax_nopriv_grabardatos_desde_modalform','grabardatos_desde_modalform');
function grabardatos_desde_modalform(){
$datos=array(
$_POST['id'] => array(
'cantidad' => $_POST['cantidad'],
'tipo' => $_POST['tipo']
));
error_log(print_r($datos));
update_option('arrayproductos',$datos);
}
But I don't know why the query is not executed, because when I hit send it is as if the modal was reloaded.
On the other hand, I also need that after processing the data the main page is redirected.

Related

Woocommerce - wc_print_notices returns two messages instead of one, what's wrong?

I'm editing woocommerce form-edit-account.php, in this template there is a form that allows users to change name, surname, address etc. I added ajax requests to save the data without reloading the page. The data is saved correctly, so the ajax request works fine. The only step I can't get to work properly are handling error messages.
The problem
when click on submit button and the data is saved successfully, two messages appear.
The first message is the original woocommerce message: "Account details changed successfully", and can be found at https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.346. The second message is what I wrote in my functions.php with wc_add_notice.
Expectations
I should only get the message I added to functions.php with wc_add_notice, why am I getting the original message as well? What am I doing wrong ?
Hope someone can help me with this, I can't figure out where the mistake is. I appreciate any help and thank you for any replies.
Js which handles updating fields and error / success message
$(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error msg
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data) {
$('.newdiv').html(data);
}, 'json'
);
//Ajax Save settings
$.ajax({
type: "POST",
data: $(".mts-edit-account").serialize(),
beforeSend: function() {
$(".container_loader").show();
},
success: function(data) {
$(".container_loader").hide();
}
});
});
});
Handling error in functions.php
// Validate - my account
add_action( 'woocommerce_save_account_details_errors', array( &$user, 'save_account_details' ), 10, 1);
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
function save_account_details( &$user ) {
if (isset( $_POST['account_first_name'] ) == '') {
wc_add_notice("<b>Nome</b> è un campo obbligatorio", "error");
$response = wc_print_notices(true);
} else if (isset($_POST['account_first_name']) ) {
wc_add_notice("Modifiche salvate con successo", "success");
$response = wc_print_notices(true);
}
echo json_encode($response);
exit();
}
Example of my form html
<form name="Form" class="mts-edit-account" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<?php do_action( 'woocommerce_edit_account_form_start' ); ?>
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
</div>
<!-- Other fields -->
<!-- Save Info Settings -->
<div style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</div>
</form>

Upload an excel in my view to display it in the controller

I want...
Upload an excel file to my server in my view (only temporary because I will only read it, get its data and save it to a DB), then use fopen () on my controller, and open that file that the user uploaded in the view . (I am using CI)
Issue...
When I try to open the file in my controller it does not exist.
What I have...
view
<?php
print_r($_FILES);
$archivo = fopen($_FILES["csv"]["tmp_name"], 'r');
?>
<?php echo form_open_multipart('',array('id' => 'envio', 'role'=>'form')); ?>
<legend>Importar Datos</legend>
<?php if (isset($alerta) && $alerta): ?>
<div class="alert alert-danger">
<?=$alerta ?>
</div>
<?php endif; ?>
<div class="form-group">
<label for="">Archivo CSV</label>
<input type="file" class="form-control" id="csv" name="csv" placeholder="Archivo CSV">
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="1" name="has_header" checked>
El archivo contiene cabeceras
</label>
</div>
<input type="hidden" name="key" value="1">
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
<script type="text/javascript">
function al_inicio()
{
console.log("on submit set");
$( '#envio-t' )
.submit( function( e ) {
console.log('submitting');
e.preventDefault();
$.ajax( {
// url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
dataType: 'script'
} );
} );
}
</script>
Controller_api
function dev_get(){
print_r($_FILES);
$archivo = fopen($_FILES["csv"]["tmp_name"], 'r');
}
Images
This is in View
This is in Controller

Ajax request only works one time [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I have a select option which is working perfectly but only one time, the request does not executes again.
I think it's because of the 'onchange' event.
This is my ajax code :
jQuery(document).ready(function($) {
$('#referenceProduit').change(function(){
//on recupere la valeur de l'attribut value pour afficher tel ou tel resultat
var req=$('#referenceProduit').val();
//requête ajax, appel du fichier function.php
$.ajax({
type: "POST",
url: "include/php.php",
data: "referenceProduit="+req,
dataType : "json",
//affichage de l'erreur en cas de problème
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
//function s'il n'y a pas de probleme
success:function(data){
//On affiche la réponse du serveur
$('.produit').empty();
$('.produit').prepend(data.produit);
$('input[name="designation"]').val(data.resDisplayForm.designation);
$('input[name="prix"]').val(data.resDisplayForm.prix);
}
});
});
});
HTML code :
<div class="form-group">
<label for="referenceProduit" class="col-sm-1 control-label">Reference</label>
<div class="col-sm-2">
<select class="form-control" name="referenceProduit" id="referenceProduit">
<option selected="selected" disabled="disabled">Choisir</option>
<?php foreach($lesProduits as $unProduit){?>
<option name="<?php echo $unProduit['id'];?>" value="<?php echo $unProduit['id'];?>"><?php echo $unProduit['reference']?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<div class="produit"></div>
</div><br/><br/>
You should map to
.on(eventType, selector, function)
example
$('#parentElement').on('change', '#referenceProduit', function)

Reselect dropdownlist after submit/error . validation

I'm sorry but my brain is totally fogging up on this one.
I want to have my dropdownlist 'editprojectSelect' to be selected if there is an error with validation. P.S. in the picture i posted u can see i specifically entered a string 'test' where there should be an integer.
<div id="project-wijzigen" class="form">
<h2> Wijzig een project </h2>
<select id="editprojectSelect" name="editprojectSelect" onchange="getDetails()">
<option value="">-</option>
</select>
<?php echo '<input type="hidden" id="hidden-input" value="'.$_POST['editProjectSelect'].'">';?>
<div id="editProject">
<?php echo form_open('c_admin/wijzigProject');?>
<h2 id="hoofding"></h2>
<div><label> Project titel: </label> <input type="text" id="pt" name="titel" required value="<?php echo set_value('projecttitel'); ?>"/></div>
<div><label> Startdatum: </label> <input type="text" id="sd" name="start" required value="<?php echo set_value('startdatum'); ?>"/></div>
<div><label> Einddatum: </label> <input type="text" id="ed" name="eind" required value="<?php echo set_value('einddatum'); ?>"/></div>
<div><label> In samenwerking met: </label> <input type="text" id="samen" name="samen" required value="<?php echo set_value('ism'); ?>"/></div>
<div><label> Omschrijving: </label> <textarea id="omschr" name="text" required value="<?php echo set_value('text'); ?>"></textarea></div>
<input type="hidden" id="hiddenID" name="hiddenID" />
<input type="submit" name="submit" value="Wijzig project"/>
<?php echo form_close(); ?>
</div>
<?php
// --------------------------- Error checking/display
if(isset($projectWijzigenError)) // check of de variabele wel een waarde heeft (als je die zomaar oproept en hij moest leeg of NULL zijn dan krijg je een error op je pagina)
{
if ($projectWijzigenError=='true') // ALS er een error is, dan opent de form terug en worden errors weergegeven
{
?>
<script>
$("#editProjectSelect").val($('#hidden-input').val());
$('#project-wijzigen').show();
$(this).toggleClass('close');
</script>
<?php
echo validation_errors('<p class="error">');
}
}
// -------------------------- End error checking/displaying
?>
</div>
---------------
$(document).ready(function()
{
$(function()
{
$.ajax(
{
url:"<?php echo site_url("c_admin/ajaxTitels");?>",
type: 'POST',
success: function(msg)
{
var jsonMsg = $.parseJSON(msg);
var count = Object.keys(jsonMsg).length;
for(var x = 0; x < count; x++)
{
$("#projectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#delprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#editprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
}
}
});
});
})
function getDetails()
{
//$("#editProject").empty();
document.getElementById('editProject').style.display = "none";
$(".error").empty();
var sel = document.getElementById('editprojectSelect');
var opt = sel.options[sel.selectedIndex];
var p = opt.value;
if(p != "")
{
document.getElementById('editProject').style.display = "block";
//$("#editProject").append($("<label></label><br />").html("test"));
$.ajax(
{
url:"<?php echo site_url("c_admin/ajaxProject");?>",
type: 'POST',
data: {project: p},
success: function(msg)
{
var jsonMsg = $.parseJSON(msg);
$('#hoofding').html(jsonMsg.Projecttitel);
document.getElementById("pt").value = jsonMsg.Projecttitel;
document.getElementById("sd").value = jsonMsg.Startdatum;
document.getElementById("ed").value = jsonMsg.Einddatum;
document.getElementById("samen").value = jsonMsg.ISM;
document.getElementById("omschr").value = jsonMsg.Projecttekst;
document.getElementById("hiddenID").value = jsonMsg.ProjectID;
}
});
}
}
$(document).ready(function()
{
$(function()
{
$.ajax(
{
url:"<?php echo site_url("c_admin/ajaxTitels");?>",
type: 'POST',
success: function(msg)
{
var jsonMsg = $.parseJSON(msg);
var count = Object.keys(jsonMsg).length;
for(var x = 0; x < count; x++)
{
$("#projectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#delprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#editprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
}
}
});
});
if(isset($projectWijzigenError) AND ($projectWijzigenError == true)){
var projectId = '<?php echo set_value('editProjectSelect'); ?>';
//set the select field
$("#editProjectSelect").val(projectId);
//call the getDetails function to populate your fields
getDetails();
}
Your <select> field is not inside the <form> element. So when you submit the form, the field is not submitted and PHP/codeigniter does not know your old value.
What you can do is, put the select field inside the form.
Once your form is submitted and if there are validation errors, do the following:
Get the value of the editprojectSelect, and in $(document).ready part of jquery after the ajax call, set the value of the select to what you got from your form.
After that, call the getDetails() function.

Codeigniter ajax request fail on output

I'm trying to make an ajax request with jquery/codeigniter. Well, there seems to be a problem. i do get it to work, but it seems like the POST is not sent, for some reason...
Javascript
$('#profileUpdateButton').click(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
From the codeigniter controller
if($this->input->is_ajax_request()) {
echo $this->input->post('profileUpdate');
}
If i replace the "echo $this->" etc.. with just echo "Hello" i do get an alertbox with "Hello", why don't i get the text from the box?
html
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
Change your html markup to this...
<div id="statusUpdate"> <!-- Use ID not NAME here |v| -->
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
you were setting the form's name and you were selecting $('#statusUpdateForm') which means the id of statusUpdateForm, not the name attribute...

Categories