I have a checkBox in Yii and I use ajax in it. What I want to do is the use one 'url' parameter when the checkBox is checked and another different when it is unchecked.
For example, when checked:
'url'=> CController::createUrl('/item/add'),
When unchecked
'url'=> CController::createUrl('/item/remove'),
What is the best approach for it? Of course I do not want to check the state of the view checkBox from the controller.
Thank you
I know I would do jQuery, like:
var url = '';
if($('#chbInput').val() == 1)
{
//do something when checked
url = '<?php echo CController::createUrl('/item/add') ?>';
...
}
else
{
url = '<?php CController::createUrl('/item/remove') ?>';
...
}
Solved this way:
<input type="checkbox" id="chk">
<?php
$url1 = $this->createUrl('/item/add');
$url2 = $this->createUrl('/item/remove');
$js = '
$(\'#chk\').change(function(){
$.post(this.checked ? "'.$url1.'" : "'.$url2.'", function(data) {
$("#items").html(data);
});
});
';
Yii::app()->clientScript->registerScript('chk', $js);
?>
Related
I am using contact from 7 plugin and my question is to open contact form 7 in popup via wordpress admin ajax but my code not working. Only popup open but contact form 7 not submitting. It is redirecting in admin ajax url and returns 0.
Here is the code that i am doing in functions.php
<?php
add_action('wp_head', 'my_action_popup_cf7_javascript');
function my_action_popup_cf7_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.myajaxcarrer').click(function(){
//alert(1);
var mydata = $(this).data();
$(".overlay").fadeIn('slow');
var data = {
action: 'my_action_popup_cf7',
//whatever: 1234,
id: mydata.id
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
//console.log(ajaxurl);
$('.item').removeClass('active');
$('[data-id=' + mydata.id + ']').parent().addClass('active');
$.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
// alert('Got this from the server: ' + response);
$('#testcarrer').html(response);
var offset = $(window).scrollTop();
$(".career-form").css("top", offset+50 );
$('.closeBtn').click(function(e){
e.preventDefault();
$(".overlay").fadeOut('slow');
$('.career-form').css("top", -1000+"%" )
});
});
});
});
</script>
<?php
}
add_action('wp_ajax_my_action_popup_cf7', 'my_action_popup_cf7_callback');
add_action( 'wp_ajax_nopriv_my_action_popup_cf7', 'my_action_popup_cf7_callback' );
function my_action_popup_cf7_callback() {
global $wpdb; // this is how you get access to the database
//$whatever = 'ID=> '. $_POST['id'];
//echo $whatever;
?>
X
<h3>Apply Now</h3>
<div class="formBox">
<?php echo do_shortcode('[contact-form-7 id="905" title="My New Carrer Form"]'); ?>
</div>
<?php
exit(); // this is required to return a proper result & exit is faster than die();
}
And code in page template file is
<span class="applyBtn"><a class="myajaxcarrer" data-id="903">Apply Now</a></span>
<div class="overlay"></div>
<div class="career-form">Ajax result Load here..</div>
And js code is below.
$('.applyBtn').click(function(e){
e.preventDefault();
var offset = $(window).scrollTop();
$(".overlay").fadeIn('slow');
$(".career-form").css("top", offset+50 )
});
$('.closeBtn, .overlay').click(function(e){
e.preventDefault();
$(".overlay").fadeOut('slow');
$('.career-form').css("top", -1000+"%" )
});
You can open it by echoing do_shortcode('[form name with id]'); it in you php function.
Hi im attempting to use jquerys ajax to update a form after a GET request, I simply want the table to update but it send through the page headers as well.
First Here is my script, its small so i will include it all,
var wishorder = {
init: function(config){
this.config = config;
this.bindEvents();
},
bindEvents: function(){
this.config.itemSelection.on('click',this.addWish);
},
addWish: function(e){
console.log('working');
var self = wishorder;
$.ajax({
url: $(this).attr('href'),
type: 'GET',
data: {
sku: $(this).data('sku'),
action: $(this).data('action'),
qty: $(this).data('qty')
},
success: function(results){
//here is where is would like to repopulate the div
//but its outputting the whole page
console.log(results);
}
});
e.preventDefault();
}
};
wishorder.init({
itemSelection: $('#carttable a'),
form: $('#cartfrm')
});
I can see that it is returning the results i want but it wraps it in html as in page header.
Here are the php function its calling.
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_GET['action'] == 'move'){
list($sp_type, $pid) = $this->parse_sku($_GET['sku']);
$qty = (filter_var($_GET['qty'], FILTER_VALIDATE_INT, array('min_range' >= 1)))?$_GET['qty']:1;
$q = "CALL add_to_wish_list('$this->uid', '$sp_type', $pid, $qty)";
$this->query($q);
$q = "CALL remove_from_cart('$this->uid', '$sp_type', $pid)";
$this->query($q);
$q = "CALL get_shopping_cart_contents('$this->uid')";
$this->query($q);
$this->read();
$this->outcart();
exit();
}
and the outcart function wich generates the html for the div
function outcart(){
echo "<div id=\"cartcont\" class=\"cartitems\"><form action=\"/cart.php\" method=\"post\"><table id=\"carttable\"><tr class=\"theads\"> <th class=\"titm\" >Item</th> <th >Quantity</th> <th >Price</th> <th>Subtotal</th> <th class=\"topt\" >Options</th>";
$total = 0;
while($row = $this->_result->fetch_object()){
$price = $this->get_just_price($row->price, $row->sale_price);
$subtotal = $price * $row->quantity;
$total += $subtotal;
echo "<tr class=\"tdata\">
<td>".$row->category." :: ".$row->name."</td>
<td><input type=\"text\" name=\"quantity[".$row->sku."]\" value=\"$row->quantity\" size=\"2\">
<td>$".$price."</td>
<td>$".number_format($subtotal, 2)."</td>
<td> Move To Wishlist <br> Remove From Cart </td>";
}
echo "</tr><tr class=\"ttotals\"><td colspan=\"3\" ><strong id=\"carttotal\">TOTAL:</strong></td>
<td colspan=\"2\" > $".number_format($total,2) ." </td>
</tr>";
echo "</table>";
echo "<div id=\"cartmnbtns\"><p><input type=\"submit\" value=\"UPDATE QUANTITIES\" class=\"buttoncart1 green\"><br>Checkout</p> </div></form>";
}
So i just want to repopulate the table really or the cartcont div with the results, where am missing the point?
The page you're calling is url: $(this).attr('href') and that's a web-page you're just on with all headers and stuff... You have to put your functions in a separate .php file that doesn't contain a whole web-page frame and only outputs the text you want.
If that's not possible then create in your success callback function with document.createDocumentFragment(), pass the whole response inside the fragment and pull out your stuff you need with something like myHTML = docFrag.getElementsByTagName('div')[0] and then pass this with append to your form.
You might also want to set something like contentType: "text/plain; charset=utf-8" in your ajax call.
By the way: If you're not using the convenience of parsing variables inside strings you might want to use a different way (the other quotes) of writing your strings, as it's then faster, so:
echo '<tr class="tdata">...'
Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}
If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});
I'm adding a button to every list_item on page.
The buttons are generated, with their correct id.
And the button value changes as it should - as shown in the alert.
But on a single button click, the alert fires as many times as there are buttons on the page.
The alert always shows the same (and correct) button id.
Without the alert, this causes the button value to switch back and forth if other buttons are clicked in the meantime.
Generate the buttons:
function create_saved_message_button( ) {
$button_label = "Save";
?>
<td width="15%" class="thread-options">
<input type="button" class="savedbutton" value = "<?php echo $button_label ?>" id = "<?php echo message_thread_id(); ?>" />
</td>
<?php
}
The ajax:
function saved_message_button_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.savedbutton').click(function(event){
event.preventDefault();
var button = $(this);
var butt_txt = $(button).attr('value');
alert($(button).attr("id"));
$(button).attr({'disabled': true});
var data = {
action: 'saved_button_clicked',
};
$.get(ajaxurl, data, function(response) {
if(butt_txt == 'Save') {
$(button).attr('value', 'Un-Save');
}
else {
$(button).attr('value', 'Save');
}
});
$(button).attr({'disabled': false});
return false;
});
});
</script>
<?php
}
Is there any way to stop the multiple alerts?
I think that would solve the value switching problem.
Then I just need to pass the button id to the php function saved_button_clicked
The add_actions:
add_action( 'messages_inbox_list_item', 'create_saved_message_button', 1 );
//this was the problem
//add_action('messages_inbox_list_item', 'saved_message_button_javascript');
//the solution - use this instead
add_action('after_member_messages_threads', 'saved_message_button_javascript');
add_action('wp_ajax_saved_button_clicked', 'process_save_button_clicked');
Maybe I misunderstood something. I created a html with 5 buttons and your javascript in it but I couldn't find the behavior you described. Look here.
Hi guys Im trying to make a drop-down list of countries and when the user select a country that redirect to a specific page created dynamically actually i manage to make the redirection work using javascript, but i need to take more parameters to the method inside the controler like the county "id" with out exposing it on the uri, so is that possible using $_post also i should not use button submit.
this is my code
view page
<?php echo form_open('site/country');
$options = array();
$js = 'id="country" onChange="window.location.href= this.form.CTRY.options[this.form.CTRY.selectedIndex].value"';
$options['#'] = "(please select a country)" ;
foreach ($list as $row):
$value= site_url()."/site/country/".url_title($row->name);
$options[$value] = $row->name ;
endforeach;
echo form_dropdown('CTRY', $options,'',$js);
//$test =array ('number' => 10)
//echo form_hidden($test);
echo form_close();?>
this is my method in controller
function country($data)
{
echo 'this is taking you to county= '.$data;
}
Why don't you do something like #Joseph Silber described.
Use jQuery to perform an ajax request when the drop-down list is changed, also managing the redirect?
Something like;
$('#my-drop-down').change(function() {
$.ajax({
url: '/site/country',
type: 'post',
data: $("#my-form").serialize(),
success: function( response.redirect ) {
window.location.href = response.redirect;
},
error: function( response ) {
alert('Oops');
}
});
});
By using serilaize(), you can post all data from the form, or just add the parameters you want to pass.
E.g data: 'id='+$('#id').val()+'&country='+$('#country').val()