Not able to supply right argument to foreach statement - javascript

Hello I have 2 html tables. I am using jquery UI to change the position of the table and pass this jquery event arguments through ajax while taking index and item id of the table position so that I can update in the database the current position of the table. Everything is running fine I can pass the parameter. The only mistake I am making is I am not able to take this argument in foreach statement properly. It is generating an error in foreach statement that invalid argument supplied for foreach().Here is my fiddle :demo. I want to pass array but i am passing string in ajax. And not able to do so.I am getting like this when i try to print_r($_POST): Array ( [aktion] => show-widget [widget] => 1 [item] => Fahrzeuge )
Here is my code:
dashboard.js
$("#widget_update").sortable({
update : function(event, ui) {
var widget = $('#widget_update').sortable('serialize');
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {'aktion' : 'show-widget','widget':ui.item.index(),'item':ui.item[0].id},
success: function(data){
$('#widget').html(data.html);
},
error: function(data){
alert('Error');
}
});
}
});
dashboard.php
foreach ($_GET['item'] as $position => $item) :
$sql="Update dashboard_widget_users inner join dashboard_widget on dashboard_widget_users.dsnr_dashboard_widget=dashboard_widget.ID
set dashboard_widget_users.position=".$position."
where dashboard_widget.name='".$item."' and dashboard_widget_users.dsnr_yw_user=10";
$sql_update=mysql_query($sql);
endforeach;

You passed ui.item[0].id to your item property for your data. I think it is passing a string instead of an array that will be used to your foreach.
Try to pass ui.item
Hope that helps.
Answer 2:
Since you already know the position and id, you could loop them and store data in an object before passing to data property. This code may guide you:
$("#widget_update").sortable({
update : function(event, ui) {
var widget = $('#widget_update').sortable('serialize'),
items = [];
for (var i in ui.item) {
item = item[i];
items.push({
position: i,
id: item.id
})
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {
'aktion': 'show-widget',
'widget': ui.item.index(), // I'm not sure what is this for
'item': items
},
success: function(data){
$('#widget').html(data.html);
},
error: function(data){
alert('Error');
}
});
}
});
**In your PHP
// print_r($_POST);
foreach ($_POST["item"] as $value) {
// print_r($value);
$id = $value["id"];
$position = $value["position"];
}
These codes are not tested but you can see whats happening in there.

Related

Handle multiple data/parameters that change in Ajax - Wordpress

i am trying to filter custom post type called podcasts with ajax, using two custom taxonomies id as parameters, genre and country.
This is the front end: https://imgur.com/a/G2vB62q.
As you can see, i can choose a genre or/and a country to use as filter for my posts (below there is an array with the parameters that are passed).
In my podcast page i have two foreach, with link within, with name and the term_id.
foreach ($genre/$country as $category) {
echo '<a class="button-prova/button-prova2 premuto2"
name="keyword/keyword2" id="keyword/keyword2"
value="'.$category->term_id.'"
href="#">'.$category->name.'</a>';
}
Then, within function.php, i have my ajax function and ajax-fetch.
$( document ).ready(function() {
$(document).on("click touchend", ".premuto, .premuto2", function () {
fetch(this);
});
});
function fetch(prova){
if($(prova).attr('name') == 'keyword'){
var1 = $(prova).attr('value') ? jQuery(prova).attr('value') : 0;
} else
{
var2 = $(prova).attr('value') ? jQuery(prova).attr('value') : 0;
}
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: [var1,var2] },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
At first, when i choose one genre, the country is set to 0, as you see in the code. But when i select the other taxonomy, genre set to 0 (or vice versa, like in the image). There is a way to store my precendent selection?
Since you use AJAX. The previously selected value will persist if you declare the variable outside the functions. Try this.
var keywords = {};//Put this line outside of the function, so it available globally
$(document).ready(function() {
$('.premuto, .premuto2').on("click", function () {
keywords[$(this).attr('name')] = $(this).attr('value');
fetch();
});
});
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { 'action': 'data_fetch', 'keywords': keywords },
success: function(data) {
}
});
}
The keywords variable will look like this:
{keyword:0,keyword2:4}
And it will be read as an associative array in the PHP side.
Additional note:
Using javascript global variables can lead to clashing variable names from other scripts/plugins. To remedy this, you can encapsulate all your scripts inside a self-invoked function like this:
(function(){
/*PUT YOUR PLUGIN SCRIPTS HERE*/
})();
The buttons you use to filter have a certain markup (probably a class) when clicked. You can use that class as a toggle. In your 'fetch' function you can do:
keywords = Array();
$('.filters.toggle').each(function(){ // all filters with the toggle class
// add those values to the keywords array
keywords.push($(this).val()); // .val() is the same as attr('value')
});
keywords will be an array of all genres, countries that are toggled on.
then:
data: { action: 'data_fetch', keyword: keywords},

Sending php value to js via ajax

So, I have the following ajax call:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data);// Need changes
});
Then my php:
function rhmain_tag() {
// 1. Getting wp tag list:
$args = array(
'orderby' => 'count',
'order' => 'DESC'
);
$tags = get_tags($args);
foreach ( $tags as $tag ) {
echo $tag->term_id;
}
//2. Getting "another.php" file
$template_part_path = 'page-parts/another_php';
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_ajax_call', 'ajax_call');
add_action('wp_ajax_nopriv_ajax_call', 'ajax_call');
As you can see, in the php function, there are two separate thing going on.
Getting tag list passed onto the js as variable.
echo $tag->term_id; shows a number like this "16508164981650616502165031650416505165071650116520." So, somehow I need to put comma in between each term id (not sure how) so it looks like this : "16508,16498,16506,16502,16503,16504,16505,16507,16501,16520"
Then I need to pass these values to js to be used as a variable (not sure how)
another_php file is passed onto js (Works fine).
Questions:
How to do I add "comma" in between the tag term_id?
How do I pass these tag values to js?
EDIT: Using json_encode to pass data
PHP
function rhmain_tag() {
$template_part_path = 'page-parts/another_job';
$return_data['another_job'] = get_template_part($template_part_path);
$return_data['tag_id'] = '16498';
echo json_encode($return_data);
exit;
}
add_action('wp_ajax_rhmain_tag', 'rhmain_tag');
add_action('wp_ajax_nopriv_rhmain_tag', 'rhmain_tag');
JS:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
Using json_encode to send an array containing both data that you require front end you then need to make the following changes to your ajax function.
Change the dataType to json
Access the data as data.another_php and data.tag_id
The full ajax:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'json',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
To add the comma in between you could use a variable to store instead of echo'ing immediately. Like this :
$args=array(
'orderby'=>'count',
'order'=>'DESC'
);
$tags = get_tags($args);
$tag_list = "";
foreach ( $tags as $tag ) {
$tag_list += $tag->term_id + ",";
}
// Now trim the last comma
$tag_list = rtrim($tag_list, ",");
echo $tag_list;

How to catch array sent by PHP script as Ajax response and use further?

I am working on an e-commerce project for practice and right now I am building product filters. So I have three files
catalogue.php
It basically shows all the products.
product filters on left and displays products on right. When user checks a box then AJAX call is made.
productsfilter.js
It contains Javascript and AJAX calls.
var themearray = new Array();
$('input[name="tcheck"]:checked').each(function(){
themearray.push($(this).val());
});
if(themearray=='') $('.spanbrandcls').css('visibility','hidden');
var theme_checklist = "&tcheck="+themearray;
var main_string = theme_checklist;
main_string = main_string.substring(1, main_string.length)
$.ajax({
type: "POST",
url: "mod/product_filter.php",
data: main_string,
cache: false,
success: function(html){
replyVal = JSON.parse(myAjax.responseText);
alert(replyVal);
}
});
product_filter.php
It is the PHP script called by the AJAX call.
$tcheck = $objForm->getPost('tcheck');
if(!empty($tcheck)) {
if(strstr($tcheck,',')) {
$data1 = explode(',',$tcheck);
$tarray = array();
foreach($data1 as $t) {
$tarray[] = "adv.attribute_deterministic_id = $t";
}
$WHERE[] = '('.implode(' OR ',$tarray).')';
} else {
$WHERE[] = '(adv.attribute_deterministic_id = '.$tcheck.')';
}
}
$w = implode(' AND ',$WHERE);
if(!empty($w))
{
$w = 'WHERE '.$w;
}
$results = $objCatalogue->getResults($w);
echo json_encode($results);
So product_filter.php returns an array of product_ids retrieved from the database and gives it back to AJAX. Now the problem is: that array of product ids I got from AJAX call, how do I use it in catalogue.php?
As I got {["product_id" : "1"]} from product_filter.php, I want to use this id in catalogue.php and find the related attributes and display the product details.
How can I pass this array to my catalogue.php page so that it can use this array and call further PHP functions on it?
If the question is unclear then kindly say so, and I will try to explain it as clearly as I can. Help would be much appreciated.
It seems you want to get data from one php and send it to a different php page then have the ajax callback process the results from that second page.
You have at least 2 options
Option 1 (the way I would do it)
In product_filter.php, near the top, do this
include('catalogue.php');
still in product_filter.php somewhere have your function
function getFilterStuff($someDataFromAjax){
// ... do some stuff here to filter or whatever
$productData = getCatalogueStuff($results);
echo json_encode($productData);
exit;
}
In catalogue.php somewhere have that function
function getCatalogueStuff($resultsFromFilter){
// ... get product data here
return $productData;
}
Then in your Ajax do this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (response) {
replyVal = response;
alert(replyVal);
}
});
Option 2
Nested ajax calls like this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (filterResponse) {
$.ajax({
type: "POST",
dataType: "json", // add this
url: "catalogue.php",
data: filterResponse,
cache: false,
success: function (catalogueResponse) {
alert(catalogueResponse);
}
});
}
});

How to bind button function to a corresponding item in an array - AJAX, Firebase

I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}

Ajax request return empty array

I am trying to get the id, where the user clicked, and pass it to my controller via AJAX.
For some reason, when i try to show what i am receiving in my controller, it show an empty array.
Any idea why my alert return an empty Array?
JS Function:
function categorySelected(elem) {
$.ajax({
url: "/newgallery/creative-fields-click",
type: "POST",
data: elem.id
}).done(function (response) {
alert(response);
});
}
PHP:
public function creativeFieldsClickAction()
{
$idSelected = $this->_request->getPost();
print_r( $idSelected );
exit();
}
Data should be JSON, not integer.
data: { elemid : elem.id }
Then in PHP data can be found from $_POST['elemid']. In your code it could be like
$this->_request->getPost()['elemid'];
Or something like that.
Try by changing
In ajax
data: { id : elem.id }
And in action of controller
$ids = $_POST;
print_r($ids);

Categories