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},
Related
In my website I have a link where user id is store like this :
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
Here you can see variable $uid. This is the user id. So I want to make ajax call when I click on this link. It's should get the value of $uid to result page ofUser.php. But in result page (ofUser.php) it's showing :
Undefined index: id
Can you tell me how can I solve it ?
Here is the JS offUser function
function ofUser(id, event){
id = $(id);
event.preventDefault();
var formData = id;
$.ajax({
url : <?php echo "'ofUser.php'"; ?>,
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend : function () {
$("#ofUser_message").val("Searching...");
},
success : function (data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
offUser.php
echo $uid = (int) $_POST['id'];
id = $(id); will cast id to jQuery object which is not making any sense here. It will make id as array(id=$(1) => [1])
Also note, your data being sent over server should be an object.
Try this:
function ofUser(id, event) {
event.preventDefault();
$.ajax({
url: 'ofUser.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function() {
$("#ofUser_message").val("Searching...");
},
success: function(data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: {
id: id
},
cache: false
});
}
Edit: Remove processData : true as it will send data as DOMDocument
Just try to pass id = id; instead id = $(id); because $(id) means you are trying to get any DOM element values using jQuery, I hope it will work, also tell me that, what HTML is generated for your this code
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
To solve this problem, SIMPLIFY to make sure you are correctly passing the ID value. In your AJAX success function, ALERT the value you send back so you can immediately see what you received in PHP.
Try setting it up this way instead:
html:
<p>by <a id="uid_<?php echo $uid; ?>" href="#" ><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</a></p>
javascript:
$('[id^=uid_]').click(function(event){
event.preventDefault();
var formData = this.id.split('_')[1];
$("#ofUser_message").val("Searching...");
$.ajax({
type : 'POST',
url : 'ofUser.php',
data : id=formData,
success : function (data) {
alert(data);
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
}
});
});
ofUser.php
$uid = $_POST['id']; //REMOVE the (int) for now, to verify what PHP is receiving - then add it back.
echo 'Received $uid';
Notes:
(1) Note that you misspelled ofUser.php and offUser.php (not sure which is correct - I went with ofUser.php)
(2) Try not to use inline javascript. jQuery is easiest to use when you break out the javascript from the HTML, as per above example.
(3) In above example, the jQuery selector starts with is used:
$('[id^=uid_]').click(function(event){
That code is fired by any element whose ID begins with uid_, as we configured the <a> tag's ID to appear. That makes it easy to see in your HTML.
(4) This line:
var formData = this.id.split('_')[1];
uses pure javascript to get the ID, because it's faster - and simpler to type. The code splits off the 2nd part of the ID, at the _ char, resulting in just the ID number. That ID number is then assigned to the variable formData
(5) In the AJAX code block, make sure the url is spelled correctly:
url : 'ofUser.php',
Here are some other SIMPLE AJAX examples that might help. Don't just look at them - reproduce them on your server and play with them. They are simple, but you may learn a lot:
AJAX request callback using jQuery
When click over any hyperlink then start redirecting to provided URL. so you need to prevent its default action using below code inside your click event handler
event.preventDefault();
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
});
}
I'm quite new to programming, and im trying to update a certain column in a database using php and javascript.
The data base only has 2 columns, seatnums and status. Basically, i want the status to reset back to 1 if the status is currently 0. Could anybody point me in the right direction?
I have a class inside a div in my HTML:
<a class='two' href="javascript:databaseReset() ">Reset</a>
My javascript function (Part im struggling with):
function databaseReset();
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
function over(id) {
selectedseat=$(id).attr('title');
$(id).attr('src','images/mine.gif');
$(id).attr('title', 'Available');
}
function out(id) {
$(id).attr('src','images/available.gif');
}
my php file:
<?php
include("dbconnect.php");
$query="UPDATE seats SET status=1 WHERE status=0";
$link = mysql_query($query);
if (!$link) {
die('error 2');
}
?>
I assume it was simply a typo, but your function call needs to wrap brackets around the ajax call:
function databaseReset(){ //<---*****Add these braces*****
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
}; //<---*****Add these braces*******
your code seems to declare the function, but not assign its functionality
Also, the data section is unnecessary, as it is not used. In fact, since you are not posting data, you can use the "GET" method instead.
Beyond that your code looks good, can you please specify what the issue is?
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.
I have two tables, has-many relationship,
in the master add.ctp, allow user to upload 0~5 files(file path information are stored in details table)
I want to dynamically display attachment(detail) form in the master/add.ctp
1, user choose number of files want to upload from dropdown list,
echo $this->Form->input('attachments', array( 'options' => array(1, 2, 3, 4, 5),'empty' => '(choose one)', 'onchange' => 'showNumber(this.value)'));
then forloop
{
echo $this->Form->input('attachment_path', array('type'=>'file','label' =>'Attachment, Maximum size: 10M'));
}
//but I don't know how to capture this.value, I know Javascript can not pass value to php.
or user click 'add another attachment' link, then detail form shows up.
How to achieve this function, any help would be appreciated.
I have read this article:
Assign Javascript variable to PHP with AJAX
and get same error: the variable is undefined
Edit:
http://cakephp.1045679.n5.nabble.com/Adding-fields-to-a-form-dynamically-a-complex-case-td3386365.html
'For each field use a default name with [] at the end (which will make
it stack like a array) example: data[][book_id] after the fields have
been submitted'
Where should I place the []?
I think you should use Ajax for this.
Simply create an ajax call on select.change() and then a method in the controller that returns the necessary info.
You can return an array of data using echo json_encode(array('key' => 'value')) directly on your controller (or better in a custom view) and access it with Javascript:
success: function(data) {
alert(data.key);
}
Edit...
In your javascript use something like...
$('select').change(function(e) {
var select = $(this);
$.ajax({
type: "POST",
dataType: "json",
url: "/attachments/youraction",
data: { data: { id: select.find(":selected").val() } },
success: function(data) {
for (i in data) {
var input = $('<input>', {type: "file", label: data[i].Attachment.label})
$('form.your-form').append(input);
}
}
})
});
Then in "Yourcontroller" create "youraction" method:
<?php
class AttachmentsController extends AppController
{
public function youraction()
{
if (!$this->RequestHandler->isAjax() || !$this->RequestHandler->isPost() || empty($this->data['id']))
{
$this->cakeError('404');
}
// Do your logic with $this->data['id'] as the select value...
$data = $this->Attachment->find('all', array('conditions' => array('id' => $this->data['id'])));
// ....
// then output it...
echo json_encode($data);
// This should be done creating a view, for example one named "json" where you can have there the above echo json_encode($data);
// Then..
// $this->set(compact('data'));
// $this->render('json');
}
}
It's more clear now?? If you have doubts about ajax + cakephp you should do a search on the web, where you will find a lot of tutorials.
I use this approach to achieve this function. (finally got it :))
http://ask.cakephp.org/questions/view/foreach_loop_with_save_only_saving_last_member_of_array
Yes, AJAX can do lots of things, to me, it's very hard to understand the logic in a day..
Anyway, Thanks again.