on click function is not working properly with codeigniter anchor() - javascript

I'm using Codeigniter 2.2. I'm trying to build a table using HTML table class library. It also contain a edit button .here is my view file :
foreach($invoices as $row) {
$data = array(
'name' => 'btn btn-default btn-sm dropdown-toggle',
'type' => 'button',
'content' => '',
'class' => 'btn btn-default btn-sm dropdown-toggle',
'class' => 'entypo-trash',
);
$edit_url = base_url().
'index.php?modal/popup/modal_edit_invoice/'.$row['invoice_id'];
$onclick_edit = array('onclick' => "showAjaxModal('{$url}')");
$links = form_button($data, $js);
$links. = anchor('#', 'edit', $onclick_edit); //here is the issue, on click popup try load , but in a next second page redirect to the index page
$this->table->add_row(
$this->crud_model->get_type_name_by_id('student', $row['student_id']), $row['title'], $row['description'], $row['amount'], $row['amount_paid'], $row['due'], $row['status'], $links
);
}
echo $this->table->generate();
Everything is working fine. But when I try to click edit button my model window is popup but in a next second page redirect to the index page.
Here is JavaScript file :
function showAjaxModal(url) {
// SHOWING AJAX PRELOADER IMAGE
jQuery('#modal_ajax .modal-body').html('<div style="text-align:center;margin-top:200px;"><img src="assets/images/preloader.gif" /></div>');
// LOADING THE AJAX MODAL
jQuery('#modal_ajax').modal('show', {
backdrop: 'true'
});
// SHOW AJAX RESPONSE ON REQUEST SUCCESS
$.ajax({
url: url,
success: function(response) {
jQuery('#modal_ajax .modal-body').html(response);
}
});
}
It's working fine with anchor tag but I can't use that one in HTML table class.
Please help me out.. thanks in advance

Just change this line
$onclick_edit = array('onclick' => "showAjaxModal('{$url}')");
to this
$onclick_edit = array('onclick' => "return showAjaxModal('{$url}')");
And change your js function like this
function showAjaxModal(url) {
// SHOWING AJAX PRELOADER IMAGE
jQuery('#modal_ajax .modal-body').html('<div style="text-align:center;margin-top:200px;"><img src="assets/images/preloader.gif" /></div>');
// LOADING THE AJAX MODAL
jQuery('#modal_ajax').modal('show', {
backdrop: 'true'
});
// SHOW AJAX RESPONSE ON REQUEST SUCCESS
$.ajax({
url: url,
success: function(response) {
jQuery('#modal_ajax .modal-body').html(response);
}
});
return false; //this will stop <a> tag behavior
}

Related

How to save a post and custom fields values with ajax in front end in wordpress?

p.s. had placed this simply to share the solution.
I'd like to save a post in front end if we click a button using ajax in js:
var title = $("#portfolioTitle").val();
var customFieldValues = $("#customfieldValue").val();
$("#btnClick").on("click", function() {
$.ajax({
url : ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'data_Publish', portfolioTitle: title, fieldValues: customFieldValues
},
success: function(data) {
if(data == "exists") {
console.log("Add a different title");
} else {
console.log("post added");
console.log(data["link"]);
console.log(data["title"]);
}
}
});
});
Placing my own answer but wondering if there is there any speed or security improvements?
For example we could add a caching system, or define our own ajax (Maybe a help could be answering: How to implement the code in the link using the case scenario we have on this question?) in order not to have wordpress loading all the files but here we are doing a http request, anyway, if any of you would want to give their 2 cents to make it faster, It'd be great.
Let's say we want to add posts via ajax in frontEnd in wordpress and we want to check if the title is unique in the database otherwise tell the user to add a different title:
We have a button to click:
<button type="button" id="btnClick">Load</button>
We have an input for the title and a custom field:
<input type="text" id="portfolioTitle" name="portfolioTitle" value="" placeholder="Your title...">
<input type="text" id="customfieldValue" name="customfieldValue" value="" placeholder="Your customFieldvalue...">
The JS. Firstly you need to load wordpress ajax (This is the bit that could be improved if anyone fances to):
var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
Then your javaScript:
var title = $("#portfolioTitle").val();
var customFieldValues = $("#customfieldValue").val();
$("#btnClick").on("click", function() {
$.ajax({
url : ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'data_Publish', portfolioTitle: title, fieldValues: customFieldValues
},
success: function(data) {
if(data == "exists") {
console.log("Add a different title");
} else {
console.log("post added");
console.log(data["link"]);
console.log(data["title"]);
}
}
});
});
Then in function.php:
function data_Publish() {
$post_title = $_POST['portfolioTitle'];
$post_custom_field = $_POST['fieldValues'];
$post = array(
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'page',
'page_template' => 'portoflio.php'
);
if ( get_page_by_title( $post_title ) === null ) {
// the title is unique, we can add the new page
$post_id = wp_insert_post( $post );
add_post_meta($post_id, 'customField', $post_custom_field], true);
$link = get_permalink( get_page_by_title( $post_title ) );
$title = get_the_title($post_id);
$newPostAttributes[] = array("link"=>$link, "title"=>$title);
echo json_encode($newPostAttributes);
} else {
// that title already exists, tell the user to change it
echo json_encode("exists");
}
wp_die();
}
add_action('wp_ajax_data_Publish', 'data_Publish');
Basically that function is a normal wordpress query. Therefore you could use the same logic to retrieve post values if You'd want to, for example you won't be using $post_id = wp_insert_post( $post ); but maybe to get the tittle back to the user you'd use $postTile = get_the_title();.
Let's break it down:
In ajax we use action: 'data_Publish', portfolioTitle: title where data_Publish is our php function, and portfolioTitle: title is what we are sending.
In function we can see: $post_title = $_POST['portfolioTitle']; that's our title that we have sent via ajax. With 'page_template' => 'portoflio.php' we can add our own template to that page.
Then we need to use if ( get_page_by_title( $_POST['portfolioTitle'] ) === null ) { to check if that title exists or not, if it doesn't exist, we add the posts to the database with $post_id = wp_insert_post( $post );
Once we added it we use the following to add any other values to our custom field in the newly created postadd_post_meta($post_id, 'customField', $_POST['customfieldValue'], where customField is the name of the custom field we want to create in the new post we just added.
So if the posts doesn't exist, we save it and we can send back to ajax its title and its link so that we could shows it to the user as a response if We'd ever want to.
So we define title and link like this and we create a multidimentional array to send the data back to the front end:
$link = get_permalink( get_page_by_title( $post_title ) );
$title = get_the_title($post_id);
$newPostAttributes[] = array("link"=>$link, "title"=>$title);
If the title exists we send back a response echo json_encode("exists");
We need to die the query for safeness wp_die();
If We'd ever want to make ajax available to no logged user, remember wordpress ajax is only available to admin, so we need to add:
add_action('wp_ajax_data_Publish', 'data_Publish');
add_action( 'wp_ajax_nopriv_data_Publish', 'data_Publish' );
Basically in function.php wordpress uses wp_ajax_ +"name of our function" and wordpress has wp_ajax_nopriv_ to make ajax available if not logged.
I hope It helps anyone and if any of You could improve it, It'll be better for all.

How to use jQuery in WordPress shortcode?

I want to show this jquery variable's value into WordPress shortcode.
I already tried but not working.
Jquery code:
jQuery('.button').on('click', function(){
var post_id = jQuery(this).attr('data-product_id');
//alert(post_id);
});
PHP Code:
echo do_shortcode('[product_page id="36"]');
It's a bit more complicated than you might think. What you have isn't going to work because PHP processes on the server and jQuery runs in the clients browser.
A potential solution could be.. on button click send the variable (post_id) via an AJAX request to the server, this would then process and generate the shortcode html which will then return the html for you to use in your JS.
Below is an example of what I mean...
jQuery
$('.button').on('click', function() {
var $button = $(this);
var post_id = $button.data('product_id');
$button.prop('disabled', true); // Disable button. Prevent multiple clicks
$.ajax({
url: myLocalVariables.ajax,
method: 'post',
data: {
action: 'render-product-shortcode',
id: post_id
}
}).then(function(response) {
if (response.success) {
var $shortcode = $(response.data);
// Do what ever you want with the html here
// For example..
$shortcode.appendTo($('body'));
} else {
alert(response.data || 'Something went wrong');
}
}).always(function() {
$button.prop('disabled', false); // Re-enable the button
});
});
functions.php
// Set local JS variable
add_action('wp_enqueue_scripts', function() {
wp_localize_script('jquery', 'myLocalVariables', [
'ajax' => admin_url('admin-ajax.php')
]);
});
// Handle AJAX request
add_action('wp_ajax_render-product-shortcode', 'render_product_shortcode');
add_action('wp_ajax_nopriv_render-product-shortcode', 'render_product_shortcode');
function render_product_shortcode() {
$product_id = !empty($_POST['id']) ? (int)$_POST['id'] : 0;
if ($product_id) {
return wp_send_json_success( do_shortcode('[product_page id="'.$product_id.'"]') );
}
return wp_send_json_error('No ID in request.');
}

pendig bootstrap modal in click for load remote data

I have this code for load dynamic data from remote file into bootstrap using jquery ajax :
JS:
$(function(){
$('.push').click(function(){
var essay_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'your_url.php', // in here you should put your query
data : 'post_id='+ essay_id, // here you pass your id via ajax .
// in php you should use $_POST['post_id'] to get this value
success : function(r)
{
// now you can show output in your modal
$('#mymodal').show(); // put your modal id
$('.something').show().html(r);
}
});
});
});
HTML:
click
<div class="modal-body">
<div class="something" style="display:none;">
// here you can show your output dynamically
</div>
</div>
this worked for me But modal box not show until/pending data loaded. I need to load modal box after click and then load data.
how do fix this?!
You could make the ajax call outside your click event on load and show hide on click:
$(document).ready(function() {
var essay_id = $(this).attr('id');
var results;
$.ajax({
type : 'post',
url : 'your_url.php',
async: false
'post_id='+ essay_id,
success : function(r) {
results = r;
}
});
$(' your_element').click(function() {
if (results) {
$('#mymodal').show();
$('.something').show().html(results);
}
});
});
Using async:false will force it to finish your request before continuing the script. Hope this helps.

How to refresh Yii widget without refreshing/changing page

I'm having an issue with submitting a TbActiveForm and the renderPartial wiping my page out and displaying only the partial view. I want to reload only the widget after my action triggers and finishes. I'm also using a modal to display and make changes.
view:
$form = $this->beginWidget(
'booster.widgets.TbActiveForm',
array(
'id' => 'horizontalForm',
'type' => 'horizontal',
'action' => Yii::app()->createUrl('orderControl/order/returns.save'),
)
);
echo $form->hiddenField(
$editReturnFormModel,
'orderId',
array(
'value' => $editReturnFormModel->orderId
)
);
$this->widget(
'bootstrap.widgets.TbButton',
array('buttonType' => 'submit', 'type' => 'primary', 'label' => 'Save')
);
$this->endWidget();
Action:
$this->controller->renderPartial('ScModules.orderControl.widgets.ReturnsWidget.views._returnItems', array('returnsDataProvider'=>$returnsDataProvider, 'editReturnFormModel'=>$editReturnFormModel));
One other point is that the Yii::app()->createUrl('orderControl/order/returns.save') is change the page url all together. On this page page I'm directed to, the view is created fine. I need the widget to rebuild/refresh on the current page and not send me somewhere else. Any ideas on solution would be appreciated.
Here's what I would do:
Wrap your form widget inside a div or whatever block tag you like.<div id="myFormWrapper"> (your widget goes here) </div>
Add a custom ID in your form (id="formId") and submit button (id="submitButtonId")
Add some jQuery in order to submit your form and replace the old widget with the new
$(document).on('click', '#submitButtonId' , function() {
$.ajax({
type: 'POST',
url: $('#formId').attr('action'),
data : $('#formId').serialize(),
beforeSend : function(){
//do anything you want before sending the form
},
success : function(data){
//We'll replace the old form with the new form widget
$('#myFormWrapper').html(data);
},
error : function(data){
console.log('ops');
},
});
return false;
});
Do whatever you want to do in your Controller action and use renderPartial.
//The action below should be the same that you used in the action attribute of the form
public function actionProcessForm(){
$model = new MyFormModelName();
if(isset($_POST['MyFormModelName'])){
$model->attributes = $_POST['MyFormModelName'];
if($model->save()){
//Do whatever you want here
$returnsDataProvider = new CActiveDataProvider('YourModel');
$this->renderPartial('//folder/to/your/view', array('returnsDataProvider'=> $returnsDataProvider, 'editReturnFormModel'=>$editReturnFormModel));
}else{
//You might want to render something else here
$this->renderPartial('errorViewPage');
}
}
}

Update database with html link click using ajax php mysql

I've read through a number of similar questions and tried my hand at putting it to work on my website, but it is not working (when you click the link there is no response on the console and the database is not updated).
Here's what I want to do: I want users to rate a comment +1 by clicking an icon next to the comment. I want that to update my mysql comment_table column called rating with rating+1. When I do it without AJAX (ie, just set the form action to a php page?id=10) it works fine. I can't get the AJAX to update the database though.
My main page with the comment:
<span class="glyphicon glyphicon-chevron-up"></span>
The javascript below that link:
<script type="text/javascript">
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
rating: rating,
id: <?php echo $thisperspective_row['id']; ?>,
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
</script>
and my rating.php file is
<?php
require_once('connectiontodatabase.php');
/* simple comment up and down voting script */
$mode = $_GET['mode'];
$rating = $_GET['rating'];
$id = $_GET['id'];
if ($mode=="vote")
{
// The name of the
$cookie = "nameofmycookie".$id;
if(isset($_COOKIE[$cookie]))
{
echo '<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Sorry You have already rated this comment within the last 14 days.</div>';
}
else
{
$expiry = 1209600 + time(); // 14 day expiry
setcookie ($cookie, "voted", $expiry);
mysql_query ("UPDATE comment_table SET rating = rating+$rating WHERE id=$id", $connection);
}
}
?>
The php runs fine and all the variables are listed properly when I view the source. However, when I click the link, there is no response at all and the console does not output the response. What am I doing wrong? Thanks in advance!
Firstly you should change the way you are detecting the click event. Check out this fiddle. Then secondly you need to pass all the variables through in one JSON string using the data option. Your code should look something like this:
<span class="glyphicon glyphicon-chevron-up clickable"
data-rating="1"
data-id="<?php echo $thisperspective_row['id']; ?>"></span>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "vote",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'rating.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
First off all, check that you are loading jQuery, then use this code
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
data: { rating: rating, id: id },
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
is working for me.
note that I removed ` inside Ajax, since you are already sending the params in the function, also to send params you have to use data:, you can see more examples here Ajax jQuery

Categories

Resources