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.
Related
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
This is my HTML code where I'm creating a simple HTML form in my plugin settings page:
<?php
/**
* Adds a submenu page under a custom post type parent.
*/
function books_register_ref_page()
{
add_submenu_page('edit.php?post_type=fscf_contact', __('Setting', 'fscf') , __('Settings', 'fscf') , 'manage_options', 'setting-fscf-contacts', 'fscf_contact_page_callback');
// call register settings function
add_action('admin_init', 'register_my_fscf_contact_settings');
}
function register_my_fscf_contact_settings()
{
// register our settings
register_setting('fscf-plugin-settings-group', 'fscf_field_1');
}
/**
* Display callback for the submenu page.
*/
function fscf_contact_page_callback()
{
?>
<div class="wrap">
<h1><?php
_e('Contact Form Setting', 'textdomain'); ?></h1> <hr>
<div class="wrap">
<form method="post" action="" id="myform">
<?php
settings_fields('fscf-plugin-settings-group'); ?>
<?php
do_settings_sections('fscf-plugin-settings-group'); ?>
<table class="form-table" id="p_scents">
<tr valign="top">
<th scope="row">New Option Name</th>
<td> <p>
<label for="p_scnts">
<input type="text" name="fscf_field_1" id="fscf_field_1" value="<?php
echo esc_attr(get_option('fscf_field_1')); ?>" /> <input type="button" id="addScnt" name="" value="+">
</label>
</p> </td>
</tr>
</table>
<?php
$other_attributes = array(
'id' => 'submit_repeatable_fields'
);
submit_button("Submit", "submit", "submit", false, $other_attributes); ?>
<span id="fscf_error"></span>
</form>
</div>
</div>
<?php
}
add_action('init', 'books_register_ref_page');
This is my .js code where I'm repeating <tr> in HTML form:
jQuery(document).ready(function() {
var scntDiv = jQuery('#p_scents');
var i = jQuery('#p_scents p').size() + 1;
jQuery('#addScnt').live('click', function() {
jQuery('<tr valign="top"><th scope="row">New Option Name</th><td> <p><label for="p_scnts"><input type="text" name="fscf_field_' + i +'" id="fscf_field_' + i +'" value="" /> Remove</p> </td></tr>').appendTo(scntDiv);
i++;
return false;
});
jQuery('#remScnt').live('click', function() {
if( i > 2 ) {
jQuery(this).parents('#p_scents tr').remove();
i--;
}
return false;
});
// Making Ajax Request for settings
jQuery("#myform").submit(function(e) {
e.preventDefault();
var formdata = jQuery("#myform input[type='text']").serializeArray();
var numberflds = jQuery("#myform input[type='text']").size();
var data = {
'action' : 'fscf_create_repeatable_fields',
'fullform':jQuery("#myform input[type='text']").serializeArray(),
'fields': numberflds,
//nonce : security
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_obj.ajax_url, data, function(response) {
console.log(response);
jQuery("#fscf_error").html(response);
});
});
});
Here is my php code where I want to save fields which I had repeated in .js file but I'm unable to save data:
function fscf_create_repeatable_fields(){
$mydata = $_POST['fullform'];
$fields = $_POST['fields'];
//$i=0;
foreach ($_POST['fullform'] as $form) {
register_setting( 'fscf-plugin-settings-group', $form['name']);
//$i++;
}
echo "Field Created.";
wp_die();
}
add_action( 'wp_ajax_nopriv_fscf_create_repeatable_fields', 'fscf_create_repeatable_fields' );
add_action( 'wp_ajax_fscf_create_repeatable_fields', 'fscf_create_repeatable_fields' );
So, the problem is I can't save repeatable fields in my plugin page. What mistake I'm doing?
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.
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!
I've been trying to hide this div ID #signup within this code I'm working in and can't seem to get it work with what I've been doing. Any good way of hiding this div ID by fading out and in return fading in the new div #test? Here's what I got!
HTML (index)
<form id="signup" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
<fieldset>
<label for="email" id="address-label">Email Address</label>
<input type="text" name="email" id="email" />
<input type="image" src="i/join.jpg" name="submit" value="Join" class="btn" alt="Join" />
</fieldset>
</form>
<div id="response">
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
<div id="test">test</div>
</div>
CSS
#test {display: none;}
JS/PHP (inc/store-address.php)
<?php
function storeAddress(){
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
( "#signup" ).hide( "slow" );
( "#test" ).show( "slow" );
}
else {
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
From what I can see you are trying to mix php and Javascript in one function, but this will not work. Php runs serverside before the webpage has been sent to the client, and Javascript runs only on the client and only after the page has been sent.
You will need to do this in JavaScript most likely, Jquery is a light library that is highly reccomended for a task like this.
here is a link where the code below was harvested from.
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
You could use php to conditionally output js to the browser - not the most elegant but it will work; The comments about server / client side are important and you do have to be very mindful of single / double quotes.
<?php
function storeAddress(){
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
echo '<script>';
echo '$( "#signup" ).hide( "slow" );';
echo '$( "#test" ).show( "slow" );';
echo '</script>';
}
else {
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>