Jump to content

PHP AJAX for auto load


asifmohammed1978

Recommended Posts

Hi, 

 

I have the below code and jquery in wordpress. I would like the form to auto submit, but at the moment I just get a 0 in the place of the heart icon. it seems to refresh but the form is not submitting the query.

 

Thank you in advance

 

<form id="lastviewer" class="ajax-form" action="<?php echo AJAX_URL; ?>" method="POST">

<?php if(ThemexUser::islastviewed(ThemexUser::$data['active_user']['ID'])) { ?>
  <a href="#" title="<?php _e('Remove from lastviewed', 'lovestory'); ?>" data-title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button current"></a>
  <input type="hidden" class="toggle" name="user_action" value="remove_lastviewed" data-value="add_lastviewed" />
<?php } else { ?>
  <a href="#" title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" data-title="<?php _e('Remove from Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button"></a>
  <input type="hidden" class="toggle" name="user_action" value="add_lastviewed" data-value="remove_lastviewed" />
<?php } ?>
<input type="hidden" name="user_lastviewed" value="<?php echo ThemexUser::$data['active_user']['ID']; ?>" />
<input type="hidden" class="nonce" value="<?php echo wp_create_nonce(THEMEX_PREFIX.'nonce'); ?>" />
<input type="hidden" class="action" value="<?php echo THEMEX_PREFIX; ?>update_user" />
</form>
      
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
 
                window.setInterval(function() {
                    AutoPost();
                }, 3000);
 
            }); 
 
            function AutoPost() {
          
                $.ajax({
                    type: "POST",
                    url: "<?php echo AJAX_URL; ?>",
            
                    success: function(data) {
                        $("#lastviewer").html(data) ;
                    }
 
                });
            }
 
        </script>
Link to comment
Share on other sites

function AutoPost() {
    $.ajax({
        type: "POST",
        url: "<?php echo AJAX_URL; ?>",
        data: $('#lastviewer').serialize(),
        success: function(data) {
            $("#lastviewer").html(data) ;
        }
    });
}

Post the updated code you're using now. Try code tags as it makes it easier to read. In general though as said, you were not specifying the data to send over. 

 

Also are you trying to put this code in the template file, wysiwyg editor, etc..?

Link to comment
Share on other sites

Hi, Thank you. See below. I'm doing the changes in the php file directly.

 

<form id="lastviewer" class="ajax-form" action="<?php echo AJAX_URL; ?>" method="POST">

<?php if(ThemexUser::islastviewed(ThemexUser::$data['active_user']['ID'])) { ?>
  <a href="#" title="<?php _e('Remove from lastviewed', 'lovestory'); ?>" data-title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button current"></a>
  <input type="hidden" class="toggle" name="user_action" value="remove_lastviewed" data-value="add_lastviewed" />
<?php } else { ?>
  <a href="#" title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" data-title="<?php _e('Remove from Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button"></a>
  <input type="hidden" class="toggle" name="user_action" value="add_lastviewed" data-value="remove_lastviewed" />
<?php } ?>
<input type="hidden" name="user_lastviewed" value="<?php echo ThemexUser::$data['active_user']['ID']; ?>" />
<input type="hidden" class="nonce" value="<?php echo wp_create_nonce(THEMEX_PREFIX.'nonce'); ?>" />
<input type="hidden" class="action" value="<?php echo THEMEX_PREFIX; ?>update_user" />
</form>
      
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
 
                window.setInterval(function() {
                    AutoPost();
                }, 3000);
 
            }); 
 
            function AutoPost() {
          
                $.ajax({
                    type: "POST",
                    url: "<?php echo AJAX_URL; ?>",
            data: $('#lastviewer').serialize()
                    success: function(data) {
                        $("#lastviewer").html(data) ;
                    }
 
                });
            }
 
        </script>
Link to comment
Share on other sites

You've got a syntax error and a couple logical errors in the code you've posted. Here's an example of what I think you're trying to do:

function AutoPost() {
	$.ajax({
		type: "POST",
		url: "<?php echo AJAX_URL; ?>",
		data:$('#lastviewer').serialize(),
	}).done(function(data) {
		if(data.success == true){
			$("#lastviewer").html(data.processed) ;
		}else{
			$('#lastviewer').html('<p>Sorry, there was an error</p>');
		}
	}).fail(function(jqXHR, status){
		$('#lastviewer').html('<p>Server error: ' + status + '</p>');
	});
}

<?php
function doAjax($data){
	$rnd = rand(0,2);
	if($rnd == 0 || $ret == 2){
		$ret['success'] = true;
		$ret['processed'] = 'This is your data after processing';
	}else{
		$ret['success'] = false;
	}
	print(json_encode($ret));
	die();
}
?>

Obviously I'm skipping any actual processing and just checking a random number, but other than that...

 

First off, your success() callback was improperly placed inside the AJAX object as opposed to chained to it. It's also been deprecated, so I've replaced it with the done() callback. Now, the done() callback will fire regardless the outcome of the php processing - as long as the AJAX object receives any legitimate return value(s), AJAX considers that success. So add a 'success' index to the return array that gets set to true if the php processes successfully or false if it doesn't, and check that in the done() callback before any processing takes place. Along those lines, you're going to want to check for server errors as well - that's where the fail() callback comes in.

 

Using WordPress, your AJAX_URL constant is going to be a set path that resolves to

/whatever_your_content_path_is/wp-admin/admin-ajax.php

so don't set that as the action parameter of your form. WordPress will use the contents of the hidden 'action' field in your form to know what php function to call, as long as you've added the following lines in your functions.php file (assuming THEMEX_PREFIX is 'mine_'):

add_action('wp_ajax_mine_update_user', 'doAjax');

WordPress uses a front-end pattern approach, so everything is going to go through index.php - just leave the action parameter of your form empty.

 

That will hopefully get you pointed in the right direction and makes any sense at all and is close to what you were looking for...

Edited by maxxd
Link to comment
Share on other sites

One thing I'm not sure of...is why you replace the contents of #lastviewer (the form), with the result of your ajax upon ajax completion (success event). Is the result from ajax the same form again? Because the ajax is sending the form data over and over every 3 seconds, but then you're replacing the contents of the form so it might not work on subsequent ajax calls unless the response from your ajax IS the form HTML again.

Edited by CroNiX
Link to comment
Share on other sites

Hi All,

 

Apologies for the delayed response, so maybe I need to go back to basics. I have a WP theme that allows a user to click a heart icon and that triggers an update into the MySQL DB. 

 

However what I want to do is remove the user having to click so the MYSQL DB is updated automatically. The update only needs to take place once after 3 seconds and never again, additionally I don't need it remove the update as the current functionality does.

 

As you can see I'm seriously basic in my coding skills, hopefully the above and below makes it easier to help me.

 

Thank you in advance, being really cheeky, full code snippets would be great so I can copy paste but also learn so I don't bug anyone again.

 

author.php page code:--------------------------------------------

<form class="ajax-form" action="<?php echo AJAX_URL; ?>" method="POST">

<?php if(ThemexUser::islastviewed(ThemexUser::$data['active_user']['ID'])) { ?>
  <a href="#" title="<?php _e('Remove from lastviewed', 'lovestory'); ?>" data-title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button current"></a>
  <input type="hidden" class="toggle" name="user_action" value="remove_lastviewed" data-value="add_lastviewed" />
<?php } else { ?>
  <a href="#" title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" data-title="<?php _e('Remove from Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button"></a>
  <input type="hidden" class="toggle" name="user_action" value="add_lastviewed" data-value="remove_lastviewed" />
<?php } ?>
<input type="hidden" name="user_lastviewed" value="<?php echo ThemexUser::$data['active_user']['ID']; ?>" />
<input type="hidden" class="nonce" value="<?php echo wp_create_nonce(THEMEX_PREFIX.'nonce'); ?>" />
<input type="hidden" class="action" value="<?php echo THEMEX_PREFIX; ?>update_user" />
</form>
 
themex.user.php: --------------------------------------------
 
public static function getUser($ID, $extended=false) {
$data=get_userdata($ID);
if($data!=false) {
$user['login']=$data->user_login;
$user['email']=$data->user_email;
}
$user['ID']=$ID;
$user['status']=self::getStatus($ID);
$user['profile']=self::getProfile($ID);
if($extended) {
$user['lastviewed']=themex_keys(ThemexCore::getUserMeta($ID, 'lastviewed', array()));
}
return $user;
}
 
public static function updateUser() {
$data=$_POST;
if(isset($_POST['data'])) {
parse_str($_POST['data'], $data);
$data['nonce']=$_POST['nonce'];
check_ajax_referer(THEMEX_PREFIX.'nonce', 'nonce');
self::refresh();
}
if(isset($data['user_action']) && wp_verify_nonce($data['nonce'], THEMEX_PREFIX.'nonce')) {
$redirect=false;
switch(sanitize_title($data['user_action'])) {
case 'register_user':
self::registerUser($data);
break;
case 'login_user':
self::loginUser($data);
break;
case 'reset_password':
self::resetPassword($data);
break;
case 'update_profile':
self::updateProfile(self::$data['user']['ID'], $data);
break;
case 'add_lastviewed':
self::addlastviewed(self::$data['user']['ID'], $data['user_lastviewed']);
break;
case 'remove_lastviewed':
self::removelastviewed(self::$data['user']['ID'], $data['user_lastviewed']);
$redirect=true;
break;
case 'update_settings':
self::updateSettings(self::$data['user']['ID'], $data);
break;
case 'update_status':
self::updateStatus(self::$data['user']['ID']);
break;
}
 
if($redirect) {
wp_redirect(themex_url());
exit();
}
}
}
/** Checks user last viewed */
public static function islastviewed($ID) {
if(isset(self::$data['user']['lastviewed'][$ID])) {
return true;
}
 
return false;
}
/** Adds user lastviewed    */
public static function addlastviewed($ID, $user) {
if(!isset(self::$data['user']['lastviewed'][$user])) {
array_unshift(self::$data['user']['lastviewed'], array(
'ID' => "$ID",
'date' => current_time('timestamp'),
));
 
ThemexCore::updateUserMeta($user, 'lastviewed', self::$data['user']['lastviewed']);
}
}
 
/** Removes user last viewed  */
public static function removelastviewed($ID, $user) {
if(isset(self::$data['user']['lastviewed'][$user])) {
unset(self::$data['user']['lastviewed'][$user]);
ThemexCore::updateUserMeta($ID, 'lastviewed', self::$data['user']['lastviewed']);
}
}
 
/** Gets user settings */
public static function getSettings($ID) {
$settings=ThemexCore::getUserMeta($ID, 'settings', array(
'favorites' => ThemexCore::getOption('user_settings_favorites', 1),
'lastviewed' => ThemexCore::getOption('user_settings_lastviewed', 1),
'photos' => ThemexCore::getOption('user_settings_photos', 1),
'gifts' => ThemexCore::getOption('user_settings_gifts', 1),
'notices' => 1,
));
 
return $settings;
}
 
/** Updates user settings */
public static function updateSettings($ID, $data) {
 
$settings=array();
 
 
//lastviewed
if(isset($data['user_lastviewed'])) {
$settings['lastviewed']=intval($data['user_lastviewed']);
}
 
 
//password
if(isset($data['user_password']) && !empty($data['user_password'])) {
if(strlen($data['user_password'])<4) {
ThemexInterface::$messages[]=__('Password must be at least 4 characters long', 'lovestory');
} else if(strlen($data['user_password'])>16) {
ThemexInterface::$messages[]=__('Password must be not more than 16 characters long', 'lovestory');
} else if(preg_match("/^([a-zA-Z0-9]{1,20})$/", $data['user_password'])==0) {
ThemexInterface::$messages[]=__('Password contains invalid characters', 'lovestory');
} else if($data['user_password']!=$data['user_password_repeat']) {
ThemexInterface::$messages[]=__('Passwords do not match', 'lovestory');
} else {
wp_set_password($data['user_password'], $ID);
wp_set_auth_cookie($ID, true);
ThemexInterface::$messages[]=__('Password has been successfully changed', 'lovestory');
$_POST['success']=true;
}
}
 
ThemexCore::updateUserMeta($ID, 'settings', $settings);
self::$data['user']['settings']=self::getSettings($ID);
 
if(empty(ThemexInterface::$messages)) {
ThemexInterface::$messages[]=__('Settings have been successfully saved', 'lovestory');
$_POST['success']=true;
}
}
 
jquery.interface.js: --------------------------------------------
 
var themeElements = {
 
submitButton: '.submit-button',
ajaxForm: '.ajax-form',
 
}
 
//AJAX Form
$(themeElements.ajaxForm).each(function() {
var form=$(this);
 
form.submit(function() {
var message=form.find('.message'),
loader=form.find('.loader'),
toggle=form.find('.toggle'),
button=form.find(themeElements.submitButton),
title=form.find(themeElements.submitButton).data('title');
 
var data={
action: form.find('.action').val(),
nonce: form.find('.nonce').val(),
data: form.serialize()
}
 
loader.show();
button.addClass('disabled').toggleClass('current');
 
if(!message.hasClass('static')) {
message.slideUp(300, function() {
$(themeElements.colorboxLink).colorbox.resize();
});
}
 
jQuery.post(form.attr('action'), data, function(response) {
if(jQuery('.redirect', response).length) {
if(jQuery('.redirect', response).attr('href')) {
window.location.href=jQuery('.redirect',response).attr('href');
} else {
window.location.reload();
}
 
message.remove();
}
 
if(title) {
button.data('title', button.attr('title'));
button.attr('title', title);
}
 
toggle.each(function() {
var value=toggle.val();
toggle.val(toggle.data('value'));
toggle.data('value', value);
});
 
loader.hide();
button.removeClass('disabled');
 
if(response!='' &&  response!='0' && response!='-1') {
if(message.hasClass('popup')) {
$.colorbox({html:'<div class="popup">'+response+'</div>'});
} else if(message.hasClass('static')) {
message.append(response);
} else {
message.html(response).slideDown(300, function() {
$(themeElements.colorboxLink).colorbox.resize();
});
}
}
 
form.find('.temporary').val('');
form.find('.scroll').each(function() {
$(this).scrollTop($(this)[0].scrollHeight);
});
});
 
return false;
});
});
 
//Submit Button
$(themeElements.submitButton).not('.disabled').click(function() {
var form=$($(this).attr('href'));
 
if(!form.length || !form.is('form')) {
form=$(this).parent();
while(!form.is('form')) {
form=form.parent();
}
}
 
form.submit();
return false;
});
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.