Change wordpress shortcode with Javascript - javascript

let's say I have a wordpress shortcode, in a page (not post), like [display id="144,145,146"] and I want to add a link in the page like "click here to sort by views", so I can click the link and a javascript function can change the shortcode, putting different ids. Is it possible?

This is not possible without using AJAX unless you load you load all of the different short code options beforehand.
Preloading Shortcodes:
$('#change-shortcode').on('click', function() {
$('.shortcode-container').toggleClass('hidden');
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shortcode-container">[display id="144,145,146"]</div>
<div class="shortcode-container hidden">[display id="147,148,149"]</div>
<br/><br/>
<a id="change-shortcode">Click Here</a>
Fetching Shortcodes with AJAX:
// Add the "fetch_shortcode" AJAX action.
add_action('wp_ajax_nopriv_fetch_shortcode', 'fetch_shortcode');
add_action('wp_ajax_fetch_shortcode', 'fetch_shortcode');
function fetch_shortcode() {
if (isset($_POST['ids'])) {
$ids = implode(',', $_POST['ids']);
// ob_start and ob_get_clean will prevent the shortcode from displaying and instead will return the value to the $html variable.
ob_start();
do_shortcode('[display id="' . $ids . '"]');
$html = ob_get_clean();
wp_send_json_success($html);
}
}
On the front end, you would have this:
<div id="shortcode-container">[display id="144,145,146"]</div>
<br/><br/>
<a id="change-shortcode">Click Here</a>
<script>
$('#change-shortcode').on('click', function() {
// This is where you get to use the 'fetch_shortcode' action name that you created above.
data = {
ids: [147, 148, 149],
action: 'fetch_shortcode'
};
$.ajax({
url: "<?php echo admin_url('admin-ajax.php') ?>",
method: "POST",
data: data
}).done(function(response) {
$('#shortcode-container').html(response.data);
});
});
</script>

Related

Two target for one <a> tag and display two results in two different div

Student.php -here i am getting list of students from a specific Institution in a tag
<?php
if(isset($_POST['c_id'])) { //input field value which contain Institution name
$val=$_POST['c_id'];
$sql="select RegistrationId from `students` where `Institution`='$val' ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$number=$row['RegistrationId'];
?>
<a href='<?php echo "index.php?StudentID=$number"; ?>' target="index" id="link">
//getting student id in the dynamic link
<?php echo "$number";
echo "<br/>";
}}
?>
<div id="index" name="index"> </div>
<div id="Documents"> </div>
<script>
$(document).on('change', 'a#link', function()
{
$.ajax({
url: 'Documents.php',
type: 'get',
success: function(html)
{
$('div#Documents').append(html);
}
});
});
</script>
In index.php - I am Getting students details based on $_GET['StudentID'] ('a' tag value)
<?php
$link=$_GET['StudentID'];
$sql = "select StudentName,Course,Age,Address from `students` where `RegistrationId`="."'".$link."'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['StudentName']."<br/>";
echo $row['Course']."<br/>";
echo $row['Age']."<br/>";
echo $row['Address']."<br/>";
}
?>
In Documents.php -I am getting documents related to the speific student selected in 'a' tag
$link=$_GET['StudentID'];
$qry = "select Image,Marksheet from `documents` where `RegistrationId`='$link'";
$result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$image = $row["Image"];
$image1 = $row["Marksheet"];
echo '<embed src='. $image.'>';
echo ' <object data='. $image1.'width="750" height="600">';
echo ' </object>';
}
On click of student id i am trying to get result from index.php to div()
and result from Documents.php to div()
(i.e)two target for one click in tag
My code only take me to the index.php file result in a new Window
Please Help me to solve this problem
(sorry if my question seems silly i am new to php)
Update:
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
});
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
From your question, it seems that you want to load the two results, one from index.php and one from Documents.php in two separate divs on the same page when the link is clicked.
But you're using a change event on the link, not a click event. The change event is not fired when the link is clicked, so JavaScript does not get executed and the page loads to the URL specified in the href attribute of the link. So first you need to change $(document).on('change') to $(document).on('click').
Furthermore, since you want two results to load - one from index.php and one from Documents.php, you'll need to create two ajax requests, one to index.php and the other for Documents.php. In the success function of each of the ajax requests, you can get the response and put it in the corresponding divs.
In addition to this, you'll also need to prevent the page from loading to the new page specified in href attribute when the link is clicked, otherwise the ajax requests fired on clicking the link will get lost in the page load. Thus, you need to add a e.preventDefault(); to your onclick event handler like this:
$(document).on('click', 'a#link', function(e) {
// Stop new page from loading
e.preventDefault();
// Two ajax requests for index.php and Documents.php
});
Update: You don't need to add two click handlers for each ajax request. Inside one click handler, you can put both the ajax requests.
Also your event handlers won't register if you're adding them before jQuery, or if you're adding them before the DOM has loaded. So move your code to bottom of the HTML page, just before the closing </body> tag.
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link
You can change your <a> tag like below :
..
Then , in your jquery code do below changes :
$(document).on('click', 'a.link', function(e) {
var StudentID = $(this).attr("data-id") //get id
console.log(StudentID)
e.preventDefault();
$.ajax({
url: "details.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
call_next_page(StudentID);//next ajax call
}
});
});
function call_next_page(StudentID) {
$.ajax({
url: "index.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
}
});
}
And then at your backend page use $_POST['StudentID'] to get value of student id instead of $_GET['StudentID'];

Get id from grid in PHP

I am using Php for back end development.
I have grid in Html which contains bunch of records.
Now what i want is , i want to get booking id on click(on click event has
java script function) on Booking
Number(As show in below image.) which has hyper link.
This is the java script function to get booking id on click of booking Number
$('.bu').on('click', function () {
var Id = $(this).data("id");
$.get( "mypage.php?id=" + Id );
document.getElementById("idvalue").value = Id;
var inputdaata=document.getElementById("idvalue").value;
**From above javascript already getting Booking id.
Now i have to use that booking id in php.
This is for grid in Html**
<td><a href="" name="abc"
class ="bu" data-toggle="modal"
data-target="#myModal1"
data-id="<?php echo $json1[$i]
['bookingid']; ?>"><?php echo
$json1[$i]['bookingNumber'];?>
</a></td>
Thanks in advance.
<script type="text/javascript">
function gocedula(text) {
var form_data = {
is_ajax: 1,
cedula: text
};
$.ajax({
type: "POST",
url: "getCedula.php",
data: form_data,
success: function(response) {
window.location.replace("http://stackoverflow.com");
}
});
}
</script>
<a onclick="gocedula('.$valor.')">Booking Number</a>
On the Other page use
$_REQUEST["cedula"];

Show content from external php file with GET parameter inside div

Im struggling to make links for files appear on same page inside DIV.
Simply nothing happens when I a href click link, no links appear.. however I can see links when I'm going directly to example.com/ajaxdetails.php?id=OneOftheIDs
Here is mine main HTML file:
<script src="/jquery-1.11.2.min.js"></script>
<script>
function getSummary(id)
{
$.ajax({
type: "GET",
url: "detailsajax.php",
data: "id=" + id,
success: function(data) {
$('#returned-details').html(data);
}
});
}
</script>
PHP part:
foreach ($pirmiRezai as $key=>$rezultatas)
{ $i++;
echo '<div class="r">
'.$rezultatas['desc'].'
Some unrelated php code here
<div id="returned-details"></div>
</div>';
if($i>=10)
break;
}
And the detailsajax.php file contains simple textarea with returned download link from database for specific ID (detailsajax.php?id=random). I need that html code with returned download link to appear inside returned-details DIV next to a href that was clicked.
Hope its clear.
First of all id's should be always unique or else u could replace it with the class attribute.In your case something like this might help u mate.. :)
Script
<script src="/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function() {
$(".r a").on("click", function() {
var id = $(this).attr("myId");
$.ajax({
type: "GET",
url: "detailsajax.php",
data: "id=" + id,
context: this,
success: function(data) {
$(this).next('.returned-details').html(data);
}
});
});
});
</script>
PHP
foreach ($pirmiRezai as $key=>$rezultatas)
{ $i++;
echo '<div class="r">
'.$rezultatas['desc'].'
Some unrelated php code here
<div class="returned-details"></div>
</div>';
if($i>=10)
break;
}

jQuery not executed on page load

I'm building an ajax upload with an editing function (rotate, zoom and crop), and I'm using guillotine by matiasgagliano (https://github.com/matiasgagliano/guillotine) for this. My problem is that after upload the user get redirected to the editing page through ajax, but when landing on that page I always have to refresh the page in browser for the image to load.
I've tried auto-reloading, both through js and php, but that doesn't help, neither does adding a button to load the same url again. Only refresh from browser button (tested in several browsers) works. I've tried implementing jquery.turbolinks, but that stopped guillotine functions from working.
I'm loading the guillotine.js in head section after jQuery, and have the function in bottom before body tag.
Any tip or help would be appreciated. Thx
Here is some of the code:
HTML:
<div class='frame'>
<img id="id_picture" src="identifications/<?php echo $id_url; ?>" alt="id" />
</div>
<div id='controls'>
<a href='javascript:void(0)' id='rotate_left' title='<?php echo $word_row[434]; ?>'><i class='fa fa-rotate-left'></i></a>
<a href='javascript:void(0)' id='zoom_out' title='<?php echo $word_row[436]; ?>'><i class='fa fa-search-minus'></i></a>
<a href='javascript:void(0)' id='fit' title='<?php echo $word_row[438]; ?>'><i class='fa fa-arrows-alt'></i></a>
<a href='javascript:void(0)' id='zoom_in' title='<?php echo $word_row[437]; ?>'><i class='fa fa-search-plus'></i></a>
<a href='javascript:void(0)' id='rotate_right' title='<?php echo $word_row[435]; ?>'><i class='fa fa-rotate-right'></i></a>
</div>
Js:
<script type='text/javascript'>
jQuery(function() {
var picture = $('#id_picture');
picture.guillotine({
width: 240,
height: 180
});
picture.on('load', function(){
// Initialize plugin (with custom event)
picture.guillotine({eventOnChange: 'guillotinechange'});
// Display inital data
var data = picture.guillotine('getData');
for(var key in data) { $('#'+key).html(data[key]); }
// Bind button actions
$('#rotate_left').click(function(){ picture.guillotine('rotateLeft'); });
$('#rotate_right').click(function(){ picture.guillotine('rotateRight'); });
$('#fit').click(function(){ picture.guillotine('fit'); });
$('#zoom_in').click(function(){ picture.guillotine('zoomIn'); });
$('#zoom_out').click(function(){ picture.guillotine('zoomOut'); });
$('#process').click(function(){
$.ajax({
type: "POST",
url: "scripts/process_id.php?id=<?php echo $emp_id; ?>&user=<?php echo $user; ?>",
data: data,
cache: false,
success: function(html)
{
window.location = "<?php echo $finish_url; ?>";
}
});
});
// Update data on change
picture.on('guillotinechange', function(ev, data, action) {
data.scale = parseFloat(data.scale.toFixed(4));
for(var k in data) { $('#'+k).html(data[k]); }
});
});
});
</script>
Make sure both the DOM-tree and the script is loaded.
var script = document.createElement('script');
script.src = "guillotine-master/js/jquery.guillotine.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function () {
jQuery(function() {
var picture = $('#sample_picture');
picture.guillotine({
width: 240,
height: 300
});
picture.on('load', function(){
// Initialize plugin (with custom event)
picture.guillotine({eventOnChange: 'guillotinechange'});
// Display inital data
var data = picture.guillotine('getData');
for(var key in data) { $('#'+key).html(data[key]); }
// Bind button actions
$('#rotate_left').click(function(){ picture.guillotine('rotateLeft'); });
$('#rotate_right').click(function(){ picture.guillotine('rotateRight'); });
$('#fit').click(function(){ picture.guillotine('fit'); });
$('#zoom_in').click(function(){ picture.guillotine('zoomIn'); });
$('#zoom_out').click(function(){ picture.guillotine('zoomOut'); });
$('#process').click(function(){
$.ajax({
type: "POST",
url: "scripts/process_img.php?id=<?php echo $emp_id;?>&user=<?php echo $user; ?>",
data: data,
cache: false,
success: function(html)
{
window.location = "<?php echo $finish_url; ?>";
}
});
});
// Update data on change
picture.on('guillotinechange', function(ev, data, action) {
data.scale = parseFloat(data.scale.toFixed(4));
for(var k in data) { $('#'+k).html(data[k]); }
});
});
});
};
You're incorrectly loading Guillotine twice, before and inside the onload handler.
You should initialize Guillotine after the image is loaded and just once:
var picture = $('#sample_picture');
picture.on('load', function(){
picture.guillotine({
width: 400,
height: 300,
eventOnChange: 'guillotinechange'
});
...
});
If after fixing this you still get any troubles, be aware that if an image is already loaded the onload event never gets triggered, even if the image is not present but cached it might load before you set the handler for onload.
It's not that jQuery doesn't execute on page load but possibly that the onload event never gets triggered.
To prevent this you can force the image to be loaded, place this after setting the onload handler:
// Force reloading if completed or if undetermined.
if (picture[0].complete !== false) {
// 1x1 gif
gif = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='
// Save original src, replace with the gif and reload the original src
src = pic.src; pic.src = gif; pic.src = src
}
I hope this solves your problem, don't lose your faith in Guillotine ;)
Thanks for the respond guys, but i was unable to solve it.
As soon as I wrapped any function around the jQuery function, the functions within it stopped working.
I ended up using Jcrop instead of Guillotine, and built a rotating function that can be used before cropping. Now everything is working well.
Link to Jcrop: http://deepliquid.com/content/Jcrop.html

PHP removing everything after HTML tags

I have a contenteditable div like this:
<form>
<div name="new_post" class="post" contenteditable="true"></div>
<button type="submit">Submit</button>
</form>
The contenteditable div allows bold and italic tags, but no other tag.
My issue is that if the user types something like Hello there <u>world</u>!, it will save in the database as Hello there. It seems to remove everything after the tags and I don't know why.
I'm using AJAX and PHP to handle posts, so here's the rest of the code.
Ajax:
$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
alert($('.post').html()); // added this to debug it. This prints "Hello there <u>world</u>!"
$.ajax({
url: 'php/post.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize() + "&post_field=" + $('.post').html(),
success: function(data) {
alert(data.message);
}
});
});
});
PHP:
<?php
$post = $_POST["post_field"];
// query to insert post into database goes here
$array = array('message' => $post);
echo json_encode($array);
?>
Please help!
Change:
$('.post').html()
to:
encodeURIComponent($('.post').html())
The HTML characters need to be encoded in a URL parameter.

Categories