WP wp_update_user($userdata) Error - php

I am working with WordPress 3.9 and Woocommerce in templates/../my-account.php. I did not like the default my-account page and wanted the user to be able to edit specific settings so I set it up so the user can change their username, email, or password. That was the goal at least haha.
In the debugging process, I found the problem was with $user_id = wp_update_user( $userdata ); . is_wp_error($user_id) returns false. When I use wp_get_current_user(); I am able to echo user_email, for example, and the user's email is displayed. I'm pretty sure I created the $userdata array correctly, so what do I need to change to be able to update the user's settings?
I could be making a mistake, but to my knowledge I'm doing everything according to the codex docs.
Here's my code for my-account.php if you need other code or more information I can supply. Thank you for any help.
<?php
/**
* My Account
*/
global $woocommerce;
global $current_user;
?>
<style type="text/css">
#edit-account-settings { font-size: 1.2em; width: 280px; }
#edit-account-settings input { width: 100%; }
#edit-submit { font-size: 1em; }
</style>
<?php
wp_get_current_user();
if(is_null($current_user)) {
echo 'Sorry, you are not logged in. '.wp_loginout();
} else {
$php_option = false;
$fName = $current_user->first_name;
$lName = $current_user->last_name;
$username = $current_user->user_login;
$email = $current_user->user_email;
print '<div id="account-settings"><h2>Welcome '.$fName.' '.$lName.'</h2>';
print '<p style="font-size: 1.4em;">User Name: '.$username.'</p>';
print '<p style="font-size: 1.4em;">Email: '.$email.'</p>';
print '<p style="font-size: 1.4em;">Password: ********</p>';
print '<a id="edit-account-settings" href="#" onclick="edit_settings();">Change your account settings</a></div>';
}
?>
<script>
function edit_settings() {
//alert("inside onclick event");
var username = <?php echo json_encode($username); ?>;
var email = <?php echo json_encode($email); ?>;
var data = '<p style="font-size: 1.2em;">To change your settings, enter the new value in the appropriate text field</p>';
data += '<p style="font-size: 1.2em;">If do not want to change your password, enter your current password twice.</p>';
data += '<p style="font-size: 1.2em;">If you want your other settings to remain the same, leave the fields as they are and submit.</p>';
data += '<form id="edit-account-settings" name="edit-account-settings" method="post" action="">';
data += '<label for="un">User Name: </label><input type="text" id="un" name="un" value="'+username+'" maxlength="16" required />';
data += '<label for="email">Email: </label><input type="email" id="em" name="em" value="'+email+'" maxlength="32" required />';
data += '<br /><br /><input type="password" id="p1" name="p1" value="" placeholder="Enter a new password" maxlength="16" required />';
data += '<br /><br /><input type="password" id="p2" name="p2" value="" placeholder="Re-enter password" maxlength="16" required />';
data += '<br /><br /><input type="submit" id="edit-submit" name="edit-submit" value="Submit Changes" />';
data += '</form></div>';
var elem = document.getElementById("account-settings");
elem.innerHTML = data;
}
</script>
<?php
if (isset($_POST['em']) && $_POST['em'] != $email && $_POST['em'] != "") {
$em = $_POST['em'];
$userdata = array(
'user_email' => $em
);
if (!empty($userdata) || isset($userdata['user_email'])) {
$user_id = wp_update_user( $userdata );
if(is_wp_error($user_id)) {
echo "<p style='color: #FF0000;'>Error: Sorry your settings could not be updated. Please try again in a minute.</p>";
} else {
echo "<p style='color: #00FF00;'>Congradulations! Your settings have been updated.</p>";
}
} else {
echo "<p>$userdata is null or undefined</p>";
}
} else {
echo "<p>Your email address is the same</p>";
}
?>
<?php do_action('woocommerce_before_my_account'); ?>
<?php if ($downloads = $woocommerce->customer->get_downloadable_products()) : ?>
<h2><?php _e('Available downloads', 'woocommerce'); ?></h2>
<ul class="digital-downloads">
<?php foreach ($downloads as $download) : ?>
<li><?php if (is_numeric($download['downloads_remaining'])) : ?><span class="count"><?php echo $download['downloads_remaining'] . _n(' download remaining', ' downloads remaining', $download['downloads_remaining'], 'woocommerce'); ?></span><?php endif; ?> <?php echo $download['download_name']; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<h2><?php _e('Recent Orders', 'woocommerce'); ?></h2>
<?php woocommerce_get_template('myaccount/my-orders.php', array( 'recent_orders' => $recent_orders )); ?>
<h2><?php _e('My Address', 'woocommerce'); ?></h2>
<p class="myaccount_address"><?php _e('The following addresses will be used on the checkout page by default.', 'woocommerce'); ?></p>
<?php woocommerce_get_template('myaccount/my-address.php'); ?>
<?php
do_action('woocommerce_after_my_account');

I believe you need to include the user's ID in your $userdata array. For instance:
$userdata = array(
'ID' => $current_user->ID,
'user_email' => $em
);

Related

Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?

i iclude a wordpress media selector in my wordpress plugin.
i got this error :
Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
error
i added to this code to wp-config.php file :
`
/** WordPress değişkenlerini ve yollarını kurar. */
require_once ABSPATH . 'wp-settings.php';
define( 'UPLOADS', 'wp-content/uploads' );
`
and added to myportfolio-form.php file
<?php
add_action( 'admin_footer', 'media_selector_print_scripts' );
function media_selector_print_scripts() {
$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );
?><script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>; // Set this
jQuery('#upload_image_button').on('click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
$( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );
$( '#image_attachment_id' ).val( attachment.id );
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery( 'a.add_media' ).on( 'click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script><?php
}
function portfolio_admin_myprojects_page_handler()
{
global $wpdb;
$table = new Portfolio_MyProjects_List_Table();
$table->prepare_items();
$message = '';
if ('delete' === $table->current_action()) {
$message = '<div class="updated below-h2" id="message"><p>' . sprintf(__('Items deleted: %d', 'portfolio-admin-myresume'), count($_REQUEST['ID'])) . '</p></div>';
}
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects_form');?>"><?php _e('Add new', 'portfolio-admin-myresume')?></a>
</h2>
<?php echo $message; ?>
<form id="myprojects-table" method="POST">
<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
<?php $table->display() ?>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_page_handler()
{
global $wpdb;
$table_name = $wpdb->prefix . 'portfolio_myprojects';
$message = '';
$notice = '';
$default = array(
'ID' => 0,
'projects_name' => '',
'projects_category' => '',
'projects_link' => '',
'projects_image' => '',
'order' => '',
);
if ( isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
$item = shortcode_atts($default, $_REQUEST);
$item_valid = portfolio_admin_validate_myprojects($item);
if ($item_valid === true) {
if ($item['ID'] == 0) {
$result = $wpdb->insert($table_name, $item);
$item['ID'] = $wpdb->insert_id;
if ($result) {
$message = __('Item was successfully saved', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while saving item', 'portfolio-admin-myresume');
}
} else {
$result = $wpdb->update($table_name, $item, array('ID' => $item['ID']));
if ($result) {
$message = __('Item was successfully updated', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while updating item', 'portfolio-admin-myresume');
}
}
} else {
$notice = $item_valid;
}
}
else {
$item = $default;
if (isset($_REQUEST['ID'])) {
$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $_REQUEST['ID']), ARRAY_A);
if (!$item) {
$item = $default;
$notice = __('Item not found', 'portfolio-admin-myresume');
}
}
}
add_meta_box('myprojects_form_meta_box', __('Work Details', 'portfolio-admin-myresume'), 'portfolio_admin_projects_form_meta_box_handler', 'myprojects', 'normal', 'default');
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects');?>"><?php _e('back to list', 'portfolio-admin-myresume')?></a>
</h2>
<?php if (!empty($notice)): ?>
<div id="notice" class="error"><p><?php echo $notice ?></p></div>
<?php endif;?>
<?php if (!empty($message)): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif;?>
<form id="form" method="POST">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<input type="hidden" name="ID" value="<?php echo $item['ID'] ?>"/>
<div class="metabox-holder" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<?php do_meta_boxes('myprojects', 'normal', $item); ?>
<input type="submit" value="<?php _e('Save', 'portfolio-admin-myresume')?>" id="submit" class="button-primary" name="submit">
</div>
</div>
</div>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_meta_box_handler($item)
{
// Save attachment ID
if ( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :
update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );
endif;
wp_enqueue_media();
?>
<tbody >
<div class="formdatabc">
<form >
<div class="form2bc">
<p>
<label for="projects_name"><?php _e('Project Name:', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_name" name="projects_name" type="text" value="<?php echo esc_attr($item['projects_name'])?>"
required>
</p>
</div>
<div class="form2bc">
<p>
<label for="projects_category"><?php _e('Project Category', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_category" name="skills_percent" type="text" value="<?php echo esc_attr($item['projects_category'])?>"
required>
</p>
</div>
<div class="form3bc">
</div>
<div>
<p>
<label for="projects_link"><?php _e('Project Link:', 'portfolio-admin-myresume')?></label>
<br>
<textarea id="projects_link" name="projects_link" cols="100" rows="3" maxlength="240"><?php echo esc_attr($item['projects_link'])?></textarea>
</p>
</div>
<div class='image-preview-wrapper'>
<img id='image-preview' src='' width='100' height='100' style='max-height: 100px; width: 100px;'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value=''>
</form>
</div>
</tbody>
<?php
}
`
i tried to iclude wordpress media selector to my plugin but it doesnt work.
error : Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
You need to change permissions of directories on server itself
chmod -R 777 /path/to/web-root/wp-content/uploads
(Linux example, this will change all files)
chmod 777 /path/to/web-root/wp-content
(this will change only directory itself, not all files)

foreach loop results to INSERT into database

I have three different div's that contain the checkout information.
Shipping info
Billing Info
Order confirmation
The shipping information and billing information is obtained by the customer entering that information in manually, but the order confirmation, that contains what they are ordering, the quantity, and pertinent information to that order resides there. That information is obtained from a foreach loop I have in place that displays the information based on the product's ID.
I am trying to figure out how I am going to INSERT the string that displays from my foreach loop into my database. I have an order report page that I want to display what was ordered.
For the shipping information, I validate it and then send my query in with that information. Like this...
<?php
if(Input::exists()) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'fullname' => array(
'required' => true,
'min' => 2,
'max' => 50
)
if($validation->passed()) {
if(isset($_POST['create'])){
$fullname = trim( $_POST['customer_name'] );
?>
<div class="field">
<label class="paddingleft" for="fullname">Full Name</label>
<div class="center"><input type="text" class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required></div>
</div>
The part that I am really confused with is how to INSERT the actual string this foreach loop displays. If the result of my foreach loop was:
2 balls
4 shoes.
I want that information to send in with my query.
This is how I have the Order confirmation section as of now..
<div class="checkoutconfirmationcontainer">
<?php foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
?>
<span class="tealmedium"><?php echo $product['quantity'] . " - " . $products[$product_id]['name'] . $message; ?></span><br><br><br>
<div class="floatleft"><div class="smallerimgcontainer">
<?php
$result = mysqli_query($con,"SELECT * FROM products");
if($row = mysqli_fetch_array($result)) {
$products[$row['product_id']] = $row;
if($row['image'] == ""){
echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
} else {
echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
}
echo "<br><br><br><br>";
}
?>
</div></div>
<div class="checkoutitemsummary">
<?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
<p><span class="redprice"><?php echo '$' . $products[$product_id]['price'] . "<br />"; }?></span></p>
</div>
How can I get the results of my foreach loop to be inserted into my database with my query?
Shopping Cart
<tr>
<th class="cartth">Name</th>
<th class="cartth">Price</th>
<th class="cartth">Category</th>
<th class="cartth">Quantity</th>
</tr>
<?php
$base_price = 0;
foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
$base_price += $products[$product_id]['price'] * $product['quantity'];
$shipping_price += $products[$product_id]['shippingprice'] * $product['quantity'];
?>
<tr>
<td class="carttd"><?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
</td>
<td class="carttd"><?php echo '$' . $products[$product_id]['price']; ?></td>
<td class="carttd"><?php echo $products[$product_id]['category']; ?></td>
<td class="carttd">
<?php echo "<input type='text' name='quantity[$product_id]' value='" . $product['quantity'] . "' />"; ?> </td>
</tr>
<?php
}
Javascript/Jquery that produces my div transition:
$('.checkoutmenu>li').on('click',function(e){
$('.checkoutprocess>.'+ e.target.classList[0]).show().siblings().hide();
});
<script>
$('.paymentinfocontainer').hide();
$('.confirmationinfocontainer').hide();
</script>
<script>
$('#button2').click(function () {
$(".checkoutprocess > div").hide();
$('.paymentinfocontainer').show("slow");
});
</script>
<script>
$('#button3 ').click(function () {
$(".checkoutprocess > div").hide();
$('.confirmationinfocontainer').show("slow");
});
</script>
<script>
/*
$('#button1').click(function () {
$(".checkoutprocess > div").hide();
$('.shippinginfocontainer').show("slow");
});
</script>
<script>
$('#button2 ').click(function () {
$(".checkoutprocess > div").hide();
$('.paymentinfocontainer').show("slow");
});
</script>
<script>
$('#button3 ').click(function () {
$(".checkoutprocess > div").hide();
$('.confirmationinfocontainer').show("slow");
});
*/
</script>
Ok, when I clicked on "3. Order Confirmation", I got the following HTML:
<div class="confirmationinfocontainer" style="display: block;">
<span class="summarytitle"><p>Order Confirmation</p></span>
<br>
<div class="floatrightinline">
<div class="confirmshippinginfo">
<p>Shipping to:</p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
</div>
<div class="checkoutconfirmationcontainer">
<div name="product_id"></div>
<span class="tealmedium">1 - Lakers Hat</span>
<br>
<br>
<br>
<div class="floatleft">
<div class="smallerimgcontainer">
<img alt="Coming Soon" src="/productpics/coming_soon.png" class="sizedimg">
<br>
<br>
<br>
<br>
</div>
</div>
<div class="checkoutitemsummary">
Lakers Hat
<p><span class="redprice">$25<br></span></p>
</div>
<input type="hidden" value="405bb6b2b562b4f00dac620d3f68620f" name="token">
<input type="submit" value="Place Your Order" class="widebutton">
<br>
</div>
</div>
So I see you're already making use of a hidden field. So when a users clicks the "Place Your Order" button, you want the details to be passed along. You can simply add these details back to the form via a hidden field. Like so:
<div class="checkoutconfirmationcontainer">
<?php
foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
?>
<input type="hidden" name="product_quantity[<?php echo $id; ?>]" value="<?php echo $product['quantity']; ?>" />
<span class="tealmedium"><?php echo $product['quantity'] . " - " . $products[$product_id]['name'] . $message; ?></span><br><br><br>
<div class="floatleft"><div class="smallerimgcontainer">
<?php
$result = mysqli_query($con,"SELECT * FROM products");
if($row = mysqli_fetch_array($result)) {
$products[$row['product_id']] = $row;
if($row['image'] == ""){
echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
} else {
echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
}
echo "<br><br><br><br>";
}
?>
</div></div>
<div class="checkoutitemsummary">
<?php echo "<a href='./viewProduct.php?view_product=$id'>{$product['name']} {$products[$product_id]['name']}</a>"; ?>
<p><span class="redprice"><?php echo '${$products[$product_id]['price']}<br />"; }?></span></p>
</div>
<input type="hidden" name="token" value="405bb6b2b562b4f00dac620d3f68620f">
<input class="widebutton" type="submit" value="Place Your Order">
<br />
</div>
Looking over this, I see no <form> for this. So I suspect JQuery is handling this somewhere else. So my fix may not really get read if your JQuery or app does not now what to look for, or does not hook onto that hidden field. If this is a framework that you're using or Catalog that you're modifying, check their support. I would say you have a lot more work ahead of you.

PHP /AJAX - Update the list at any time when in MySQL appears a new row

i am trying to make an ajax call to my database and refresh my list that i display from database. Actually what i need is, i have a table with data and i display them using php, now i want to update my list on the page without refresh anytime when in my table is inserting a new row.
sample code
foreach($_IL_QUERY_INTERNAL as $_IL_RESULT_DATA){
echo $_IL_RESULT_DATA->il_name; //display all the name from my table
}
For example:
In my table i have 5 names and you can see them on the page, now somene subit a form and i insert the sixth name in my table, and i want to update my list with the sith name as real time with no refreshing.
I will appreciate any help.
My complete code
<?php
session_start();
wp_enqueue_style('il_style_mode');
wp_enqueue_style('il_admin_style_mode');
wp_enqueue_scripts('jquery');
global $_IL_ID;
global $_IL_LIMIT;
global $_IL_TOTAL;
global $wpdb;
$_IL_TABLE_NAME_INTERNAL = $wpdb->prefix . "il_internal_transfer";
$_SESSION['IL_COUNT_ADMIN'] = 1;
require_once ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer_tabs.php");
$_IL_START = 0;
$_IL_LIMIT = 10;
if( isset($_GET['paged']) ){
$_IL_ID = $_GET['paged'];
$_IL_START = ($_IL_ID-1) * $_IL_LIMIT;
}
$_IL_QUERY_INTERNAL = $wpdb->get_results( "SELECT * FROM $_IL_TABLE_NAME_INTERNAL ORDER BY il_id DESC LIMIT $_IL_START, $_IL_LIMIT");
$_IL_NUM_ROWS_INTERNAL_ALL = $wpdb->get_var( "SELECT COUNT(*) FROM $_IL_TABLE_NAME_INTERNAL");
echo '<span class="il_admin_main_title">';
echo '<span>';
echo '<h2>Internal Transfers</h2>';
echo '</span>';
echo '<span>';
require_once ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer_sub_tabs.php");
echo '</span>';
echo '</span>';
echo '<span class="il_admin_transactions_block" id="il_admin_transactions_block">';
echo '<ul id="list">';
if( $_IL_NUM_ROWS_INTERNAL_ALL < 1 ){
include ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_include/il_messages/il_internal_transfer_sorry.php");
}else{
foreach($_IL_QUERY_INTERNAL as $_IL_RESULT_DATA)
{
?>
<span class="il_admin_transactions_block_raw_block">
<form method="post">
<input type='hidden' name='il_transaction_id' value="<?php echo $_IL_RESULT_DATA->il_id ?>" />
<span class="il_admin_transactions_block_raw">
<span class="il_admin_transactions_block_raw_count"><?php echo $_SESSION['IL_COUNT_ADMIN'] ?></span>
<span class="il_admin_internal_block_raw_full_name">
<?php echo $_IL_RESULT_DATA->il_name ?>
</span>
<span class="il_admin_internal_block_raw_from_to">
<span><?php echo $_IL_RESULT_DATA->il_from_mt4 ?></span> <?php echo $_IL_RESULT_DATA->il_from_mt4_currency ?>
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_gray_left_icon.png" class="il_arrow_between" />
<span><?php echo $_IL_RESULT_DATA->il_to_mt4 ?></span> <?php echo $_IL_RESULT_DATA->il_to_mt4_currency ?>
</span>
<span class="il_admin_internal_block_raw_email"><?php echo $_IL_RESULT_DATA->il_email ?></span>
<span class="il_admin_internal_block_raw_date"><?php echo $_IL_RESULT_DATA->il_date ?></span>
</span>
<span class="il_admin_transactions_block_raw_extras">
<?php if( $_IL_RESULT_DATA->il_comments === NULL || empty($_IL_RESULT_DATA->il_comments) ){ ?>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_comment">
<span>Comment:</span>
<span><?php echo $_IL_RESULT_DATA->il_comments ?></span>
</span>
<?php } ?>
<?php if( $_IL_RESULT_DATA->il_status == 'approved' ){ ?>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_extras_status_icon">
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_green_status_<?php echo $_IL_RESULT_DATA->il_status ?>_icon.gif" alt="Processing" title="Processing"/>
</span>
<?php } ?>
<span class="il_admin_transactions_block_raw_extras_ip">
The transaction was done from this ip <?php echo $_IL_RESULT_DATA->il_user_ip ?>
</span>
<span class="il_admin_transactions_block_raw_extras_ip_select">
<?php if( $_IL_RESULT_DATA->il_status == 'approved' ){ ?>
<span class="il_admin_transactions_block_raw_extras_status_<?php echo $_IL_RESULT_DATA->il_status ?>"><?php echo $_IL_RESULT_DATA->il_status ?></span>
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_green_status_<?php echo $_IL_RESULT_DATA->il_status ?>_icon.gif" alt="Processing" title="Processing" width="20"/>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_extras_update">
<select name="il_status_new">
<option>approved</option>
<option>waiting</option>
<option>rejected</option>
</select>
</span>
<span class="il_admin_transactions_block_raw_extras_update_button">
<input type="submit" name="il_status_update" value="update status" />
<input type="submit" name="il_delete" value="delete" class="il_admin_transactions_delete_button" />
</span>
<?php } ?>
</span>
</span>
<span class="il_clear"></span>
</form>
</span>
<?php
$_SESSION['IL_COUNT_ADMIN']++;
}
}
echo '</ul>';
echo '</span>';
if(isset($_POST['il_status_update'])){
$wpdb->update(
$_IL_TABLE_NAME_INTERNAL,
array(
'il_status' => $_POST['il_status_new'],
),
array( 'il_id' => $_POST['il_transaction_id'] ),
array(
'%s',
),
array( '%s' )
);
};
if(isset($_POST['il_delete'])){
$wpdb->delete( $_IL_TABLE_NAME_INTERNAL, array( 'il_id' => $_POST['il_transaction_id'] ), array( '%d' ) );
};
$_IL_ROWS_COUNT = mysql_num_rows(mysql_query("select * from $_IL_TABLE_NAME_INTERNAL"));
$_IL_TOTAL = ceil( $_IL_ROWS_COUNT / $_IL_LIMIT );
if($_IL_LIMIT < $_IL_ROWS_COUNT){
echo '<span class="il_pagination_block_admin">';
if( $_IL_ID > 1 )
{
echo "<a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".($_IL_ID-1)."' class='il_pagination_prev'><span class='il_pagination_prev_icon'></span></a>";
}
echo "<ul class='il_pagination'>";
for( $i = 1; $i <= $_IL_TOTAL; $i++ )
{
if( $i == $_IL_ID ) { echo "<li class='il_pagination_current'>".$i."</li>"; }
else { echo "<li><a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".$i."'>".$i."</a></li>"; }
}
echo "</ul>";
if( $_IL_ID != $_IL_TOTAL )
{
echo "<a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".( $_IL_ID + 1 )."' class='il_pagination_next'><span class='il_pagination_next_icon'></span></a>";
}
echo "</span>";
}else{
}
?>
<script>
jQuery( document ).ready(function($) {
function fetch(){
$.ajax({
url: '/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer.php',
success: function(data) {
$(data).hide().prependTo("#list").slideDown("slow");
if($("#list li").length > 15){
$('#list li:gt(14)').remove();
}
setTimeout("fetch()", 5000);
}
});
}
});
</script>
Use this JS code for live updating your result. Code will append new result at the top.
JS CODE
function fetch(){
$.ajax({
url: 'PATH-TO_FILE',
success: function(data) {
$(data).hide().prependTo("#list").slideDown("slow");
if($("#list li").length > 15){
$('#list li:gt(14)').remove();
}
setTimeout("fetch()", 5000);
}
});
}
HTML CODE
<ul id="list">
<?php
foreach($_IL_QUERY_INTERNAL as $_IL_RESULT_DATA){
echo $_IL_RESULT_DATA->il_name; //display all the name from my table
}
?>
</ul>

AJAX not updating the list from MySQL

i am inserting from a form data into my database, after i create a file with a FOR loop that i display all the records from my table. I am trying to refresh my list with data on a page without refresh every time when there was inserted new data into database.
main.php
<script type="text/javascript" >
function fetch(){
jQuery.ajax({
url: '/ajax.php',
success: function(data) {
jQuery(data).hide().prependTo("#list").slideDown("slow");
if(jQuery("#list li").length > 15){
jQuery('#list li:gt(14)').remove();
}
setTimeout("fetch()", 1000);
console.log(data);
}
});
}
</script>
PHP / HTML
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-blog-header.php");
session_start();
wp_enqueue_style('il_style_mode');
wp_enqueue_style('il_admin_style_mode');
wp_enqueue_scripts('jquery');
global $_IL_ID;
global $_IL_LIMIT;
global $_IL_TOTAL;
global $wpdb;
$_IL_TABLE_NAME_INTERNAL = $wpdb->prefix . "il_internal_transfer";
$_SESSION['IL_COUNT_ADMIN'] = 1;
require_once ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer_tabs.php");
$_IL_START = 0;
$_IL_LIMIT = 10;
if( isset($_GET['paged']) ){
$_IL_ID = $_GET['paged'];
$_IL_START = ($_IL_ID-1) * $_IL_LIMIT;
}
$_IL_QUERY_INTERNAL = $wpdb->get_results( "SELECT * FROM $_IL_TABLE_NAME_INTERNAL ORDER BY il_id DESC LIMIT $_IL_START, $_IL_LIMIT");
$_IL_NUM_ROWS_INTERNAL_ALL = $wpdb->get_var( "SELECT COUNT(*) FROM $_IL_TABLE_NAME_INTERNAL");
echo '<span class="il_admin_main_title">';
echo '<span>';
echo '<h2>Internal Transfers</h2>';
echo '</span>';
echo '<span>';
require_once ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer_sub_tabs.php");
echo '</span>';
echo '</span>';
echo '<span class="il_admin_transactions_block" id="il_admin_transactions_block">';
if( $_IL_NUM_ROWS_INTERNAL_ALL < 1 ){
include ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_include/il_messages/il_internal_transfer_sorry.php");
}else{
require_once ($_SERVER["DOCUMENT_ROOT"]."/ajax.php");
}
echo '</span>';
if(isset($_POST['il_status_update'])){
$wpdb->update(
$_IL_TABLE_NAME_INTERNAL,
array(
'il_status' => $_POST['il_status_new'],
),
array( 'il_id' => $_POST['il_transaction_id'] ),
array(
'%s',
),
array( '%s' )
);
};
if(isset($_POST['il_delete'])){
$wpdb->delete( $_IL_TABLE_NAME_INTERNAL, array( 'il_id' => $_POST['il_transaction_id'] ), array( '%d' ) );
};
$_IL_ROWS_COUNT = mysql_num_rows(mysql_query("select * from $_IL_TABLE_NAME_INTERNAL"));
$_IL_TOTAL = ceil( $_IL_ROWS_COUNT / $_IL_LIMIT );
if($_IL_LIMIT < $_IL_ROWS_COUNT){
echo '<span class="il_pagination_block_admin">';
if( $_IL_ID > 1 )
{
echo "<a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".($_IL_ID-1)."' class='il_pagination_prev'><span class='il_pagination_prev_icon'></span></a>";
}
echo "<ul class='il_pagination'>";
for( $i = 1; $i <= $_IL_TOTAL; $i++ )
{
if( $i == $_IL_ID ) { echo "<li class='il_pagination_current'>".$i."</li>"; }
else { echo "<li><a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".$i."'>".$i."</a></li>"; }
}
echo "</ul>";
if( $_IL_ID != $_IL_TOTAL )
{
echo "<a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".( $_IL_ID + 1 )."' class='il_pagination_next'><span class='il_pagination_next_icon'></span></a>";
}
echo "</span>";
}else{
}
?>
ajax.php
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-blog-header.php");
wp_enqueue_style('il_style_mode');
wp_enqueue_style('il_admin_style_mode');
wp_enqueue_scripts('jquery');
global $wpdb;
$_IL_TABLE_NAME_INTERNAL = $wpdb->prefix . "il_internal_transfer";
$_IL_QUERY_INTERNAL = $wpdb->get_results( "SELECT * FROM $_IL_TABLE_NAME_INTERNAL ORDER BY il_id DESC LIMIT $_IL_START, $_IL_LIMIT");
echo '<ul id="list">';
foreach($_IL_QUERY_INTERNAL as $_IL_RESULT_DATA)
{
?>
<li>
<span class="il_admin_transactions_block_raw_block">
<form method="post">
<input type='hidden' name='il_transaction_id' value="<?php echo $_IL_RESULT_DATA->il_id ?>" />
<span class="il_admin_transactions_block_raw">
<span class="il_admin_transactions_block_raw_count"><?php echo $_SESSION['IL_COUNT_ADMIN'] ?></span>
<span class="il_admin_internal_block_raw_full_name">
<?php echo $_IL_RESULT_DATA->il_name ?>
</span>
<span class="il_admin_internal_block_raw_from_to">
<span><?php echo $_IL_RESULT_DATA->il_from_mt4 ?></span> <?php echo $_IL_RESULT_DATA->il_from_mt4_currency ?>
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_gray_left_icon.png" class="il_arrow_between" />
<span><?php echo $_IL_RESULT_DATA->il_to_mt4 ?></span> <?php echo $_IL_RESULT_DATA->il_to_mt4_currency ?>
</span>
<span class="il_admin_internal_block_raw_email"><?php echo $_IL_RESULT_DATA->il_email ?></span>
<span class="il_admin_internal_block_raw_date"><?php echo $_IL_RESULT_DATA->il_date ?></span>
</span>
<span class="il_admin_transactions_block_raw_extras">
<?php if( $_IL_RESULT_DATA->il_comments === NULL || empty($_IL_RESULT_DATA->il_comments) ){ ?>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_comment">
<span>Comment:</span>
<span><?php echo $_IL_RESULT_DATA->il_comments ?></span>
</span>
<?php } ?>
<?php if( $_IL_RESULT_DATA->il_status == 'approved' ){ ?>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_extras_status_icon">
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_green_status_<?php echo $_IL_RESULT_DATA->il_status ?>_icon.gif" alt="Processing" title="Processing"/>
</span>
<?php } ?>
<span class="il_admin_transactions_block_raw_extras_ip">
The transaction was done from this ip <?php echo $_IL_RESULT_DATA->il_user_ip ?>
</span>
<span class="il_admin_transactions_block_raw_extras_ip_select">
<?php if( $_IL_RESULT_DATA->il_status == 'approved' ){ ?>
<span class="il_admin_transactions_block_raw_extras_status_<?php echo $_IL_RESULT_DATA->il_status ?>"><?php echo $_IL_RESULT_DATA->il_status ?></span>
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_green_status_<?php echo $_IL_RESULT_DATA->il_status ?>_icon.gif" alt="Processing" title="Processing" width="20"/>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_extras_update">
<select name="il_status_new">
<option>approved</option>
<option>waiting</option>
<option>rejected</option>
</select>
</span>
<span class="il_admin_transactions_block_raw_extras_update_button">
<input type="submit" name="il_status_update" value="update status" />
<input type="submit" name="il_delete" value="delete" class="il_admin_transactions_delete_button" />
</span>
<?php } ?>
</span>
</span>
<span class="il_clear"></span>
</form>
</span>
</li>
<?php
$_SESSION['IL_COUNT_ADMIN']++;
}
echo '</ul>';
actually what i am trying is every time when new data will be inserted in my table i want to display them automatically in my list using the loop from ajax.php

Codeigniter HMVC does not clear form fields

I am developing a site with CI 2.1.3
I have a blog module, in this blog I have a form to post a comment.
I am calling this form inside a view with:
echo Modules:: run('blog/comment');
When I submit this form with ajaxForm, the values of the input fields are not being cleared.
My controller’s function for the comment form:
public function comment($postId)
{
$this->load->helper('form');
$this->data['success'] = FALSE;
$this->data['postId'] = $postId;
if(!isset($_POST['comment_submit']))
{
$this->data['new_comment'] = $this->blog_comment_m->get_new();
}
else
{
$this->data['new_comment'] = $this->blog_comment_m->object_from_post(array('author', 'authur_email', 'content'));
$this->load->library('form_validation');
$rules = $this->blog_comment_m->rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == TRUE)
{
$this->data['success'] = TRUE;
$this->data['new_comment'] = $this->blog_comment_m->get_new();
}
}
$this->load->view('add_comment', $this->data);
}
The comment form:
<div id="commentAjax">
<?php $attr = array('id'=>'commentForm'); echo form_open(site_url('blog/comment/' .
$postId), $attr); ?>
<input type="hidden" name="post_id" value="<?php echo $postId; ?>" />
<div style="border-top:2px groove #930"><h4>Leave a Comment</h4></div>
<div class="control-group <?php if(form_error('author')) echo 'error'; ?>">
<label>Name *</label>
<?php echo form_input(array('name'=>'author', 'class'=>'input-large', 'value'=>set_value('author', $new_comment->author))); ?>
<span class="help-block"><?php echo form_error('author'); ?></span>
</div>
<div class="control-group <?php if(form_error('author_email')) echo 'error'; ?>">
<label>Email *</label>
<?php echo form_input(array('name'=>'author_email', 'class'=>'input-large', 'value'=>set_value('author_email', $new_comment->author_email))); ?>
<span class="help-block"><?php echo form_error('author_email'); ?></span>
</div>
<div class="control-group <?php if(form_error('content')) echo 'error'; ?>">
<label>Comment *</label>
<?php echo form_textarea(array('name'=>'content', 'value'=>set_value('content', $new_comment->content))); ?>
<span class="help-block"><?php echo form_error('content'); ?></span>
</div>
<div>
<?php echo form_submit('submit', 'Send Comment', 'class="btn btn-submit"');?>
<input type="hidden" name="comment_submit" value="1" />
</div>
<?php echo form_close(); ?>
<?php if($success): ?>
<div style="border:1px solid #666; background:#9F9; color:#000; margin-top:10px; width:50%; padding:5px; font-weight:bold">
<p>Thank you for your comment.</p>
<p>To avoid spam, your comment has been submitted for approval.</p>
<p><h2 class="highland">Highland Coffee Roastery</h2></p>
</div>
<?php endif; ?>
</div>
<script>
$(function()
{
var options = { target: '#commentAjax' };
$('#commentForm').ajaxForm(options);
});
</script>
I dumped the $new_comment array and the fields values are empty.
I checked the page source and the input fields values = ''.
Yet, I still see the values that I submitted in the input fields.
Refreshing the page, still, displays the values.
What is wrong?
I got the answer on the Daniweb forum:
Ok, the problem is that set_value() doesn’t consider if the validation runs true or false, usually you redirect() and so the POST array is resetted automatically, here we can force this action by extending /system/libraries/Form_validation.php, create /application/libraries/MY_Form_validation.php and paste this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_Form_validation extends CI_Form_validation {
public function __construct()
{
parent::__construct();
}
public function resetpostdata()
{
$obj =& _get_validation_object();
foreach($obj->_field_data as $key)
{
$this->_field_data[$key['field']]['postdata'] = NULL;
}
return true;
}
}
?>
After the validation runs true, call the method, as in this example:
if($this->form_validation->run() === FALSE)
{
# . . .
}
else
{
$this->form_validation->resetpostdata();
# load view & other stuff
}

Categories