Shortcode within Ajax - php

So, I have a following ajax setup:
PHP: menu.php
<!--Menu-->
<div class="rh_menu">
Front
Other
</div>
<!--Content Div-->
<div class="rhp_hide">
<div class="rrp_container is-active" id="rhp_front_rhp_id">
<div class="spinner is-active"></div>
</div>
<div class="rrp_container" style="display:none;" id="rhp_front_ca_other_id">
<div class="spinner"></div>
</div>
</div>
01_house_rhp_id.php <-- First button which is called by the Ajax
<div class="my_shortcode">
<?php echo do_shortcode('[some_shortcode]'); ?>
</div>
Function.php
// load the javascript
wp_enqueue_script( 'ajax-script', '/03.includes/js/rh_ajax.js', array('jquery') );
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
//Ajax call for House front page
function my_tab_callback() {
$template_part_path = 'page-parts/01_house_' . $_GET['id'];
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_my_tab', 'my_tab_callback');
add_action('wp_ajax_nopriv_my_tab', 'my_tab_callback');
rh_ajax.js
//To hide other divs
jQuery('.rh_menu a').click(function() {
var rh_id = jQuery(this).attr('id');
jQuery('[id^="rhp_front_"]').hide();
jQuery('#rhp_front_' + rh_id).show();
});
//To initiate first click
jQuery(window).load(function() {
jQuery("#rhp_id" ).trigger( 'click' );
return false;
});
//Ajax call
jQuery(document).ready(function() {
jQuery('.rh_menu a').click(function(e) {
e.preventDefault();
var tab_house_id = jQuery(this).attr('id');
jQuery.ajax({
type: "GET",
url: ajax_object.ajax_url,
dataType: 'html',
data: ({ action: 'my_tab', id: tab_house_id}),
success: function(data){
jQuery('#rhp_front_' + tab_house_id).html(data);
console.log(data);
},
error: function(data)
{
alert("Nope");
console.log(data);
return false;
}
});
});
});
So, it looks like when a shortcode is parsed by ajax, it is not recognized and gave me 500 server error.
How can I modify above setting so that I can use the shortcode within ajax setting?
Thanks!

Related

How to correctly make return button in Ajax?

I created a side panel with buttons. On click I load specific php file assigned to each button. How to correctly add functionality that will return us to the default button list?
HTML:
<div class="sidemenu">
<div class="content">
<button data-content="first">Load first content</button>
<button data-content="second">Load second content</button>
<button data-content="third">Load third content</button>
</div>
</div>
Script:
jQuery( document ).ready( function( $ ) {
$( '.sidemenu button' ).on('click', function( event ) {
event.preventDefault();
var content = $( this ).data( 'content' );
$( '.sidemenu .content' ).empty();
$.ajax( {
url: ajaxobject.ajaxurl,
type: 'get',
dataType: 'html',
data: {
action: 'sidemenu_content',
content: content,
},
success: function( result) {
$( '.sidemenu .content' ).append( result );
console.log(result);
}
});
});
});
PHP:
function sidemenu_content() {
if( isset( $_GET['content'] ) ) {
$content= $_GET['content'];
if ( $content == 'first' ) {
require_once( get_template_directory() . '/sidemenu/first.php' );
} elseif ( $content == 'second' ) {
require_once( get_template_directory() . '/sidemenu/second.php' );
} elseif ( $content == 'third' ) {
require_once( get_template_directory() . '/sidemenu/third.php' );
}
}
wp_die();
}
I tried to add <button data-content="return">Return</button> in each of three php files and in the sidemenu_content function:
if ( $content == 'return' ) {
require_once( get_template_directory() . '/sidemenu/return.php' );
}
But unfortunately it doesn't work.
UPDATE
Almost everything works with this code. "Return" button appear but onclick doesn't really return to the button list.
var backup;
jQuery( document ).ready( function( $ ) {
$('.sidemenu button').on('click', function( event ) {
event.preventDefault();
var content = $( this ).data( 'content' );
$.ajax( {
url: ajaxobject.ajaxurl,
type: 'get',
dataType: 'html',
data: {
action: 'sidemenu_content',
content: content,
},
success: function( result) {
backup = $( '.sidemenu .content' ).innerHTML;
$( '.sidemenu .content' ).innerHTML = result;
$( '.sidemenu .content' ).empty();
$( '.sidemenu .content' ).append( '<button class="return">Return</button>' + result );
$( '.sidemenu button.return').on('click', function( event ) {
event.preventDefault();
$( '.sidemenu .content' ).innerHTML = backup;
})
}
})
})
});
I think it's good for performance if when clicked on return button browser doesn't send AJAX to get already have code. I add hidden block to backup buttons for reuse after click on return
<div class="sidemenu">
<div class="content">
<button data-content="first">Load first content</button>
<button data-content="second">Load second content</button>
<button data-content="third">Load third content</button>
</div>
<div class="hidden" style="display:none;"></div>
</div>
And jQuery:
jQuery( document ).ready( function( $ ) {
$('.sidemenu button').on('click', function( event ) {
event.preventDefault();
var content = $( this ).data( 'content' );
$.ajax( {
url: ajaxobject.ajaxurl,
type: 'get',
dataType: 'html',
data: {
action: 'sidemenu_content',
content: content,
},
success: function( result) {
$( '.sidemenu .hidden' ).append($( '.sidemenu .content button' ));
$( '.sidemenu .content' ).html(result);
$( '.sidemenu .content' ).append('<button class="return">Return</button>');
$('.sidemenu button.return').on('click', function( event ) {
event.preventDefault();
$( '.sidemenu .content' ).empty();
$( '.sidemenu .content' ).append($( '.sidemenu .hidden button' ));
})
}
})
})
});
How it Works:
Before empty all data I backupped and after successfull ajax response I empty data end append response data. After response data I append return button. If you click this button all data in .content empty and append backupped code.
P.S You can optimize this code

Ajax. How to unappend on second click?

I have the following ajax script
$(document).ready(function(){
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass");
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
alert(data);
$(this).closest('.form-group').next('.userInfo').append(data);
}
});
});
})
Its posting data in this html code
<?php if($usuarios[$i]["IdRol"] == '2'){ ?>
<tr>
<td colspan="2">
<!-- -->
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="ver"></label>
<div class="col-md-4">
<button data-dnipass="<?= $dni?>" class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
</div>
</div>
<table id ="<?= $i?>" class="table userInfo" data-formpost="<?= $dni?>"></table>
</td>
</tr>
<?php } ?>
How do I make that on second click it deletes the data? , and then on third it posts it again, on fourth deletes.... and so..
EDIT: Progress using ramraider code
$(document).ready(function(){
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass");
state = $(this).closest('.form-group').next('.userInfo').data("state"); //always picking 0, instead of the new generated 1
console.log(state);
state = 1-parseInt(state);
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
switch( state ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
$(this).closest('.form-group').next('.userInfo').attr("data-state","1");
break;
case 0:
$(this).closest('.form-group').next('.userInfo').remove();
$(this).closest('.form-group').next('.userInfo').attr("data-state","0");
break;
}
}
});
This is how my data-state tag looks on no click
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="0"></table>
And this is how it looks on first click
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="1"></table>
And this is how it looks from second click and all of the next ones
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="1"></table>
It basically stops changing, but im not sure why, seems that state = $(this).closest('.form-group').next('.userInfo').data("state"); start to always pick 0, instead the new generated 1
EDIT 2:
Ramraiders suggested answer works properly, I was missing that the data-state was moved to button
You can set a dataset attribute ( on the button ) that you toggle between 1 and 0 - the value can then be used to fork the logic in your ajax function. For example, set data-state=0 and then toggle it's value in the click handler and test that value in the callback
<button data-dnipass='<?php echo $dni;?>' data-state=0 class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
<!-- note the data-state attribute that will be toggled! -->
$(document).ready(function(){
$( ".ver" ).click( function(event){
event.preventDefault();
event.target.dataset.state = 1 - event.target.dataset.state;
var pulsado = $(this).data("dnipass");
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:pulsado
},
success: (data) => {
switch( parseInt( event.target.dataset.state ) ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
break;
case 0:
/* delete */
break;
}
}
});
});
})
I don't use jQuery so I am not familiar at all with its syntax or intricacies but this appears to do what you want. I have put it together into a working demo - obviously some of the code you see is mickey mouse but should give the idea.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
echo "gigantic mouse strangles elephant";
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>jQuery-toggle append/delete</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(document).ready(function(){
$( ".ver" ).click( function(event){
event.preventDefault();
event.target.dataset.state = 1 - event.target.dataset.state;
var pulsado = $(this).data("dnipass");
$.ajax({
type: 'POST',
url: location.href, //'adminVerLineas.php',
data: {
dni:pulsado
},
success: (data) => {
switch( parseInt( event.target.dataset.state ) ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
break;
case 0:
/* delete */
$(this).closest('.form-group').next('.userInfo').text('');
/* or, slightly better IMO */
// $(this).closest('.form-group').next('.userInfo').html('<tr><td></td></tr>');
break;
}
}
});
});
})
</script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<div class="form-group">
<label class="col-md-4 control-label" for="ver"></label>
<div class="col-md-4">
<button data-state=0 data-dnipass="BANANA APPLE ORANGE STRAWBERRY" class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
</div>
</div>
<table id ="XYZABC123" class="table userInfo" data-formpost="BANANA APPLE ORANGE STRAWBERRY"></table>
</td>
</tr>
</table>
</body>
</html>
Create two click handler such as:
$(".ver-post").click(function(event) {...}
and
$(".ver-delete").click(function(event) {...}
in the success of each replace the class.
success: (data) => {
...
$(this).addClass('ver-delete').removeClass('ver-post');
}
Haven't tested it yet but something like this should work.
Like #urfusion mention it, counter is probably the easiest solution:
$(document).ready(function(){
count_click = 0; // new row counter
$(".ver").click(function(event){
count_click += 1; // new row update counter
var pulsado = $(this).data("dnipass");
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
alert(data);
if (count_click % 2 == 0) { // second, fourth, sixth...
// TO DO - delete data
} else { // first, third...
// TO DO - add data
}
$(this).closest('.form-group').next('.userInfo').append(data);
}
});
});
})

HTML format not getting proper in jquery ajax response

I have tried to get response using jQuery ajax call but HTML div is not return in ajax response in WordPress.
Following is my HTML
<form action="" name="article_search" id="article_search">
<input type="search" name="search_article_post" class="form-control search_article_post" placeholder="search">
<button type="button" name="search_article" class="project-search-icon search_article">
<img src="<?php echo THEME_DIR; ?>/images/project-search-icon.png">
</button>
</form>
<div class="testimonials-slider"></div> // Ajax output display in this div
Following is my ajax call.
jQuery(document).ready(function(){
jQuery(".search_article").on("click",function(){
var search_by_name = jQuery('.search_article_post').val();
var data = {
action: 'get_articles_details',
search_by_name:search_by_name
};
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
jQuery.ajax({
method: 'post',
url:ajaxurl,
dataType: "html",
data: data,
beforeSend: function (response) {
jQuery("#loading").show();
},
complete: function (response) {
jQuery("#loading").hide();
},
success: function (response) {
jQuery('.testimonials-slider').html(response);
console.log(response)
},
});
return false;
});
});
Following script is written in functions.php in wordpress theme for ajax call
add_action('wp_ajax_get_articles_details' , 'get_articles_details');
add_action('wp_ajax_nopriv_get_articles_details', 'get_articles_details');
function get_articles_details(){
$serch_by_name = isset($_POST['search_by_name']) && !empty($_POST['search_by_name']) ? $_POST['search_by_name'] : '';
$post_arg =array( 'posts_per_page' => -1,
's' => esc_attr( $serch_by_name ),
'post_type' => 'post',
'orderby' =>$serch_by_name,
'order'=>'desc'
);
$get_articles = new WP_Query($post_arg);
global $post;
if($get_articles->have_posts()){
while($get_articles->have_posts()) : $get_articles->the_post();
$html .='<div class="slider-content"><div class="article-content bg-white">';
$html .='<div class="article-img">'.the_post_thumbnail().'</div>';
$html .='</div></div>';
?>
<?php
endwhile;
}
echo $html;
}
I get following output
<img width="481" height="321" src="image_path" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="image_path" sizes="(max-width: 481px) 100vw, 481px" />
<div class="slider-content"><div class="article-content bg-white"><div class="article-img"></div></div>
I mean image is not add in div class article-img it's added before class. so in response of HTML in not getting proper might be missing something.
You need to write
echo json_encode($html);exit;
or
echo $html;exit

how to combine an id div and a php id

I don't know the specifications of PHP and an ID DIV. Here's my question :
Can I put in the same time an ID DIV named #modal and an ID PHP RETURN ?
while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo'
<div class="row print">
<div class="col s12 m4">
<div class="card">
<div class="card-image">
<img data-tags="print" class="activator" src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '">
<i class="material-icons">add</i>
</div>
<div class="card-content">
<span class="card-title">'.$contents_print['nom_projet'].'</span>
<p>'.$contents_print['detail_projet'].'</p>
</div>
</div>
</div>
</div>';
}
This is my jquery ajax code :
$(document).ready(function(){
$('.materialboxed').materialbox();
});
$( document ).ready( function () {
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id=3',
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
}
} );
// the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
$( '.modal' ).modal();
} );
In my ajax code : the line url: 'core/libs/contents-services.php?action=getFilterContent&id=3', I have to use the id from the php/mysql request
I would like to make a link like this :
url: 'core/libs/contents-services.php?action=getFilterContent&id='.$_GET['id'].',
I hope I'am clear
Thanks for your help
http://portfolio.rabahbook.fr to see my working's site
As I understand you get an Id from response and trying to assign it to ajax href. If this is your case, you can do something as below(please note the url_id variable.):
var url_id =3;
$( document ).ready( function () {
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
url_id = response.url_id;/// get url id from response and assign it to
//your href
}
});
// the "href" attribute of the modal trigger must specify the modal ID
//that wants to be triggered
$( '.modal' ).modal();
} );
</script>
$('.post .modal-action').click(function(e){
e.preventDefault();
var id_projet= $(this).data('id_projet');
var $hidennDiv = $('#' +id_projet);
// do your ajax and whatever you want to do with the hidden div
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id='+id_projet,
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
id_projet = reponse.id_projet;
}
} );
$( '.modal' ).modal();
});
This works for me
Thanks all to taking time to anwser to me !

Nivo Slider dose not load the Ajax response from PHP file

I'm trying import images to HTML using PHP, but NivoSlider not loaded that.
I looked for the cause of the problem.
I am printing a alert message of response and the right.
Here is the HTML and AJAX query:
<div id="workcontent" class="pcontent" style="display:none;">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
</div>
</div>
<script>
$(document).ready(function() {
var wl = $('#worklist div');
wl.on('click', function(){
var name = $(this).attr('id');
console.log(name);
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response);
alert(response);
});
});
});
</script>
<div id="back"></div>
<div id="backcontainer">
<div id="back">
Back
</div>
</div><!--End backcontainer-->
</div><!--End content-->
And here is the other jQuery:
<script>
$(document).ready(function() {
$('#slider').nivoSlider(function(){alert('OK');});
});
</script>
This alert don't show! ):
Finally, here is the PHP code:
<?php
if (isset($_POST["data"])){
if ($_POST["data"] == "") {
echo "data ures";
} else {
$data = $_POST["data"];
$fname = "content/".$data."/*.*";
$files = glob($fname);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" data-thumb="'.$num.'">';
}
}
} else {
echo "nem jott data";
}
?>
Sorry for my bad english
NivoSlider doesn't take a function as an argument.
Also .nivoSlider() is probably called before the AJAX call returns it's response.
A better solution would be:
$(document).ready(function() {
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response).nivoSlider( {} );
});
});
Now you can be fairly sure #slider contains the images from the response body so NivoSlider can act on them.

Categories