I have jQuery function that dynamically adds the Meta Key Name and Meta Key Value in Wordpress when a a checkbox in a certain custom post type is clicked. Currently the function Stores the post Id as the Meta Key Name but I would like to change this to say checkbox_meta_key so all posts under this custom post type have this Meta Key Name.
(function($){
$('li.todo').click(function(){
if($(this).find('.uncheck_box').length >0){
var _t=$(this).find('.uncheck_box');
_t.removeClass('uncheck_box');
_t.addClass('check_box');
m_val='1';
$(this).find('a').addClass('strike');
}else{
m_val='0';
var _t=$(this).find('.check_box');
_t.removeClass('check_box');
_t.addClass('uncheck_box');
$(this).find('a').removeClass('strike');
}
//trigger a custom event here
$(this).trigger('updateclass')
var m_key=jQuery(this).attr('id');
jQuery.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri(); ? >/ajax_get.php",
data: { meta_key: m_key, meta_value: m_val},
beforeSend: function( ) {
//jQuery(this).attr("disabled", true);
},
success:function(){}
})
});
var $checkboxes = jQuery('li.todo'),
$completeCount = jQuery('.complete-count'),
$incompleteCount = jQuery('.incomplete-count');
var updateCount = function(){
$completeCount.text(jQuery('.check_box').length);
$incompleteCount.text(jQuery('.uncheck_box').length);
};
$checkboxes.on('updateclass', updateCount);
updateCount();
$('.sort, .itemage').on('click', function (e) {
var $this = $(this).hasClass('sort') ? $(this).addClass('active') : $('.sort.active');
var itemage = $('.itemage').val(),
b = itemage == 10;
$('.sort').not($this).removeClass('active');
if ($this.hasClass('showall')) {
$('li.todo').hide().filter(function () {
return (this.getAttribute('itemage') === itemage || b);
}).show();
return;
}
var sel = $this.hasClass('incomplete') ? 'span.uncheck_box' : 'span.check_box';
$('li.todo').hide().filter(function () {
return (this.getAttribute('itemage') === itemage || b) && !! $(this).find(sel).length;
}).show();
var count=$(".leftlist li:visible").length;
document.cookie="incompletecount="+count;
})
})(jQuery)
jQuery(document).ready(function(){
jQuery('.chkbx').click(function(){
var cuser_id='<?php echo $current_user->ID;?>';
var m_val='0';
if(jQuery(this).is(':checked'))
{
m_val='1';
jQuery(this).parent().next("dd").addClass('strike');
}else
{
m_val='0';
jQuery(this).parent().next("dd").removeClass('strike');
}
var m_key=jQuery(this).attr('id');
jQuery.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri(); ?>/ajax_get/",
data: { meta_key: m_key, meta_value: m_val},
beforeSend: function( ) {
jQuery(this).attr("disabled", true); }
})
.done(function( msg ) {
jQuery(this).attr("disabled", false);
});
});
});
Where the ajax_get.php has the following code:
<?php
require_once('../../../wp-load.php' );
wp();
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
update_user_meta($current_user->ID, $_REQUEST['meta_key'],$_REQUEST['meta_value']);
echo $_REQUEST['meta_value'];
}
else{
echo'0';
}
?>
Basically you need to implement a database query, which will update all records, based on the new meta key, this can be done in your ajax_get.php file.
This is how you can do it.
Unfortunately your question is incomplete and I cannot give you more clues.
EDIT:
It seems to be an error in your code, check this line:
url: "<?php echo get_template_directory_uri(); ?>/ajax_get/",
should it be
url: "<?php echo get_template_directory_uri(); ?>/ajax_get.php" ?
Related
My question is I am checking input field value from database, if found then form should not submit. But in my case if 3 input fields are there one says already exists and other is normal value. Form gets submitted. How can i prevent form submission based on no error found on any input field.
public function check_module($postdata)
{
$module_name = $postdata['module_name'];
$data['select'] = ['*'];
$data['table'] = MODULE;
$data['where'] = ['module_name' => $module_name, 'status !=' => '9'];
$res = $this->selectRecords($data);
if ($res != null) {
$response = 0;
} else {
$response = 1;
}
echo $response;
exit;
}
$(document).on('change', '.module_name', function () {
var that = $(this);
var module_name = $(this).val();
var error = 0;
var base_url = $('#base_url').val();
$.ajax({
url: base_url + 'module/check_module',
type: 'post',
data: {
module_name: module_name
},
success: function (res) {
if (res == 0) {
that.next('span').html('Module already exist');
$('#submit').attr('disabled', 'disabled');
} else {
$('.text-danger').each(function () {
var value = $(this).html();
if (value != "") {
error++;
}
});
if (error == 1) {
$('#submit').removeAttr("disabled");
}
that.next('span').html('');
}
}
});
});
You could use a global variable which is modified with each ajax call. If the ajax response is zero add one into the global errors variable or 0 if all is OK.
To calculate if the array contains a mix of 1 & 0's there are a number of ways you could do that but a Set seems quite concise and can be combined with an array.reduce call to calculate the sum of all elements in the array. If the sum is zero the form can be submitted.
let errors=[];
let col=document.querySelectorAll('input[name="module_name"]');
$( document ).on('change', '.module_name', function(){
var that = $(this);
var module_name = $(this).val();
var base_url = $('#base_url').val();
$.ajax({
url: base_url + 'module/check_module',
type: 'post',
data: {
module_name: module_name
},
success: function( res ) {
if( res==0 ) {
that.next('span').html('Module already exist');
$('#submit').attr('disabled', 'disabled' );
}
errors.push( res==0 ); // add either 1 or 0 depending upon result
if(
// 3 elements?
errors.length == col.length
&&
// all the same number?
new Set( errors ).size==1
&&
// sum equals zero
errors.reduce( (a,b)=>a+b )==0
)$('#submit').removeAttr("disabled");
}
});
});
My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}
I want to delete the records that are dynamically created but the code is not working..Please have a look
script.js
$(function() {
$('#studentRecord').on('click', 'button.delete', function() {
var $tr = $(this).closest('tr');
var $id = parseInt( $(this).attr('id').split('-')[1] );
if ( confirm("Are you sure you want to delete this record") ) {
$.ajax({
url: '/ab_batch/practice/db/action.php',
type: 'POST',
data: {
action: 'ajaxDelRecord',
id: JSON.stringify(id)
},
success: function() {},
error: function() {}
});
}
});
});
action.php
$action = ( isset($_REQUEST['action']) && !empty($_REQUEST['action']) ) ? $_REQUEST['action'] : null;
switch ($action) {
case 'ajaxDelRecord':
if ( isset($_POST['id']) ) {
$id = json_decode($_POST['id']);
}
$id = json_decode($_POST['id']);
print ( $student->delRecord($id) ) ? 'true' : 'false' ;
break;
}
There is another file db.php that contains all the APIs for delete, add and update
JSON.stringify(id) should be JSON.stringify($id) as you are declaring your id as $id , you don't really need : JSON.stringify as you are just sending an integer to the server.
and for deleting the line which you just removed from database , you can just replace your javascript code with following:
$(function() {
$('#studentRecord').on('click', 'button.delete', function() {
var $tr = $(this).closest('tr');
var $id = parseInt( $(this).attr('id').split('-')[1] );
if ( confirm("Are you sure you want to delete this record") ) {
$.ajax({
url: '/ab_batch/practice/db/action.php',
type: 'POST',
data: {
action: 'ajaxDelRecord',
id: JSON.stringify($id)
},
success: function() {},
$tr.remove(); // removing the current deleted record from html.
error: function() {}
});
}
});
});
i did add $tr.remove(); inside a success callback , as you have already declared the parent element of the deleted record , so you just need to use : $tr.remove(); to delete the tr.
Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }
acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}