How to use jQuery in WordPress shortcode? - javascript

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.');
}

Related

AJAX Sql Update not working

I stripped down my code to make this question a little simpler.
This is my PHP at the top of the file...
if (isset($_POST['action'])) {
$field = $_POST['db_field'];
$value = $_POST['db_value'];
$fields=array('points'=>($value));
$db->update('teams',$field,$fields);
}
Then I have this script on the same page...
<script type="text/javascript">
function performAjaxSubmission() {
$.ajax({
url: 'points3.php',
method: 'POST',
data: {
action: 'save',
field: $(this).attr("db_field"),
val: $(this).attr("db_value")
},
success: function() {
alert("success!");
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(performAjaxSubmission);
});
</script>
Then I have 2 super simple buttons for testing purposes...
Click here-1
Click here-2
Currently, it just basically passes null to the database and gives me a success message.
If I change...
$field = $_POST['db_field'];
$value = $_POST['db_value'];
To...
$field = 233;
$value = 234;
It puts the number 234 in the proper column of item 233 in my database as I would like. So basically whatever is in that link is not getting passed properly to the post, but I don't know how to fix it. Any help would be awesome.
Change your data variable to this
data: {
action: 'save',
db_field: $(this).attr("db_field"),
db_val: $(this).attr("db_value")
},
And it won't send null value
Your variable name in js is this :
**field**: $(this).attr("db_field"),
**val**: $(this).attr("db_value")
So in php file use:
$_POST['field'];
$_POST['val'];
to get values of these two variables.

How to display comment form submit without refresh the page using AJAX?

Comment Form is submitting and also data getting saved to the database. But not displaying on the browser without refreshing the page.
here is the code:
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
EDIT:
All i can understand is i haven't published the data with ajax??
Is this what i need to do??
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/get_more_comments.php',
data: 'last_id='+last_id,
success: function(data){
$('.view_container').append(data);
},
complete: function(){
console.log('DONE');
}
});
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
All your code does is post the data to the server. There is nothing that fetches the new comments from the server or manually appends the posted comment. You can either use ajax again to refresh comments or more simply append a comment with the posted content.
I would say to search the web for jQuery's .load :
example:
function updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
}
in this case shoutbox would be the containing div with your comments,
you would call this function on the success of your ajax post
latestshouts.php would only contain the content of that div.
kinda hard to explain, i hope it makes sense to you
link: http://api.jquery.com/load/

redirect after alert message not working

this is a snippet of a js file>
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList',
type: 'POST',
data: {id: id, userT: usertype},
success: function(html){
$('[data-id='+id+']').parents('tr').remove();
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
as you can see there is an alert message after deleting a user from a list.
I want to refresh the page after ok on alert message is pressed so i added the line>
window.location.reload();
but it's not working, why is this? how can i fix it?
I've been trying to use alternative to this like
location.href = '....';
window.location = '/some/url';
but nothing seems to work!
this is in my admin.php, the code for deleting user from the database:
public function deleteUserFromList(){
if ((isset($_POST['id']) && (isset($_POST['userT'])))){
$rowId = $_POST['id'];
$userType = $_POST['userT'];
$result = array();
if($userType == 'front'){
$front = UserManager::getInstance()->getUser($rowId);
UserManager::getInstance()->deleteItem($front);
}else{
$back = UserBackManager::getInstance()->getUser($rowId);
UserBackManager::getInstance()->deleteItem($back);
}
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
}
In order to simulate redirect in your browser try to:
Javascript way:
window.location.replace("http://stackoverflow.com");
jQuery way:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
Try this and let me know it it works for you or not.
EDIT:
Inside ajax success. Try to close modal window and try to replace method.
EDIT 2:
Put this part of code inside of your document ready block and check is it fired or not if it is fired it means your form is reloading correctly.
$( window ).unload(function() {
alert( "Bye now!" );
});
Elaborating on #charlietfl's comment, could you try something like this?
Return the count from the ajax script and insert it into your page:
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList', // this returns the user count as data
type: 'POST',
data: {id: id, userT: usertype},
success: function(data){
$('[data-id='+id+']').parents('tr').remove();
$('#countDisplayElement').text(data); // insert new count into current page
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
That would eliminate the need to refresh the page entirely and be a bit more friendly to use.

laravel ajax post issue

I have been working on this all weekend and cant get it to work. I can get it working using get but not post. Im using Laravel 4 and jquery.
My JS looks like this:
$('.status').on('click', function(){
var $modal = $('#ajax-modal');
var id = $(this).attr("id");
setTimeout(function(){
$modal.load('../status/'+id, '', function(){
$modal.modal();
});
});
});
which opens a bootstrap modal just fine and loads the status page. On that page, I set a button with an id of the user, and when that is clicked, I call another JS snippet:
$modal.on('click', '.update', function(){
$modal
.find('.modal-body')
.html('<div class="progress progress-striped active"><div class="bar" style="width: 100%;">Processing ...</div></div>');
var PostData = 'UserId='+$(this).attr("id");
$.ajax({
type: "POST",
url: "",
data:PostData,
success: function(msg){
$('.update').prop('disabled', true);
setTimeout(function(){
$modal
.find('.modal-body')
.html('<div class="alert-show-success"><img src="../../../public/assets/img/icons/accept.png" />This user was successfully de-activated!</div>');}, 1500);
},
error: function(){
//alert("failure");
setTimeout(function(){
$modal
.find('.modal-body')
.html('<div class="alert-show-failed"><img src="../../../public/assets/img/icons/failed.fw.png" />There was an error processing this request!</div>');}, 1500);
}
});
});
The modal loads fine, and it finds the status page fine, but nothing actually happens in the controller: (I hard coded the 2 in there to test it.
public function postStatus()
{
DB::table('users')
->where('id', 2)
->update(array('activated' => 0));
}
Not sure what I am missing. Any help is greatly appreciated.
I'd recommend making the changes suggested by #Arda, but I believe your jquery is incorrect. You are setting the key to be unique, and the value to be data.
Try this:
$("a.delete").click(function () {
var id = $(this).attr("id");
$.ajax({
type: 'post',
url: "{{URL::route('user_status')}}",
data: {'id' : id}
});
This requires using a blade template, but that's pretty good practice anyway.
Try like this:
First, make your route named for URLs to be more dynamic:
Route::post('users/status', array('as'='user_status', 'uses'=>'Controllers\UsersController#postStatus');
Then, alter your post jQuery (which I think is the error's source)
$("a.delete").click(function () {
var $id = $(this).attr("id");
$.post('{{URL::route('user_status')}}',
{
id: $id
}
);
});
And your controller method:
public function postStatus()
{
if(Request::ajax()) {
$thisID = Input::get('id');
DB::table('users')
->where('id', $thisID)
->update(array('activated' => 0));
}
}
Didn't try, but should work.

Is it possible to pass a variable to jquery when it starts or every action?

I'm super new to jquery and just stractching the surface of its awesomeness so sorry if this is a really basic question but I have a button on my site that once clicked posts some data to my server and I'm wondering how to provide jquery with data I want to be posted. I have made jquery refreshless forms but they have required the user to enter something which I post but now I want to send some data that is not entered or available on the webpage.
On my site, I have a button to click on if you want to 'follow' a topic. If you follow a topic I need to send a topic_id and your user id to my server to start the process but I think putting this on my web page for jquery to capture would be confusing to users(if I can't pass variables I plan to do this approach but hide the fields). The userid/topicid is avaiable to my template engine but I'm unsure how to pass the data over to the script.
Here's a example of my script
html:
<input type='button' value='Follow' id='btnFollow'>
follow.js:
$(document).ready(function () {
$('#btnFollow').click(function() {
//$("#btnFollow").prop('value', 'Following');
if ($(this).val() == 'Follow') {
$("#btnFollow").prop('value', 'Following')
} else if ($(this).val() == 'Following') {
$("#btnFollow").prop('value', 'Follow')
$.ajax({
type: 'POST',
url: '/follow_modification',
async: true,
data: {
fe1: "test"
},
complete: function(xmlRequestObject, successString){
ymmReceiveAjaxResponse(xmlRequestObject, successString);
}
});
}
})
});
How do I get info into the function from the html? So far all my javascripts have been triggered by clicks and then take data from the page.. if I have a variable in my template called {{ user_id }} how can I pass that to the script so when a click triggers a action then it'll have the data it needs to post?
<input type="button" value="Follow" id="btnFollow" data-topic="topicid" />
$('#btnFollow').click(function() {
var topic_id = $(this).attr('data-topic');
alert(topic_id);
});
<input type='button' value='Follow {{user-id}}' id='btnFollow' data-user="{{user-id}}">
on the html side, and
$(document).ready(function () {
$('#btnFollow').click(function() {
var following = $(this).attr("data-user");
if ($(this).val() == 'Follow') {
$("#btnFollow").prop('value', 'Following')
} else if ($(this).val() == 'Following') {
$("#btnFollow").prop('value', 'Follow')
$.ajax({
type: 'POST',
url: '/follow_modification',
async: true,
data: {
fe1: following
},
complete: function(xmlRequestObject, successString){
ymmReceiveAjaxResponse(xmlRequestObject, successString);
}
});
}
})
});
on the js side.
$(document).ready((function ( data ) {
// do some thing with somevalue
})( somevalue ));
or
$(document).ready(function ( ) {
var data = $('someSelector').val()
// do some thing with somevalue
});
or
var data = 'some value';
$(document).ready(function ( ) {
// do some thing with somevalue
});

Categories

Resources