Wordpress page using ajax and pagination - javascript

I have my ajax running perfectly and now i need my pagination to work on the page. I have no idea how to start.. another problem is i need it to bring in 16 posts at a time.. PLease help
How do i change this into a next and previous pagination
html below
<ul id="sermonserie1">
while ( $query->have_posts() ) : $query->the_post();
Next page
<?php endwhile;?>
</ul>
ajax page
global $post, $wpdb;
if(isset($_POST['pagi'])) {
if( isset($_REQUEST["locations"]) || isset($_REQUEST["speaker"]) || isset($_REQUEST["topic"])) {
if ($_REQUEST["locations"]!='#' ) {
$locat_termy = array('sermons', $_REQUEST['locations']);
} else {
$locat_termy = array('sermons');
$locations_resource = get_term_children( 16, 'category' );
foreach ( $locations_resource as $child_location ) {
$location_term = get_term_by( 'id', $child_location, 'category' );
$locat_termy[] .= $location_term->slug;
}
//print_r($locations_resource);
//print_r($locat_termy);
}
$all_args = array(
'post_type' => 'resources',
'author' => $speak,
'posts_per_page' => -1,
'tax_query' => array (
'relation' => 'OR',
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => $topicids,
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $locat_termy,
),
) ,'date_query' => $thedate
);
$query = new WP_Query( $all_args );
//print_r($query);
//$eevents = array();
//print_r($query);
while ( $query->have_posts() ) : $query->the_post();?>
<?php endwhile; ?>
<?php }
} ?>
this is my js
jQuery('.button.load-more').live('click', function() {
var pagenum = parseInt(jQuery(this).attr('page'))+ 1;
jQuery.ajax({
type: 'post',
url: 'http://cj.co.za/back/page/'+pagenum+'',
data: {
pagi:1,
},
success: function(data) {
jQuery('#sermonserie1').append(data);
jQuery('.button.load-more').attr('page', pagenum)
},
error: function() {
jQuery('.button.load-more').text('No page');
}
});
});

Related

Form events symfony

Hi guys i tried many things to solve this but i dont really know how this works.
What i want:
-Change the list of operators after change the fieldcampaign (done).
-Change the value typeform from text to filetype and from filetype to texttype depending of which operator i select.
Persist whats inside the value input if its a texttype.
This is my Form
namespace App\Form\Type;
class FiltercampaignvalueType extends AbstractType
{
private $campaign;
private $filtergroup;
private $class;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->campaign = $options['attr']['campaign'];
$this->filtergroup = $options['attr']['filtergroup'];
$this->class = 'row';
// dd($this);
$builder->add('fieldcampaign', EntityType::class, array(
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.campaign = :campaign')
->setParameter('campaign', $this->campaign)
->orderBy('u.name', 'ASC');
},
'class' => Fieldcampaign::class,
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'label' => false,
'placeholder' => 'Choose a field',
'attr' => array(
'class' => 'fieldcampaign_select',
'onchange' => 'return preseclet(this);'
)
)
);
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
// checks if the Product object is "new"
// If no data is passed to the form, the data is "null".
// This should be considered a new "Product"
if (!$data || null === $data->getId()) {
$form->add('operator', EntityType::class, array(
'class' => Operator::class,
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'label' => false,
'placeholder' => 'Choose an operator'
)
);
}
// dd($event->getForm(), $event->getData());
});
$formModifier = function (FormInterface $form, Fieldtype $type = null) {
//$positions = null === $sport ? [] : $sport->getAvailablePositions();
$form->add('operator', EntityType::class, array(
'class' => Operator::class,
'query_builder' => function (EntityRepository $er) use ($type) {
return $er->createQueryBuilder('u')
->where('u.fieldtype = :fieldtype')
->setParameter('fieldtype', $type);
//->orderBy('u.name', 'ASC');
},
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'label' => false,
'placeholder' => 'Choose an operator'
)
);
};
$builder->add('value', TextType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert value')
)
);
$builder->add('filtercampaigngroup', EntityType::class, array(
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.id = :id')
->setParameter('id', $this->filtergroup)
->orderBy('u.name', 'ASC');
},
'class' => Filtercampaigngroup::class,
'label' => false,
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'attr' => array(
'readonly' => true,
)
)
);
$value="";
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
if($data !== null) {
if($data->getOperator() !== null) {
if ($data->getOperator()->getId() == 26 || $data->getOperator()->getId() == 25){
$value="file";
/* $builder->add('value', TextType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert value')
)
);*/
}else{
$value = "number";
}
$formModifier($event->getForm(), $data->getOperator()->getFieldtype());
} else {
$formModifier($event->getForm(), null);
}
} else {
$formModifier($event->getForm(), $data);
}
}
);
if ($value == "file"){
$builder->add('value', FileType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert File')
)
);
}else{
$builder->add('value', TextType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert value')
)
);
}
$builder->get('fieldcampaign')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$type = $event->getForm()->getData()->getType();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $type);
}
);
/* $builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$data = $event->getData();
//var_dump($data['company']);
//var_dump($company);
//$formModifierOffer($event->getForm(), $data['company']);
/* if(array_key_exists('company', $data)) {
$formModifierOffer($event->getForm(), $data['company']);
}
if(array_key_exists('name', $data)) {
$formModifierAction($event->getForm(), $data['name']);
}
if(array_key_exists('action', $data)) {
$formModifierPrice($event->getForm(), $data['action']);
}
});
*/
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Filtercampaign::class,
'csrf_protection' => false,
]);
}
}
My twig:
{% extends 'index.html.twig' %}
{% block body %}
<div class="col-sm-12">
<div class="row">
<h2>{{section.action|capitalize}} {{section.title}}</h2>
<div id="result"></div>
</div>
<div id="filternav" class="row">
<div>
<a class="btn btn-outline-secondary btn-sm" href="../">◄ Back</a>
</div>
</div>
<div class="col-sm-12">
{% form_theme form 'bootstrap_singlelinecollection_layout.html.twig' %}
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</div>
</div>
<script>
var $collectionHolder;
// setup an "add a tag" link
var $addTagButton = $('<button type="button" class="btn btn-default add_tag_link"><span class="glyphicon glyphicon-plus"><i class="fas fa-plus"></i></span></button>');
var $newLinkLi = $('.multiple').append($addTagButton);
jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
$collectionHolder = $('div.multiple');
// add the "add a tag" anchor and li to the tags ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagButton.on('click', function(e) {
// add a new tag form (see next code block)
addTagForm($collectionHolder, $newLinkLi);
});
// add a delete link to all of the existing tag form li elements
$collectionHolder.find('>.form-group').each(function() {
addTagFormDeleteLink($(this));
});
//addTagFormDeleteLink($newFormLi);
function addTagFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<div class="col-sm-1 float-left"><button type="button" class="btn btn-default remove_tag_link"><span class="glyphicon glyphicon-minus"><i class="fas fa-minus"></i></span></button></div>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
});
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
var newForm = prototype;
// You need this only if you didn't set 'label' => false in your tags field in TaskType
// Replace '__name__label__' in the prototype's HTML to
// instead be a number based on how many items we have
// newForm = newForm.replace(/__name__label__/g, index);
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
newForm = newForm.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<div></div>').append(newForm);
console.log($newLinkLi);
$newLinkLi.after($newFormLi);
//preseclet();
/*$newFormLi[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].addEventListener('change',function(){
var data = {};
data[this.name] = this.value;
console.log(data);
var $form = $(this).closest('form');
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#form_filters_0_fieldcampaign').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#form_filters_0_fieldcampaign')
);
// Position field now displays the appropriate positions.
}
});
});*/
//console.log($newFormLi[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0]);
function addTagFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<div class="col-sm-1 float-left"><button type="button" class="btn btn-default remove_tag_link"><span class="glyphicon glyphicon-minus"><i class="fas fa-minus"></i></span></button></div>');
$tagFormLi.children()[0].append($removeFormButton[0]);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
addTagFormDeleteLink($newFormLi);
}
</script>
<script>
function preseclet(field) {
var form = field.closest('form');
var data = {};
data[field.name] = field.value;
console.log(form.method)
// Submit data via AJAX to the form's action path.
$.ajax({
url : form.action,
type: form.method,
data : data,
success: function(html) {
//$element.parent().parent().replaceWith(
field.parentNode.parentNode.replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#form_filters')[0]
);
// Position field now displays the appropriate positions.
document.getElementById("form_filters_0_operator").addEventListener("change", changeValueField)
}
});
}
valuefield()
function valuefield(){
if (typeof document.getElementById("form_filters_0_operator") == "object"){
//console.log(document.getElementById("form_filters_0_operator").value);
//document.getElementById("form_filters_0_operator").onchange = function(){changeValueField};
document.getElementById("form_filters_0_operator").addEventListener("change", changeValueField)
}
}
function changeValueField(){
console.log( document.getElementById("form_filters_0_operator").value);
if(document.getElementById("form_filters_0_operator").value == 25 || document.getElementById("form_filters_0_operator").value == 26){
document.getElementById("form_filters_0_value").type = "file";
}else {
document.getElementById("form_filters_0_value").type = "text";
}
}
if(document.getElementById("form_filters_0_operator").value == 25 || document.getElementById("form_filters_0_operator").value == 26){
document.getElementById("form_filters_0_value").type = "file";
}else {
document.getElementById("form_filters_0_value").type = "text";
}
</script>
{% endblock %}
The function on the controller(dont think is gonna be usefull but just in case):
public function create2(Request $request, $id) {
$this->section->action = 'create';
$em = $this->getDoctrine()->getManager();
$filtergroup = $this->getDoctrine()->getRepository(Filtercampaigngroup::class)->findOneById($id);
$campaign = $filtergroup->getCampaign();
$boolean = $filtergroup->getBoolean();
if($boolean == 0) {
$b = 'AND';
} elseif($boolean == 1) {
$b = 'OR';
} else {
$b = 'NOT';
}
$this->section->title = 'Filter #' . $id . ' ('.$b.')';
$filters = $filtergroup->getFilters();
if ($filters->isEmpty()) {
$filter = new Filtercampaign;
$filtergroup->addFilter($filter);
}
$form = $this->createFormBuilder($filtergroup)
->add('filters', CollectionType::class, array(
'entry_type' => FiltercampaignvalueType::class,
'entry_options' => array(
'label' => false,
'attr' => array(
'campaign' => $campaign->getId(),
'filtergroup' => $filtergroup->getId()
)
),
'by_reference' => true,
'allow_add' => true,
'allow_delete' => true,
'attr' => array('class'=>'multiple inline')
))
/* ->add('testfield', \Symfony\Component\Form\Extension\Core\Type\FileType::class, array(
"mapped"=> false
))*/
->add('save', SubmitType::class, array('label' => ucfirst($this->section->action) . ' ' . ucfirst($this->section->title)))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entity = $form->getData();
$em->persist($entity);
$em->flush();
$this->addFlash(
'success',
'Filter #'.$id.' edited!'
);
return $this->redirectToRoute('admin_campaign_filter');
}
return $this->render('project_field.html.twig', array(
'form' => $form->createView(),
'section' => $this->section
));
}
Any type of help is welcomed cause im so so so so so so so so so lost

I am trying to retrieve the posts via ajax call but Wordpress Ajax gives server error 500

When I click on pagination link (page number) it gives me post_type, taxonomy, term_name. I passed the variables with JQuery Variables to Ajax wordpress function. The Ajax function is receiving the vaiables. But WP_Query loop does not work with the passed data.
JavaScript Code:
<script>
$(".category--pagination").on("click", "a", function (e) {
e.preventDefault();
var link = $(this).attr("href");
if (link.indexOf("/page/") >= 0) {
brands_page = parseInt(link.substr(link.indexOf("/page/") + 6, 4));
} else {
brands_page = 1;
}
mzm_filter_taxonomy();
});
// mzm_filter_tax
function mzm_filter_taxonomy() {
$("#brandCategoryItemDisplay").addClass("loading");
var post_type = $("#post_type").val();
var taxonomy = $("#taxonomy").val();
var term_slug = $("#term_slug").val();
var term_name = $("#term_name").val();
//console.log(post_type);
// console.log(taxonomy);
// console.log(term_name);
if (brands_page == undefined) {
brands_page = 1;
}
var data = {
action: "mzm_filter_taxonomy",
post_type: post_type,
taxonomy:taxonomy,
term_slug:term_slug,
term_name:term_name,
page:brands_page,
};
$.post(mzm_filter.ajax_url, data, function (response, textStatus, jqXHR) {
if (response.success) {
console.log("executed success");
$("#brandCategoryItemDisplay").removeClass("loading");
$("#brandCategoryItemDisplay").html(response.data.items);
$(".category--pagination").html(response.data.pagination);
//$("#taxonomy_pagination").html(response.data.pagination);
}
});
}
</script>
Wordpress Ajax Function:
function mzm_filter_taxonomy()
{
$post_type = isset($_POST['post_type']) ? filter_var(trim($_POST['post_type']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$taxonomy = isset($_POST['taxonomy']) ? filter_var(trim($_POST['taxonomy']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$term_slug = isset($_POST['term_slug']) ? filter_var(trim($_POST['term_slug']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$term_name = isset($_POST['term_name']) ? filter_var(trim($_POST['term_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$perpage = mzm_brand_perpage();
$paged = (isset($_POST['page']) && intval($_POST['page'])) ? intval($_POST['page']) : 1;
// $sort = ( isset( $_POST['sort'] ) && intval( $_POST['sort'] ) ) ? intval( $_POST['sort'] ) : 1;
// $sort = (isset($_POST['sort'])) ? intval($_POST['sort']) : 1;
// $args = array(
// 'post_type' => $post_type,
// 'hide_empty' => false,
// 'posts_per_page' => $perpage,
// 'paged' => $paged,
// 'post_status' => 'publish',
// 'tax_query' => array(
// array (
// 'taxonomy' => $taxonomy,
// 'field' => 'slug',
// 'terms' => $term_slug,
// )
// ),
// );
$the_query = new WP_Query( array(
'post_type' => $post_type,
'tax_query' => array(
array (
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term_slug,
)
),
) );
// $the_query = new WP_Query($args);
ob_start();
// echo $post_type . '<br>';
// echo $taxonomy . '<br>';
// echo $term_name . '<br>';
// echo $term_slug . '<br>';
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
the_post();
// echo mzm_render_single_brand_card();
echo the_title();
}
wp_reset_postdata();
} else {
echo '<div class="no-criteria-search">Sorry, no posts matched your criteria.</div>';
}
$html = ob_get_clean();
$result = array(
'items' => $html,
'pagination' => 'mzm_render_pagination($the_query)',
);
wp_send_json_success($result);
}
add_action('wp_ajax_nopriv_mzm_filter_taxonomy', 'mzm_filter_taxonomy');
add_action('wp_ajax_mzm_filter_taxonomy', 'mzm_filter_taxonomy');
I am trying paginate via Ajax request. Other all scripts are working. But this is a single taxonomy page. On this page the loop doesn't executes. It gives server error 500.
I solved it myself.
The problem was in wp_query loop. I using custom $args and the loop object was $the_query.
So,
the_post();
//should be
$the_query->the_post();

prestashop generate a new form content with renderform via ajax

I created a button when clicked triggers the renderForm function with prestashop that is supposed to generate the form via ajax.But it doesn't seem to work.
Can anyone please help me or point me in the right direction because i'm new with prestashop ?
in the catproduct.php
public function generateform(){
$html = 'Click me
<div id="myFormm"></div>
<script type="text/javascript">
$( ".displayForm" ).click(function() {
$.ajax({
url: "'._MODULE_DIR_.$this->name.'/ajax.php",
context: document.body,
})
.done(function(data) {
$( "#myFormm" ).html( data );
alert( "Load was performed." );
});
})
</script>';
return $html;
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Add new category'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('FCI'),
'name' => 'FCI',
),
),
'submit' => array(
'title' => $this->l('Save')
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCatForm';
$helper->fields_value['FCI'] = 'ddddd';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='
.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
return $helper->generateForm(array($fields_form));
}
the ajax.php file (the ajax file call the renderForm() function to create new form):
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
include_once('catproduct.php');
$module = new catproduct();
echo $module->renderForm();

ajax function outputs a "0" when I use die() at the end

I have a php page that is making a couple of ajax calls. The first ajax call is made and on success it activates a second ajax function. Each function has die() at the end. No matter what I do, die() keeps outputting a "0" to the screen. I tried commenting the die() out of the first ajax function, but it never processes the ajax request when I do that. The loading gif just keeps spinning. When I comment out the die() in the second function, it outputs "0" twice. I have no clue why it keeps printing that to the screen.
This is the first function.
function json_info() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
// create a new array to store projects
$projectsArray = array();
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
$projectsArray = array();
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
$image = get_field('project_photo');
$image = $image['sizes']['thumbnail'];
$projectsArray[] = array(
'title' => get_the_title(),
'lat' => get_field('latitude'),
'long' => get_field('longitude'),
'status' => get_field('status'),
'industry' => get_field('industry'),
'state' => get_field('state'),
'link' => get_permalink(),
'photo' => $image,
'num' => $paged
);
endwhile; endif;
wp_reset_query();
} // end of isset
?>
<?php
echo json_encode($projectsArray);
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info', 'json_info' );
add_action( 'wp_ajax_nopriv_json_info', 'json_info' );
And this is the second function:
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
?>
<li class="group">
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
And this is the ajax call to both functions:
function run_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info',
'state' : state,
'status' : markets,
'services' : services
},
success:function(data) {
// This outputs the result of the ajax request
var jsonData = JSON.parse(data);
do_ajax();
} /*,
error: function(errorThrown){
console.log(errorThrown);
}*/
}); // end of ajax call for json_info
function do_ajax() {
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
}
I'm not sure what I'm missing or doing wrong that is causing the "0" to print to the screen.
Well, it turns out that I'm an idiot, and I was just overlooking the problem. There was a third function called by ajax, and I didn't have die() at the end of it. I was thinking the issue was in my second function since the 0 was showing up in the div where I was printing that content.

Highlighting words with Javascript, what am I missing?

I have been working with a basic javascript/PHP chatroom. I want certain words to be highlighted as they appear in the chat stream.
The html output for the chatroom looks like:
<div class="chat-container">
<div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div>
<div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div>
<div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div>
</div>
I have found one Javascript solution that is actually what I'm looking for (please see https://jsfiddle.net/4ny8adpg/2/ for a working example). But when I try to use it with the chatroom, it won't highlight any text in the "Chat-Container" div.
Will it not work because the contents of the chatroom is an output of the PHP/Javascript and not just HTML like in the jsfiddle example? Or maybe I am missing something obvious.
Any help or advise would seriously be appreciated.
EDIT (to show code and provide more information):
The chatroom is actually a wordpress plugin, it is made up of a PHP file and a Javascript file:
Javascript:
var last_update_received = 0;
function chatroom_check_updates() {
jQuery.post(
ajaxurl,
{
action: 'check_updates',
chatroom_slug: chatroom_slug,
last_update_id: last_update_id
},
function (response) {
chats = jQuery.parseJSON( response );
if ( chats !== null ) {
for ( i = 0; i < chats.length; i++ ) {
if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
continue;
jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
last_update_id = chats[i].id;
jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
}
}
}
);
setTimeout( "chatroom_check_updates()", 1000 );
}
function chatroom_strip_slashes(str) {
return (str + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
}
jQuery(document).ready( function() {
last_update_id = 0;
chatroom_check_updates();
jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {
if ( event.charCode == 13 || event.keyCode == 13 ) {
chatroom_send_message();
return false;
}
});
});
function chatroom_send_message() {
message = jQuery( 'textarea.chat-text-entry' ).val();
jQuery( 'textarea.chat-text-entry' ).val('');
jQuery.post(
ajaxurl,
{
action: 'send_message',
chatroom_slug: chatroom_slug,
message: message
},
function (response) {
}
);
}
PHP:
Class Chatroom {
function __construct() {
register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
add_action( 'init', array( $this, 'register_post_types' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );
add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );
add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );
add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );
add_filter( 'the_content', array( $this, 'the_content_filter' ) );
}
function activation_hook() {
$this->register_post_types();
flush_rewrite_rules();
}
function deactivation_hook() {
flush_rewrite_rules();
}
function register_post_types() {
$labels = array(
'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),
'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),
'add_new' => _x( 'Add New', 'book', 'chatroom' ),
'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),
'edit_item' => __( 'Edit Chat Room', 'chatroom' ),
'new_item' => __( 'New Chat Room', 'chatroom' ),
'all_items' => __( 'All Chat Rooms', 'chatroom' ),
'view_item' => __( 'View Chat Room', 'chatroom' ),
'search_items' => __( 'Search Chat Rooms', 'chatroom' ),
'not_found' => __( 'No Chat Rooms found', 'chatroom' ),
'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),
'parent_item_colon' => '',
'menu_name' => __( 'Chat Rooms', 'chatroom' )
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'show_in_nav_menus' => true,
'supports' => array( 'title' )
);
register_post_type( 'chat-room', $args );
}
function enqueue_scripts() {
global $post;
if ( $post->post_type != 'chat-room' )
return;
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );
wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );
}
function maybe_create_chatroom_log_file( $post_id, $post ) {
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return;
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );
if ( file_exists( $log_filename ) )
return;
wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, json_encode( array() ) );
// TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config
}
function define_javascript_variables() {
global $post;
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return; ?>
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
var chatroom_slug = '<?echo $post->post_name; ?>';
</script>
<?php
}
function ajax_check_updates_handler() {
$upload_dir = wp_upload_dir();
$log_filename = $this->get_log_filename( $_POST['chatroom_slug'] );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
foreach ( $messages as $key => $message ) {
if ( $message->id <= $_POST['last_update_id'] )
unset( $messages[$key] );
}
$messages = array_values( $messages );
echo json_encode( $messages );
die;
}
/**
* AJAX server-side handler for sending a message.
*
* Stores the message in a recent messages file.
*
* Clears out cache of any messages older than 10 seconds.
*/
function ajax_send_message_handler() {
$current_user = wp_get_current_user();
$this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] );
die;
}
function save_message( $chatroom_slug, $user_id, $content ) {
$user = get_userdata( $user_id );
if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {
// Set random color for each user
$red = rand( 0, 16 );
$green = 16 - $red;
$blue = rand( 0, 16 );
$user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );
update_user_meta( $user_id, 'user_color', $user_text_color );
}
$content = esc_attr( $content );
// Save the message in recent messages file
$log_filename = $this->get_log_filename( $chatroom_slug );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$last_message_id = 0; // Helps determine the new message's ID
foreach ( $messages as $key => $message ) {
if ( time() - $message->time > 10 ) {
$last_message_id = $message->id;
unset( $messages[$key] );
}
else {
break;
}
}
$messages = array_values( $messages );
if ( ! empty( $messages ) )
$last_message_id = end( $messages )->id;
$new_message_id = $last_message_id + 1;
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
// Save the message in the daily log
$log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
}
function write_log_file( $log_filename, $content ) {
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, $content );
}
function get_log_filename( $chatroom_slug, $date = 'recent' ) {
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;
return $log_filename;
}
function parse_messages_log_file( $log_filename ) {
$upload_dir = wp_upload_dir();
$handle = fopen( $log_filename, 'r' );
$contents = fread( $handle, filesize( $log_filename ) );
fclose( $handle );
return $contents;
}
function the_content_filter( $content ) {
global $post;
if ( $post->post_type != 'chat-room' )
return $content;
if ( ! is_user_logged_in() ) {
?>You need to be logged in to participate in the chatroom.<?php
return;
}
?>
<div class="chat-container">
</div>
<textarea class="chat-text-entry"></textarea>
<?php
return '';
}
}
$chatroom = new Chatroom();
Example of JSON:
[{"id":129,"time":1428340673,"sender":1,"contents":"What is your favourite animal?","html":"<div class=\"chat chat-message-129\"><strong style=\"color: #840;\">User 1<\/strong>: What is your favourite animal?<\/div>"},
{"id":130,"time":1428351683,"sender":2,"contents":"I vote for #dog.","html":"<div class=\"chat chat-message-130\"><strong style=\"color: #840;\">User 2<\/strong>: I vote for #dog.<\/div>"},
{"id":131,"time":1428352376,"sender":3,"contents":"I have a #cat!","html":"<div class=\"chat chat-message-131\"><strong style=\"color: #840;\">User 3<\/strong>: I have a #cat!<\/div>"}]
If you want your highlighting code to run after an AJAX call has returned (when there are new HTML fragments), then try something along these lines:
$.ajax({
...
success : function(data) {
...
$('.chat').each(function(){
var hashtag = $(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
$(this).html(hashtag);
});
},
...
});
In your case, call your highlighting code after you have populated all your chat fragments:
...
function (response) {
chats = jQuery.parseJSON( response );
if ( chats !== null ) {
for ( i = 0; i < chats.length; i++ ) {
if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
continue;
jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
last_update_id = chats[i].id;
jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
}
// Call highlighting code here
}
}
...
PS You can save time by caching the selector jQuery('div.chat-container') as a variable so that jQuery doesn't have to search your HTML each time.

Categories