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
});
Related
I have a little problem here. I'm working on a simple quotation form on wordpress.
I have two forms, the first one sends data to jQuery that does all the calcs (very few options so we didn't use a DB), then prints an html row. No issue until here; the problems start when I'm trying to send that row/rows to PHP to send a simple email. I've tried with ajax and wp_mail but with no success.
Here is what i've tried:
HTML inside wordpress template file:
<!--first form with data to calculate-->
<form class="needs-validation">
<!--select fields, no problem here-->
</form>
<div class="table-responsive"> <!--risultato preventivo-->
<table class="table table-bordered" id="dynamic_field">
<tr>
<!--result given by jQuery-->
</tr>
</table>
<p id="total"><!--total price passed by jQuery--></p>
</div>
<!--second form for sending email-->
<form action="#" method="POST">
Nome:<br>
<input type="text" name="nome" id="nome">
<br>
Cognome:<br>
<input type="text" name="cognome" id="cognome">
<br>
Email:<br>
<input type="email" name="email" id="email">
<input type="hidden" name="invia" value="s">
<input type="submit" id="inviaForm" value="Invia">
</form>
<div id="worked"></div>
jQuery with calcs inside file main.js:
(function ($) {
$(document).ready(function () {
function generaRisultato (riga,nProfilo,nColore,nSerramento,costoRiga){
var risultato = '<tr id="row' + riga +
'" class="dynamic-added"><td><div><h5 class="my-0">Articolo: ' + nProfilo +
'</h5><br><small class="text-muted">Colorazione: ' + nColore +
'</small><br><small class="text-muted">Serramento: ' + nSerramento +
'</small></div><span id="costo-riga'+riga+'">'+costoRiga+'€</span></td>'+
'<td><button type="button" name="remove" id="'+ riga +'" class="btn btn_remove">-</button>
</td></tr>';
return risultato;
}
//calcs done correctly
$('#dynamic_field').append(generaRisultato(i,profile,color,name,price)); //result printed
var risultatoFinale = $('#dynamic_field').html(); //variable with result stored for email
//sending form mail ajax
$('#inviaForm').on('submit', function(e){
//evito l'invio del form
e.preventDefault();
//recupero i valori
var nomeUser = $('#nome').val();
var cognomeUser = $('#cognome').val();
var emailUser = $('#email').val();
var totaleFinale = $('#totale').html();
var preventivoFinale = $('#dynamic_field').html();
//eseguo la chiamata ajax
$.ajax({
type: "POST",
url: my_vars.ajaxurl,
data: {
action : 'invio_mail', //azione da eseguire
_nonce : my_vars.nonce,
nome : nomeUser,
cognome : cognomeUser,
email : emailUser,
totale : totaleFinale,
preventivo : preventivoFinale
},
success: function(res){
$('#funzionante').html(res);
}
});
});
});
})(jQuery);
PHP inside functions.php:
function vf_load_theme_preventivatore(){
wp_register_script('main', get_template_directory_uri().'/preventivatore/js/main.js', false, false,
true);
wp_enqueue_script('main');
wp_localize_script( 'main', 'my_vars', array(
'ajaxurl' =>admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('invio-mail-nonce')
));
}
add_action('wp_enqueue_scripts', 'vf_load_theme_preventivatore');
function invio_mail_ajax(){
//verifico che il nonce sia corretto
if(!wp_verify_nonce( $_REQUEST['_nonce'], 'invio-mail-nonce') ){
die('Non autorizzato!');
}
//Prepariamo le variabili da usare
$successo = '';
$nome = strval($_REQUEST['nome']);
$cognome = strval($_REQUEST['cognome']);
$email = $_REQUEST['email'];
$preventivo = $_REQUEST['preventivo'];
$totale = $_REQUEST['totale'];
//script mail
$header = "From: Site <test#site-domain.it>\n";
$header .= "BCC: Altro Ricevente <test2#my-domain.it>\n";
// costruiamo le intestazioni specifiche per il formato HTML
$header .= "Content-Type: text/html; charset=\"UTF-8\"\n";
$oggetto = "Ecco il tuo preventivo";
$messaggio = "<html><body><p>Richiesta preventivo da sito</p><p>Nome: ".$nome."</p><p>Cognome:
".$cognome."</p><p>Email: ".$email."</p> <p>Dati del preventivo</p><p>".$preventivo."</p><p>Totale:
".$totale."€</p></body></html>";
$inviata = wp_mail($email,$oggetto,$messaggio,$header);
$successo .= '<p>'.$nome.'</p>';
echo $successo;
die();
if($inviata){
$successo = '<p> email invata</p>';
echo $successo;
die();
} else die('errore nella mail');
}
add_action('wp_ajax_invio_mail','invio_mail_ajax');
add_action('wp_ajax_nopriv_invio_mail','invio_mail_ajax');
That's what i've done, i've simply hidden the jQuery calculations because that worked flawlessly.
I wanted to send an email with an html formatted text, with this solution the email doesn't even get sent (before putting ajax and php script in fuction the email arrives, php was inside the template file), also i cannot pass the html table rows with results and the total of the quotation. Maybe i got wrong the ajax or php part.
Is there any help about this? thank you for all your support!
Created AJAX submit form. Tested working good you can change your data. Hope this help you.
Copy and paste in your function.php file
function invio_mail(){
$to = 'sendto#example.com';
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
echo 'mail send';
die;
}
add_action("wp_ajax_invio_mail", "invio_mail");
add_action("wp_ajax_nopriv_invio_mail", "invio_mail");
Just paste you want the page (Form)
<form id="ajaxformid" action="#" method="POST">
Nome:<br>
<input type="text" name="nome" id="nome">
<br>
Cognome:<br>
<input type="text" name="cognome" id="cognome">
<br>
Email:<br>
<input type="email" name="email" id="email">
<input type="hidden" name="invia" value="s">
<input type="submit" id="inviaForm" value="Invia">
</form>
Just paste in footer
<script>
jQuery(document).ready(function($) {
var frm = $('#ajaxformid');
frm.submit(function (e) {
var formData = {
nome: jQuery('#nome').val(),
cognome: jQuery('#cognome').val(),
email: jQuery('#email').val(),
action:'invio_mail'
};
$.ajax({
type : 'POST',
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : formData,
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
e.preventDefault();
});
});
</script>
i have issue in laravel 5.1 with insert a multiple inputs intro DB.
i build a query code for multiple inputs and after that i send them to controller but i have there a issues to insert it to DB
how i can insert the inputs to db if the results its like this:
{"_token":"C6m83bcZKaQsOtRiYEKxJAzzZjvdLerl9QpsvSSs","client_id":["aJQsijwqFVG9r0","aJQsijwqFVG9r0"],"short":["4","11"],"url":["567567567567","3453434534"]}
the code:
HTML:
<form class="js-validation-material form-horizontal push-10-t" action="{!! url() !!}/addreg" method="post">
{!! csrf_field() !!}
<div class="form-group">
<div id="buildyourform"></div>
</div>
<div class="form-group">
<div class="col-xs-12">
<button class="btn btn-sm btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div.form").length + 1;
var fieldWrapper = $("<div class=\"form col-sm-6 col-lg-6\" id=\"field" + intId + "\"><div class=\"form-material\">");
var client_id = $("<input type=\"hidden\" name=\"client_id[]\" value=\"{!! $task->client_id !!}\" class=\"form-control\" />");
var langname = $("<select type=\"text\" name=\"short[]\" class=\"form-control\">{!! $data['langs'] !!}</select>");
var url = $("<input type=\"text\" name=\"url[]\" class=\"form-control\" placeholder=\"Insert a url..\" />");
var label = ("<label for=\"date\"><h3 class=\"block-title\">Lang" + intId + "</h3></label>");
var removeButton = $("<button class=\"btn btn-danger btn-xs push-5-r push-10\" type=\"button\"><i class=\"fa fa-times\"></i></button>");
removeButton.click(function() {
$(this).parent().remove();
});
$("#buildyourform").append(fieldWrapper);
$("#field" + intId + " .form-material").append(client_id,langname,url,removeButton,label);
});
});
</script>
the results need to be in the DB like:
DB::table('table')->insert([
['client_id' => $request->client_id],
['short' => $request->short],
['url' => $request->url],
]);
for each input.
The problem is you are sending multiples inputs with the same name, so it only get the last one.
Everytime you do and "add" try to wrap them in a div with a class (example: "foo"). So you will get some "foo" divs.
Create a hidden input called for example "items"
{{ Form::hidden('items') }}
Next you have to overwrite the click function of the submit button:
$('#submit-form').click(function(e){
a = {};
$.each($('.foo'), function(k,v){
a[k] = $(v).find(':input').serializeArray()
});
$('input[name="items"]').val(JSON.stringify(a));
$('#form').submit()
}
And in the controller:
$items = json_decode(Input::get('items'), true);
Then you have an array with all of your inputs.
I have a column in Database with name URL and ID(PK) i'm using PHP/MYSQL
Im displaying values from db now i want to perform EDIT(update) operation Using Jquery/Ajax.
When i click on Edit link it is replaced with Update/Cancel links Which is working fine and im able to perform update operations.
My requirement is when i click on edit Url data which im using lable tag should replace with input textbox and i should perform update operation
HTML Code
<div class='col-md-4'>
<label class="feed_label" id="feed_label" idl='<?php echo $row->id;?>'><?php echo $row->url; ?></label>
<input name="url1" class="form-control url1 feed_text" value="<?php echo $row->id;?>" id="url1" type="text" placeholder="enter url" style="display:none;">
</div>
<div class='col-md-2'>
<a ide='<?php echo $row->id;?>' id="edit" class='edit' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update btn btn-primary btn-sm' href='#' style='display:none;'>UPDATE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancel btn btn-warning btn-sm' href='#' style='display:none;'>CANCEL</a>
</div>
JQUERY CODE
JQUERY CODE
//EDIT,DELETE TO UPDATE,CANCEL
$('body').delegate('#edit','click',function(){
//alert();
$(this).siblings('#delete').hide();
$(this).siblings('#update,#cancel').show();
$(this).hide();
$('#feed_label').removeClass('feed_label').addClass('feed_url');
});
$('body').delegate('#cancel','click',function(){
//alert();
$(this).siblings('#edit,#delete').show();
$(this).siblings('#update').hide();
$(this).hide();
$("#update_url")[0].reset();
});
//ENDS
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
//alert(IdEdit);
//return false;
$.ajax({
url:"pages/feeds.php",
type:"post",
datatype:"json",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
//alert('success');
$('#id').val(show.id);
$('#url1').val(show.url);
//$('#add_feed_form')[0].reset();
//$('#showdata').load('pages/feeds.php');
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
//alert('update');
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
//alert();
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
//alert('updated');
$('input[type=text]').val('');
showdata();
$('#add_feed_form')[0].reset();
$('#showdata').load('pages/feeds.php');
}
});
});
//UPdate Ends
PHP Code
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
//Ends
Any help Is appreciated Thanks!!
Here i give sample for your case :
HTML
<div class="container">
<label>John</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
<hr/>
<div class="container">
<label>John Who</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
JS (you can simplified below code into one handler)
$(document).on('click', '.edit', function(e){
var data = $(this).prev();
if ( data.is('label') ) data.replaceWith('<input value="'+data.text()+'">');
});
$(document).on('click', '.delete', function(e){
var data = $(this).prev().prev();
if ( data.is('input') ) data.replaceWith('<label>'+data.val()+'</label>');
});
DEMO
I want to add a div without refreshing the page.
Here is my Javascript:
<input class="btnsubmit" type="button" value="+Add Trivia" id="add_triviamodal">
function add_trivia()
{
var PHOTO_TRIVIA = CKEDITOR.instances.Trivia_Photo.getData();
var TITLE_TRIVIA = $('#TRIVIA_TITLE').val();
var CAPTION_TRIVIA = CKEDITOR.instances.triviacap.getData();
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
location.reload(); \\what i do is just refresh the page
});
}
This is how i output the the data that will be added using the ajax above
echo "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
}
You can use append() in jQuery to append elements to the DOM. If the div is returned by your PHP. Then append it to a DOM element by using i.e. $('#trivias').append(data);
EDIT (using the question authors code as an example):
I've replaced the location.reload() part with the code to append the returning div.
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
$('#trivias').append(data);
}
Here I assume you've got a element with the trivias id. For example <div id="trivias">...</div> somewhere in your code already.
just put your response data into whatever you want it in
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
$('#idOfTheDivYouwantToPutResponseIn').html(data);
});
Change your $.post() callback to also append the HTML response from insert_home.php into the DIV.
$.post('insert_home.php',{
TRIVIA_TITLE: TITLE_TRIVIA,
TRIVIA_PHOTO: PHOTO_TRIVIA,
TRIVIA_CAP: CAPTION_TRIVIA
}).done(function(data){
alert ("Trivia Successfully Added");
$('#trivias').html(data);
});
in PHP use json_encode
$str = "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
echo json_encode($str);
then use he post request like this
$.ajax({
type: "POST",
url: 'insert_home.php',
data: {TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA},
dataType:'json',
success: function (data) {
$('#your_id').html(data);
}
});
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>