AJAX Wordpress Insert - php

I have a complete/completed button on a custom post type page.
And It works, When someone clicks the button it sends the right data to the db and adds marks it complete but I want to conver this to ajax but the button itself doesn't send any data. I send the post type and the user id to the server based on the post they are on. And I am trying to figure this out.
In single.php
<form action='' method="post" class='comp-btn'>
<input class='workout-submit' id="workout-submit"type='submit' name='complete' value='Complete'/>
</form>
This is the post req
//Inserts row into database
if (isset($_POST['complete'])):
$wpdb->insert('wp_completed_workouts',
array(
userID => $current_userID,
postID => $current_postID,
)
);
endif;
TLDR: I have this post request (that works)I would like to turn into an AJAX call. Cause I don't want it to reload every time someone hits the complete button.

Since you are using Wordpress, AJAX works best in sending data to functions.php.
First, in your html/js file:
$('.comp-btn').on('submit', function(){
$.ajax({
type: 'POST',
url: "../../../../wp-admin/admin-ajax.php",
data: {'action':'sendworkout','complete':$('.workout-submit').val()},
success: function(response){
console.log(response); // shows 'success'
// do things here
}
});
});
Second, in your WP functions.php
add_action('wp_ajax_sendworkout', 'sendworkout');
add_action('wp_ajax_nopriv_sendworkout', 'sendworkout');
function sendworkout(){
$workoutcomplete = $_POST['complete'];
if($workoutcomplete){
//DB insert here
}
wp_send_json_success('success');
}
Note that the 'action' in ajax syntax is referring to the function name in your functions.php, and the 'complete' refers to the $_POST['complete'] in your functions.php

Related

Save and display values of multiple checkboxes in WordPress

I am trying to save the value of multiple checkboxes in WordPress, So if a guest checks a checkbox (front-end) without clicking any submit buttons, this checked value will be stored in the database.
Next time anyone loads this page, this particular checkbox should be pre-checked.
So far I have got this code in the template file that is responsible for the content of the page I am trying to add these checkboxes to.
(This is no regular WP post/page template but a "collection page" generated by a WooCommerce collection plugin):
//submit code
if(isset($_POST['cadeau']) ){
$data=serialize($_POST['cadeau']);
update_post_meta($post_id, 'cadeau', $data);
}
//edit code
$data=get_post_meta($post_id, 'cadeau');
//$data=unserialize($data[0]);
$data=$data[0];
print_r($data);?>
<input type="checkbox" name="cadeau[]" value="<?php echo $product_id;?>" <?php if(in_array($product_id,$data) ){echo "checked";} ?> >
This is not working however.. Am I on the right track? Or am I doing it completely wrong?
Basically, to make such things in WordPress (and not only) you have to make a POST request to the server. Either by submitting a form or doing an AJAX request. Here is an example of how to make it to work. If you don't want to make AJAX request just skip step 1 and jump directly to step 3 and have a look at the function. I am sure it will help you go on the right track.
1. Create a JS script which sends an AJAX request to admin-ajax.php file:
<script>
jQuery("#submit-button").on("click", function(){
var checkboxValue = jQuery("#your-checkbox").is(":checked") ? 1 : 0;
jQuery.ajax({
url: "http://www.yourdomain.com/admin-ajax.php",
method: 'POST',
data: {action: "save_checkbox", checked: checkboxValue}
}).done(function(response){
console.log("Response: " + response);
//NOTE that 'action' MUST be the same as PHP function name you want to fire
//you can do whatever you want here with your response
}).fail(function(error){
console.log(error);
});
})
</script>
2. Create new file e.x. myajax.php and include it to functions.php
3. Now write a function you want to fire on click, e.x.:
function save_checkbox(){
$checkboxValue = $_REQUEST['checked'];
update_post_meta($coll_id, 'cadeau', $checkboxValue );
$response = array(
"status" => "ok",
"message" => "Post meta saved",
);
$response = json_encode($response);
echo $response;
die();
}
add_action( 'wp_ajax_save_checkbox', 'save_checkbox' );
That's all. As I said note that actionhas to be the same as PHP function. If you want to have some response from your PHP function just echo it and this is what you will get as a response. If you'll get 0 as a response it means that function you want to fire does not exists or you didn't call die() at the end of your function. I hope I could help.

After getting value from javascript redirect to another page in codeigniter with url parameters

I am making a simple auto search, where when user after searching, the search results get displayed on the dropdown box. If he clicks to any of the search items, it will take the user to another page where more details will be shown regarding that item.
So as, if he clicks on "Discrete Maths", then the new page url will be
localhost/example/search?s=discrete+maths
and the details will be shown regarding that topic
My javascript code :
function searchclick(subid,subjct){
//subid is subject id and subjct is subject name
var search_var = {
action : "gosearch",
subid : subid,
subjct : subjct
};
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>search",
cache : false,
data : search_var,
success : function(r)
{
}
});
}
I have a controller called Search which loads the view known as search.
I want to pass those data to that controller which will then redirect to the Search view with the url like this --> localhost/example/search?s=discrete+maths as well as the title of the page will change to the name of the item searched.
I can't figure out a way. I'm new to codeigniter.
I just want to redirect to that view after getting the data and change the url parameters. Nothing else. Only this will be helpful.
After sending data to controller in controller do whatever you need to do and redirect directly to desired URL:
public function search() {
/* your code */
header("Location: http://www.example.com/");
}
If you need to send back some data to front end you can send new URL to JS on front end and redirect there:
// controller
public function search() {
/* your code */
$arr = array('redirect' => 'http://example.com/', 'other_data' => 1);
header('Content-Type: application/json');
echo json_encode( $arr );
}
// javascript
success : function(response){
window.location.replace(response['redirect'])
},
This is not codeigniter specific information. This is general AJAX method.

ng-repeat behaviour with $watch

I am newbie to AngularJs. I am using AngularJS as front end and Laravel As backend.
I have a situation where I want page to be refreshed on ajax success (when user post data).
I have template index.blade.php like this :
#extends(layout)
#section
header page
post page
main page
footer page
#endsection
Now thing is that User is posting update from post page and
on that success i want data to be refreshed which is on main page
function addpost ($scope, $http){
$scope.loadData = function(){
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.post( baseurl+"alldata").success(function(data)
{
$scope.posts = data;
});
}
$scope.addComment = function(post){
if("undefined" != post.hoot){
// Angular AJAX call
$http({
method : "POST",
url :baseurl+ "url",
data : "post="+post
}).success(function(data){
$scope.posts = data;//json response
// here i want page to be refreshed or div refresh of sub-main page
});`
$scope.post = ' ';`
}
}
$scope.loadData();
}`
Now thing is that if i am posting data from other sub page and then showing it on other sub page. Iam calling addcomment to add posted data in model and then loaddata() to get all data from model for ng-repeat in a view.
if i am going to fire watch event . it will keep on refreshing model thus view data. Suppose i am working on comment section where we can like , dislike and comment on post. and i want to use ng-click event inside ng-repeat(which is refreshing view).
Test.controller('Testing',['$scope', '$http', function($scope,$http){
$scope.products = {};
$http.post( baseurl+"ajax/getall").success(function(data)
{
$scope.products = data;
});
$scope.$watch("products", function(newValue, oldValue) {
if (newValue === oldValue) { return; } // AKA first run
$scope.products= newValue;
});
});
$scope.Hello= function(){
alert("hello");
}
}]);
It will keep on refreshing page and thus don't click event inside ng-repeat which is ng-click.
I have fired ng-click="Hello()" event but it doesn't fire.
You can register a listener to $scope.data in any part of the application that had a reference to scope. This way, everything will keep up to date when data is updated.
Like so:
$scope.$watch('data', callback)
You are thinking the jQuery way. You have to put that away and think data-binding and angularjs.
To do what you are asking is pretty easy if you think the angularjs way.
First of all, you need the php page of yours to print out a html page with a {{updateMe}}
then in your code
.success(function(data){
$scope.updateMe = data
......

PHP Submit form and get xml generated on the page

Here is what I need to do:
submit post form with some hidden fields
on the 'action' page xlm is generated
get the xml generated there using php
and then I will parce xml in order to get some info.
I tried to do it using $.post function but I cannot get the xml somewhy.
$.post(
'https://..',
{
method : 'result',
payee_id : \"{$obj->payee_id}\",
login : \"{$obj->login}\",
password : \"{$obj->password}\",
shop_order_number : \"{$obj->shopOrderNumber}\",
status : 'PAYED',
},
function (data) {
alert(data);
}
);
and this code doesn't work.
you can use:
$("#myForm").ajaxSubmit({url: 'my_script.php', type: 'post'})
OR
$("#myForm").ajaxForm({url: 'my_script.php', type: 'post'})
To submit AJAX forms using jQuery.
Hope this would solve the form POSTing problem you got.

How does AJAX handle multiples instances of a variable?

I am currently editing a WordPress plugin, which allows you to filter posts by category, once a category is selected, the posts for that caregory are displayed as a checklist on the widget, the user can select the posts they wish to display in their sidebar/widget area of the theme.
I have taken the widget to the point that the user can select their post, the widget allows a single post to be selected, however if more than one is selected and the save button is pressed, the form returns only the last slected post.
After some searching, I have found the problem to be on the form return.
It is either to do with the update, or the way AJAX handles multiple instances of a variable.
the information posted to the server is as follows:
action save-widget
add_new
id_base single_post_super_widget
multi_number
savewidgets 9bc3d79f1c
sidebar lcp-sb
widget-height 200
widget-id single_post_super_widget-2
widget-single_post_super_widget[2][object_to_use] 5005
widget-single_post_super_widget[2][object_to_use] 4892
widget-single_post_super_widget[2][object_to_use] 4607
widget-single_post_super_widget[2][object_type] 72
widget-single_post_super_widget[2][paged] 1
widget-single_post_super_widget[2][tab] all
widget-single_post_super_widget[2][title_override]
widget-width 400
widget_number 2
Where object_to_use is the post(s) being selected.
the information being sent is defined here:
var theArgs = {
action: jQuery('input.widget_class:hidden', widgetDiv).first().val() + '-get-metabox',
widget: widgetDivId,
number: widgetNumber,
blog_id: jQuery(widgetInputBase + 'blog_id').val(),
object_type: jQuery(widgetInputBase + 'object_type').val(),
tab: currentTab,
paged: currentPage,
object_to_use: jQuery('input[type=checkbox][name$="[object_to_use]['+currentTab+']"]:checked', widgetDiv).first().val(),
title_override: jQuery(widgetInputBase + 'title_override').val(),
excerpt_override: jQuery(widgetInputBase + 'excerpt_override').val(),
searched: ('search' == currentTab) ? jQuery('input.quick-search', widgetDiv).first().val() : ''
};
and the jQuery.post action:
jQuery.post(
ajaxurl,
theArgs,
function( r ) {
jQuery('.ajax-feedback').css('visibility', 'hidden');
if ( r && r.length > 2 ) {
jQuery('div.widget-content', widgetDiv).html(r);
}
}
);
In relation to the question, widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this? Does each post/variable have to be unique?
widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this?
There is nothing Ajax specific about this. You just get multiple copies of the key in the data submitted to the server.
Does each post/variable have to be unique?
No.
In most server side environments, you can get all the data just by using the right function. For example with Perl's CGI.pm module, you just get the parameter in list context:
my #thing = $cgi->param('widget-single_post_super_widget[2][object_to_use]');
… and it will 'just work'.
PHP is special. If the name ends in [] then it will just create an array in $_POST and friends. If it doesn't, then it will discard all but the last item. (Unless I'm misremembering and it keeps the first instead).
You can use ajax using jQuery.. then you can pass multiple instances of variable :-
like this :-
if(roleId !='' && roleId != '16'){
jQuery('#user_id_div').hide();
jQuery('#loading_image').show().html("<label> </label> <img src='<?php echo $this->webroot; ?>img/ajax-loader.gif' alt='Loading...'>");
urlData = "<?php echo Router::url(array('controller' => 'users', 'action' => 'getmultipleVendors')) ?>" ;
postData = "vendorType=" + roleId;
jQuery.ajax({
url: urlData,
data: postData,
success: function(data) {
jQuery('#PromoCodeUserId').html(data);
jQuery('#user_id_div').show();
jQuery('#loading_image').hide();
}
});
in postdata field you can post many data as avariables..

Categories