HTML format not getting proper in jquery ajax response - php

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

Related

Error: cannot call methods on draggable prior to initialization; attempted to call method 'destroy'

I am facing this error when trying to save a cover photo i repositioned. i am getting the error. cannot call methods on draggable prior to initialization; attempted to call method 'destroy'
rep_save: function() {
var _self = this;
if ($.isNumeric(_self.rep_position)) {
_self.submitting = true;
$(_self.$el).find('img.original-cover').draggable('destroy');
$.ajax({
url: "<?php echo cl_link("native_api/settings/save_profcover_rep"); ?>",
type: 'POST',
dataType: 'json',
data: {position: _self.rep_position},
}).done(function(data) {
if (data.status == 200) {
cl_bs_notify("<?php echo cl_translate("Your changes has been successfully saved!"); ?>");
setTimeout(function() {
SMColibri.spa_reload();
}, 1200);
}
else {
_self.submitting = false;
SMColibri.errorMSG();
}
});
}
}
<div class="user-profile__header-cover" v-show="rep_opened == true" id="rep-area">
<img class="original-cover" src="<?php echo cl_get_media($cl['prof_user']['cover_orig']); ?>" alt="IMG">
<div class="cover-corrector">
<div class="cover-corrector__body">
<button title="<?php echo cl_translate('Save changes'); ?>" class="cover-corrector__btn" v-on:click="rep_save" v-bind:disabled="submitting">
<?php echo cl_icon('save_inline'); ?>
</button>
<button title="<?php echo cl_translate('Cancel'); ?>" class="cover-corrector__btn" v-on:click="rep_end" v-bind:disabled="submitting">
<?php echo cl_icon('close'); ?>
</button>
</div>
</div>
</div>

php variable value in a while loop for each row

I have a cancel button on each row of a table that is autopopulated in a while loop.
The $id resolves correctly but when I click on the cancel button all the active rows are modified. I only want the row that is concerned to be modified.
So in a while loop in php:
<tr id="dataTable">
<td id="nom"><?php echo $nom;?></td>
<td id="statut"><?php echo $statut;?> </td>
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" href="#" title="Annuler"
onclick="document.write('<?php
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$id."'";
$resultatannuler = $connexion->query($queryannuler); ?>'); location.reload(); 'return false';">Annuler</a>
</td>
</tr>
My problem is the 'statut' column is being updated for all the rows and not just the row where I click on the cancel button. Thanks if you can help.
UPDATE
I have tried to implement your different advices by using ajax. It's tough. I didn't specify in the original post that I am using a Wordpress framework. So I have modified #ssurli code to take into account wordpress
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" class="button delete" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
</td>
<script>
function cancelRecord(id) {
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {id:id},
action: 'delete_rdv',
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
console.log('The function is hooked up');
location.reload();
console.log('The function is hooked up2');
}
});
}
AND in my functions.php file
add_action( 'wp_ajax_delete_rdv', 'delete_rdv' );
add_action( 'wp_ajax_nopriv_delete_rdv', 'delete_rdv' );
function delete_rdv() {
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
}
I'm stuck on the very first hurdle.
The console is sending an error message :
admin.php?page=plugin-voc:1 Uncaught ReferenceError: cancelRecord is not defined
But my cancelRecord function is right after my button call so I don't understand this error.
Here the working code.
Update your table row as below:
<tr id="dataTable">
<td id="nom"><?php echo $nom;?></td>
<td id="statut"><?php echo $statut;?> </td>
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
</td>
</tr>
Add below js scripts to bottom of your html page. Include jquery cdn file only if not add to page already.
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
function cancelRecord(id) {
$.ajax({
type: 'post',
url: 'cancel.php', //use actual directory path, if not kept in root directory
data: {id:id},
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
location.reload();
}
});
}
</script>
Add PHP file having PHP code having DB query responsible for cancelling the record.
//cancel.php
<?php
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
Hope it will work for you. Feel free if you have any further query.
This was the original html request
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" class="button delete" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
The javascript function was not defined when I put it in the same file as the php. I moved into the plugin index.js file and most importantly I moved this line:
action: 'delete_rdv',
into data {}
data: {
action: 'delete_rdv',
id:id},
Here is the complete javascript code:
jQuery( document ).ready(function($){ $('.button.delete').on('click', function(){ let id = $(this).attr('id'); cancelRecord(id); }); });
function cancelRecord(id) {
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {
action: 'delete_rdv',
id:id},
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
location.reload();
}
});
}
The ajax calls the function delete_rdv which I put in the functions.php file
add_action( 'wp_ajax_delete_rdv', 'delete_rdv' );
add_action( 'wp_ajax_nopriv_delete_rdv', 'delete_rdv' );
function delete_rdv() {
$queryannuler = "UPDATE wp_RDV SET statut = 'Annulé' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
}
Special thanks to #jeprubio for kinda forcing to look the ajax way and to #sssurii for posting his code and answering my question.

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 !

Shortcode within Ajax

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!

Loading a facebox modal window after an ajax request

this is what i have in the head tags of my html page to load the facebox plugin:
<!-- This is for the facebox plugin to work -->
<link href="<?php echo base_url();?>styles/facebox/src/facebox.css" media="screen" rel="stylesheet" type="text/css" />
<script src="<?php echo base_url();?>styles/facebox/lib/jquery.js" type="text/javascript"> </script>
<script src="<?php echo base_url();?>styles/facebox/src/facebox.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox({
loadingImage : "<?php echo base_url();?>styles/facebox/src/loading.gif",
closeImage : "<?php echo base_url();?>styles/facebox/src/closelabel.png"
})
})
</script>
this is the code for my div
<?php if(isset($$j)) : foreach($$j as $row) : ?>
<div class="single-result" id="single-result">
<div class="name"><?php echo $row->Name; ?></div>
<div class="description"><?php echo $row->Description; ?></div>
</div>
<?php endforeach; ?>
<?php else : ?>
error here
<?php endif; ?>
what i am wanting, is some ajax code that calls a function when the user clicks on the div id="single-result" so that it makes an ajax call to a php controller that gets the data from the database and then loads the view into a facebox modal window.
The part i am unsure about is how to make it load into a facebox modal window, l know how to use ajax calls to make it send data to a file and then load a view into a certain div on the page, l just want it to load it into the modal window instead of a certain div on the page.
Is this possible at all? (also i am using codeigniter for the php framework)
here is my ajax code which would load the ajax request results into the content-right div when the user clicks on div.
<script type="text/javascript">
$("#single-result").click(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#content-right').html(msg);
}
});
return false;
});
</script>
<!-- END -->
how do i modify this code above to make it work with going into a facebox modal window? I know facebox provides this code below, but i have no idea what to do with it?
jQuery.facebox(function() {
jQuery.get('code.js', function(data) {
jQuery.facebox('<textarea>' + data + '</textarea>')
})
})
It's not really clear what you're after...
If what you want is to have the data returned from the ajax POST to be populated into a facebox, simply call facebox on the success callback of the ajax post:
$("#single-result").click(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
jQuery.facebox(msg);
})
});
alternatively, it looks like if you want the facebox loading graphics while the post is processed, you can wrap the ajax POST in facebox function:
$("#single-result").click(function() {
jQuery.facebox(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
jQuery.facebox(msg);
})
});
})
})

Categories