How does AJAX handle multiples instances of a variable? - php

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..

Related

AJAX Wordpress Insert

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

Display hidden div if no more data found

So currently I'm searching for 10 new posts and the Ajax searches in the same page from the page and I use $_GET['limits'] in my PHP query to scan the server for all requested data.
So what I'd like to do is if there is no new data to show the 'No More Posts' Div. I tried using t.length===0 with no luck, now I don't know if its because t isn't an array or whether I put it in the wrong place in my success.
var streams_stream_count=10;
function streams_stream_load(targetID){
$('#loadmorestreamoneajaxloadertarget').show();
$.ajax({
method: 'get',
url : 'stream2.php?limits='+streams_stream_count+'&targetID='+targetID,
dataType : 'text',
success: function (t) {
$('#streams_stream_container').fadeIn('slow').html(t);
$(document).scroll(function(){
if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
streams_stream_count+=10;streams_stream_load(targetID);
}
});
},
complete: function(){
$('#loadmorestreamoneajaxloadertarget').hide();
}
});
}
And my hidden div to show if no new data.
<div id='nomoreposts' style='display:none;'>No more Posts</div>
UPDATE
I use $sqlLimit=mysqli_real_escape_string($mysqli,$_GET['limit'])
$call="SELECT * FROM streamdata ORDER BY streamitem_timestamp DESC LIMIT $sqlLimit";
You can also do like this :- Write code in backend (PHP function) and return html if no data found "No more Posts", also send one parameter true/false. On the bases of the parameter show html in your fronted.

Autopopulate textarea from database based on dropdown selection

I am trying to autopopulate a textarea with values from a (wordpress) database based on the value selected in a select menu. Basically the select menu contains a list of teams and I wish to populate my textarea with names of the players from the selected team.
The problem is that I need to convert the selected text to a php variable in order to use it to query the database. Like so:
PHP
$usergroups = $mingleforum->get_usergroups();
$team_title = $_GET['usergroup'];
$team_id = get_page_by_title( $team_title );
$players = get_users( array (
'meta_key' => 'team-meta',
'meta_value' => $team_id
));
JS
jQuery(function(jQuery){
jQuery('#usergroup').change(function() {
jQuery.ajax({
type: "GET",
url: "http://localhost:8888/dev_wordpress/wp-admin/admin.php?page=mfgroups&mingleforum_action=usergroups&do=add_user_togroup",
data: { usergroup: jQuery(this).find(':selected').text() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
UPDATE: corrected the url (based on #jterry 's comment) and no longer getting error (although it still isn't working)
I am getting the following error:
GET http://localhost:8888/dev_wordpress/wp-admin/wpf-addusers.php?usergroup=Coq+and+Bulldog 404 (Not Found)
For the points! :D
wpf-addusers.php doesn't exist at that path. Specify the absolute URI and you'll at least make it past the 404 error. Also, it looks like your url parameter has "" on both sides of the variable - you just need one on each side.
EDIT
To access the variable you're looking for (usergroup) to use in your PHP script, you can use $_GET['usergroup']. From there, you can use it as you see fit or insert it as the value of an input element.
If you use the value in an input element, be sure to use htmlentities to properly escape the value.

JQuery PHP AJAX filter based on multiple checkbox array

I'm hoping someone can point me in the right direction. I'm primarily a PHP developer but I'm really trying to get my head around jquery and javascript more due to the increasing number of AJAX work requests we receive.
Basically I have a sidebar filter that works fine. It is based on 3 things. A group, category and sub category. So for example, Boots as the category, Leather (type) as a sub category and Black (colour) as tertiary filter. At the moment it works based on a GET form. However I want to use live filters instead so as they click a checkbox, it updates the results based on a query. I can write all the PHP for this but I'm struggling to get the data together by jQuery. I've looked at using jQuery .each and .change.
There are 3 groups of checkboxes and they are all based on arrays. So for example again: category[], subcategory[], tertiary[].
Thanks in advance for the help.
Some example HTML
<input id="$ProdCatLabel" class="side_filter_checkbox" name="ProdCatFil[]" type="checkbox" value="$ProdCat">
<input id="$ProdSubCatLabel" class="side_filter_checkbox" name="ProdSubCatFil[]" type="checkbox" value="$ProdSubCat">
<input id="$BrandingLabel" class="side_filter_checkbox" name="BrandFil[]" type="checkbox" value="$Branding">
My attempts:
var prodcats = $('side_filter_prodcats[name="ProdCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
var prodsubcats = $('side_filter_prodsubcats[name="ProdSubCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "[ENTER PHP URL HERE]",
data: "ProdCats=" + prodcats + "ProdSubCats=" + prodsubcats,
success: function(msg) { $(".content_area").html(msg); }
});
Am I barking up the right tree here?
Ok let's say your checkboxes have the classes category, subcategory and tertiary. You could attach a click event handler to each group that calls the function to load in the correct data, passing the checkbox value and a class or data-attribute to the function as parameters.
// Your main DOM ready function
$(document).ready(function() {
// Checkboxes click function
$('input[type="checkbox"]').on('click',function(){
// Here we check which boxes in the same group have been selected
// Get the current group from the class
var group = $(this).attr("class");
var checked = [];
// Loop through the checked checkboxes in the same group
// and add their values to an array
$('input[type="checkbox"].' + group + ':checked').each(function(){
checked.push($(this).val());
});
refreshData(checked, group);
});
function refreshData($values, $group){
// Your $values variable is the array of checkbox values
// ie. "boot", "shoe" etc
// Your $group variable is the checkbox group
// ie. "category" or "subcategory" etc.
// Now we can perform an ajax call to post these variable to your php
// script and display the returned data
$.post("/path/to/data.php", { cats: $values, type: $group }, function(data){
// Maybe output the returned data to a div
$('div#result').html(data);
});
}
});
Here's an example of the checkbox click function in action: http://jsfiddle.net/F29Mv/1/

Dynamically change dropdowns via SQL and calculate sums?

I've got a row in a table with 3 fields laid out as so:
Job Pay Grade Cost
<Select> <Select> <Calculation>
I've got an SQL table with the information above in it, for example:
Job Pay Grade Cost
Techie 1 100
Techie 2 200
Engi 2 300
Engi 3 400
Engi 4 500
What I need to do is to be able to select a Job from the dropdown and then the Pay Grade select box will change depending on what matches that job in the SQL database. It will then show the cost which relates to the to selected.
How can I go about this as I am a little stuck
First create ajax request when a job title is selected. WIthin the success callback of the request will generate html for the options for pay grade select from JSON response from server
jQuery
$('select.jobTitle').change(function(){
var $titleSelect=$(this);
$.getJSON('processJobGrades.php', { jobTitle : $(this).val() }, function(response){
var gradesOptionsHtml='';
/* create options html from json response */
$.each( response, function(i, item){
gradesOptionsHtml+='<option value="'+item.grade+' data-cost="'+item.cost+'">'+item.grade+'</option>';
});
$titleSelect.parent().find('select.jobGrade').html(gradesOptionsHtml);
});
});
IN processJobGrades.php receive $_GET['jobTitle'] . Do DB lookup and create json to send back.
PHP
$outputArray=array();
/*in loop over DB data:*/
$outputArray[]= array( 'grade'=>$row['grade'], 'cost'=>$row['cost']);
/*Output final array as JSON*/
echo json_encode( $outputArray);
jQuery change handler for paygrade select to get cost
$('select.jobGrade').change(function(){
var cost=$(this).find(':selected').data('cost')
$(this).parent().find('input.jobCost').val( cost);
})
You need to post the select job via $.ajax and then in success function populate the dropdown list like this:
function selectHandler (event, ui)
{
var id = event.target.id;
$.ajax({
type: "POST",
url: "/php/get_quantity_type.php",
dataType:"json",
data: { ingridient : ui.item.value},
success: function(data){$("#"+id+"_t").empty(); $.each(data,function(index,value) {$("#"+id+"_t").append('<option value="' + value + '">' + value + '</option>');})}
});
}
This example takes a name of a material from select list posts it via $ajax() to a php script and writes it down to a new dropdown list which id is based on id that triggered the event. If you need the php code just ask:)
You bind your job list to the event handler above:
("#job_list").bind("select",selectHandler);
This code posts data to "/php/get_quantity_type.php", and passess the result to function declared in success attribute;

Categories