Jquery UI Dialog working just once? - javascript

As I said on my previous post, I have this bit of php code:
EDIT: I pasted the wrong code, corrected.
<?php
$posts = new Posts();
foreach($posts->getPosts() as $post){ ?>
<div class="post">
<h3><a class="post-link" data-post-id="<?php echo $post['id']; ?>" href="javascript:void(0)"><?php echo $post['title']; ?></a></h3>
</div>
<?php } ?>
<div id="insert-answer" title="Add new idea to post">
<form id="myForm" action="insertidea.php" method="post">
<fieldset>
<p><label for="idea">Your idea:</label>
<input type="text" name="idea" class="idea"</p>
<p><label for="pic">Have a pic? Paste its URL here! (optional)</label>
<input type="text" name="pic" class="pic"></p>
<input type="hidden"class="author" name="author" value="<?php echo $_SESSION['google_data']['id']; ?>" />
<input type="hidden"class="forpost" name="forpost" value="<?php echo $post['id']; ?>" />
</fieldset>
</form>
And I have a form that pops up from each post's link:
$( "#insert-answer" ).dialog({
autoOpen: false,
modal:true,
buttons: {
"Add idea": function() {
var forpost = $("#insert-answer").data("post-id"),
author = $("#author").val(),
idea = $(".idea").val(),
pic = $(".pic").val();
$.post('insertidea.php',{
forpost: forpost, author: author, idea: idea, pic: pic, action:'joined'
});//End Post
$("#insert-answer").val('');
$(".pic").val('');
$(this).dialog("close");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$( ".post-link" ).on('click', function() {
var postid = $(this).data("post-id");
var answer = $("#insert-answer");
$(answer).data('post-id', postid);
$(answer).dialog( "open" );
});
So the user is supposed to be presented with a list of post, each post has a link that pops up the dialog that in turn contains a form that sends data to a mysql database trough another php file via post and it works fine, just only the first time. The second time I get some syntax errors and according to firebug, it comes from the array that is sent to the php file. I'm suspecting my dialog function is incomplete, do I need to "unset" anything after the data is sent? How would I accomplish that?
Thanks a lot!

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>

How to refresh div after ajax success response

I have a form with ajax requests, when the fields are not respected and click on submit button the messages are displayed without page refresh. This works, the problem is that if the form is submitted several times, the error messages accumulate and multiple messages are displayed at the same time.
For example: if you leave field name blank and then submit, the error message (field required) appears. When you enter your name and then submit the success message (Settings Saved) appears but the error message is still visible.
What I want to get is only one message at a time, so the div should update showing the new message and deleting the previous one.
Now, I've tried doing some research and I understand that an if condition with $("#my-div").load("#my-div"); can be used in these cases but i have no idea how to do it, i am new to all this.
Can anyone help me understand how to achieve this? I appreciate any help and thank you for any replies.
My form
<form name="Form" class="mts-edit-account" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<!-- Message section -->
<div class="msg_box"></div>
<!-- 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>
<!-- Save Settings -->
<p 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" />
</p>
</div>
</form>
Script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
jQuery('.msg_box').append(response);
}
});
});
});
Functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$response = wc_print_notices( $return = false );
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}
You've used jQuery('.msg_box').append(response) method for displaying the messages. The documentation clearly states that this is used to insert content, specified by the parameter, to the end of each element in the set of matched elements.
Naturally giving you the multiple messages. If you just need a single message, then use:
jQuery('.msg_box').html(response)
.html() will ensure that the content of the container is overridden each time.
Reference: Official Documentation

To display the records retrieved from database into a dialog box

I have a dialog box which takes a number input.I want to send this number to database and retrieve the name corresponding to that number and display it into another dialog box.My code works fine till retrieving the data but I don't know how to display it into another dialog box.I have created a fiddle https://jsfiddle.net/payalsuthar/rdtpo7e3/
and here is dataretrieve.php-
<?php
include('db.php');
$num = $_POST['num'];
$sql = "SELECT `no`,`name` FROM `table` WHERE `no` = $num ";
if($result=mysqli_query($conn,$sql)){
//i dont know how to display the values retrieved here into my dialog2(you can check my dialog2)
}
?>
Html code-
<form action="dataretrieve.php" method="POST">
<div id="dialog1" title="div1" style="display:none">
Enter the num:<input type="text" name="num" id="num" />
</div>
</form>
<button id="clickMe">Click Me</button>
<div id="dialog2" title="div1" style="display:none">
num:<input type="text" name="number" id="number" />
JavaScript code-
$("#clickMe").click(function(){
$('#dialog1').dialog({
buttons:{
"yes":function(){
$(this).dialog('close');
callback(true);
},
"no":function(){
$(this).dialog('close');
}
}
});
function callback(value){
if(value){
$('#dialog2').dialog({
buttons:{
"ok":function(){
$(this).dialog('close');
},
"cancel":function(){
$(this).dialog('close');
}
}
});
}
}
});
Your code will look something like this (untested):
jQuery Demo
PHP: Use echo to send the data back to javascript side
<?php
include('db.php');
$num = $_POST['number'];
$sql = "SELECT `no`,`name` FROM `table` WHERE `no` = $num ";
if($result=mysqli_query($conn,$sql)){
$out = $result['yourDBfieldname'];
echo $out; //THIS sends it back to javascript side
}
?>
HTML: No need to use a <form> construct -- AJAX is what you need
<div id="dialog1">
Enter the num:<input type="text" name="num" id="num" />
<button id="submit1">Submit</button>
</div>
<button id="clickMe">Click Me</button>
JavaScript/jQuery:
var num, nam;
$("#clickMe").click(function(){
$('#dialog1').dialog('open');
});
$("#submit1").click(function(){
$('#dialog1').dialog('close');
num = $('#num').val();
$.ajax({
type: 'post',
url: 'dataretrieve.php',
data: 'number=' +num,
success: function(recd){
//if (recd.length) alert(recd);
$('#dialog1').html('<input id="name" type="text" value="'+recd+'" /><button id="submit2">Submit</button>');
$('#dialog1').dialog('open');
}
});
});
//Must use .on() because content injected after DOM initially rendered
$(document).on('click', '#submit2', function(){
$('#dialog1').dialog('close');
nam = $('#name').val();
alert('Num: '+num+ ' Name: ' + nam);
});
//Initialize the jQuery dialog - makes the #dialog1 div hidden
$('#dialog1').dialog({
autoOpen:false,
modal:true,
buttons:{
"Close":function(){
$(this).dialog('close');
}
}
});
Note:
No need for two dialogs. You can re-use the one dialog by changing the content inside the #dialog1 div, via the .html() method.

Passing data variables from PHP to jquery ui dialog

I have this bit of php code:
<?php
$posts = new Posts();
foreach($posts->getPosts() as $post){ ?>
<div class="post">
<h3><a class="post-link" data-post-id="<?php echo $post['id']; ?>" href="javascript:void(0)"><?php echo $post['title']; ?></a></h3>
</div>
<?php } ?>
<div id="insert-answer" title="Add new idea to post">
<form id="myForm" action="insertidea.php" method="post">
<fieldset>
<p><label for="idea">Your idea:</label>
<input type="text" name="idea" class="idea"</p>
<p><label for="pic">Have a pic? Paste its URL here! (optional)</label>
<input type="text" name="pic" class="pic"></p>
<input type="hidden"class="author" name="author" value="<?php echo $_SESSION['google_data']['id']; ?>" />
<input type="hidden"class="forpost" name="forpost" value="<?php echo $post['id']; ?>" />
</fieldset>
</form>
And I want to pass the post id data variable to a jquery ui dialog:
$( "#insert-answer" ).dialog({
autoOpen: false,
modal:true,
buttons: {
"Add idea": function() {
var
forpost = $(this).data("post-id"), // HOW CAN I GET THIS???
author = $(".author").val(),
idea = $(".idea").val(),
pic = $(".pic").val();
$.post('insertidea.php',{
forpost: forpost, author: author, idea: idea, pic: pic, action:'joined'
});//End Post
$(".forpost").val('');
$(".author").val('');
$(".idea").val('');
$(".pic").val('');
$(this).dialog("close");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$( ".post-link" ).click(function() {
$( "#insert-answer" ).dialog( "open" );
});
Problem is I'm mostly a php girl and I don't quite grasp the million JS examples I've checked already. What I'm trying to do is use the post id as a variable that comes from php that I can in turn use in my dialog to send to another php script via post.
You could change your post-link function as follows:
$( ".post-link" ).on('click', function() {
var postid = $(this).data("post-id");
var answer = $("#insert-answer");
$(answer).data('post-id', postid);
$(answer).dialog( "open" );
});
And then grab in in the "Add idea": function() { part with:
var forpost = $("#insert-answer").data("post-id"),
author = $(".author").val(),
idea = $(".idea").val(),
pic = $(".pic").val();
So what you are doing is basically saving the current post-id to #insert-answer and getting it from there in your dialog. Is this what you were after?
UPDATED CODE: #charlietfl is absolutely right, var post-id is not correct, I have edited the name of the variable.

issue with jquery toggle open/clos

i have a small pm system and use buttons to toggle the message open or close.
if no message is open the button shows 'lesen' bei click the button it opens the message and the text changes to 'schliessen'. i can open everey message but not close them. than the message close once and opens again but the buttontext than shows still 'lesen'
i hope u understand what i try to explain :)
here is my code:
this will set the opened message as read in the database.
<script type="text/javascript">
function setRead($id){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { id: $id}
});
}
this will open or close the message.
<script type="text/javascript">
function toggleOpenClose(id) {
$('#message-'+id).slideToggle("fast");
if(document.getElementById(id).innerHTML === "lesen") {
document.getElementById(id).innerHTML = "schließen";
} else {
document.getElementById(id).innerHTML = "lesen";
}}
<?php
while ($row = mysql_fetch_array($result)) {
?>
<form action="reply.php" method="post">
<p class="button"> <a class="open-close">
<div id="container">
<div class="item">
<span class="toggleOpen" onclick="setRead(this.id); toggleOpenClose(this.id);" id="<?php echo $row['id']; ?>" name="gelesen">lesen</span>
<div id="message-<?php echo $row['id'];?>" class="toggle">
<p><?php echo $row['nachricht']; ?></p>
<p><input class="button-link" type="submit" name="reply" value="Antworten"></form></p>
<p><form action="mailbox.php" method="post">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<input class="button-del" type="submit" name="delete_perm" style="vertical-align: top; margin-top: 20px;" value="Löschen"></p></form>
why will the message not stay close by clicking close?
i still haven't figured out what is wrong. if i use
<script type="text/javascript">
$(function() {
$('span.toggleOpen').click(function() {
$(this).next('.toggle').slideDown("fast");
});
$('span.toggleClose').click(function() {
$(this).parents('.toggle').slideUp("fast");
});});
then it works, but i have to use two buttons (open and close) and both are always shown. what i want is one button that change the text by opening or close a message.

Categories