Unable to edit recode in cake php when I load the value in select box using j-query - cakephp-2.1

I am unable to load select box value when I want to update the value. The same code perfectly working when I am going to save value.
My controller code is:
public function listwardByCircle($category = "") {
$this->layout = 'ajax';
$this->beforeRender();
$this->autoRender = false;
$ward=$this->Ward->find('list',array(
"fields" => 'id, wardname',
"conditions" => array('Ward.circle_id' => $category)
));
//$this->set('ward',$ward);
print_r($ward);
foreach($ward as $key => $val) {
echo "<option value=$key>$val</option>";
}
}
And this is my js code :
$("#AreaCircleId").change(function() {
alert("testing....");
$.post('../Admins/listwardByCircle/' + $(this).val(), function(data) {
alert( data);
$("#AreaWardId").empty().append(data);
}, 'html');
});

In js file
Url in Controller Like
`\../../Admins\/listwardByCircle`

You may need to update your URL post location in the ajax from:
$.post('../Admins/listwardByCircle/'
to
$.post('/admins/listwardByCircle/'
This is if the controller name is admins.

Related

ajax not getting any response from cakephp code

I am using CakePHP 2.9 to send data on the URL using ajax and get the related response.
I tried may method to get the response, I also want to know why this //URL:'/Pages/dropdownbox/'+id is not working.
bellow are ajax code which I wrote in the index.ctp.
$("#certificatedetail").on('change',function() {
var id = 'subcribe';
$("#usertype").find('option').remove();
$("#certificateclass").find('option').remove();
$("#certificatetyp").find('option').remove();
if (id) {
$.ajax({
type: 'POST',
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox','id')); ?>',
//url:'/Pages/dropdownbox/'+id,
dataType:'json',
cache: false,
async:true,
success: function(html)
{
$('<option>').val('').text('select').appendTo($("#usertype"));
$('<option>').val('').text('select').appendTo($("#certificateclass"));
$('<option>').val('').text('Select').appendTo($("#certificatetyp"));
$.each(html, function(key, value)
{
$('<option>').val(key).text(value).appendTo($("#usertype"));
});
}
});
}
});
I have written this controller code in PagesController,PHP and I declared the dropdownbox in AppController.php
public function dropdownbox($id = null)
{
Configure::write('debug', 0);
$this->layout = null;
$this->autoRender = false;
$category = array();
switch ($id)
{
case $id == "subcribe":
if ($id == 'subcribe') {
$category = array(
'individual' => 'Individual',
'organization'=>'Organization',
'organizationgovt' => 'Organization-Govt',
'organizationbank' => 'Organization-Bank'
);
break;
}
}
}
/ bellow is the code where I specify the dropdownbox function in AppController.php
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(
'login','add','index','contact','dropdownbox',
'cityres','stateres','sectorres','productres',
'project','service','about','apply','tender',
'decregistration','search','searchresult',
'tenderdetails'
);
}
You are generating the URL on your server, and using the string literal 'id' in it. The JavaScript id variable is never referenced. What you probably want is:
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox')); ?>' + id,
You are not returning any response from the controller. Do few things to debug it
Check in Browser's Network tab whether the called URL is correct or not.
Check the parameters are correct or not.
This is how it looks in Firefox Developer Edition
If URL is correct. Add below code in the dropdownbox() method. (Before the closing of the method)
echo json_encode($category);
Check Response Tab in the Network tab. (Example image above).
Also, console the response in the javascript code. Maybe you will be getting some other response which is not JSON.
success: function(html) {
console.log(html);
...
}
Hope it helps.

How to update pagination template of knppaginatorbundle after ajax query

Im using knppaginatorbundle to create pagination. I have created a jquery code to select data with ajax.
Everything is okay when I click on the page number , the content is loaded with the correct data.
But I have a problem , The pagination template is not changed after after ajax query:
previous and next links values must changed
current page must be disabled
and other changes that need to be done ...
How can I do this ?
public function listAction($page, Request $request)
{
$em = $this->getDoctrine()->getManager();
$paginator = $this->get('knp_paginator');
$qb = $em->getRepository('AppBundle:Travel')->getListTravels();
$pagination = $paginator->paginate(
$qb, $request->query->get('page', $page), 3
);
//ajax request
if ($request->isXmlHttpRequest()) {
$view = $this->renderView('#App/Frontend/Travel/list.html.twig', array(
'pagination' => $pagination
));
$response = new JsonResponse(array('ok' => $view));
return $response;
}
return $this->render('AppBundle:Frontend/Travel:travel-list-view.html.twig', array(
'pagination' => $pagination,
));
}
I have added an attr data-target to pagination template like this:
<a data-target="{{ page }}" href="{{ path(route, query|merge({(pageParameterName): page})) }}">{{ page }}</a>
View
//.....
<div id="mydiv">
// list.html.twig contains the loop
{% include "AppBundle:Frontend/Travel:list.html.twig" %}
</div>
<br>
{{ knp_pagination_render(pagination) }}
//....
<script>
$(document).ready(function () {
$("ul#pagination a").click(function (e) {
e.preventDefault();
var dataTarget = $(this).attr("data-target"); // each <a> has attr named data-target contains num of page
var hash;
hash = 'page=' + dataTarget;
window.location.hash = hash;
if (window.location.hash != "") {
$.ajax({
type: 'get',
dataType: 'json',
url: Routing.generate('frontend_travels_list', {'page': dataTarget}),
success: function (msg) {
if (msg["ok"] === undefined) {
alert('error');
} else {
$("#mydiv").html(msg["ok"]);
}
}
});
}
});
});
</script>
Route
frontend_travels_list:
path: /travels/{page}
defaults: { _controller: AppBundle:TravelFrontend:list, page: 1 }
options:
expose: true
If someone else needs a solution there 2 ways.
You can use that bundle https://github.com/nacholibre/knppaginator-ajax
You should build new pagination string in controller and send it in JsonResponse as a param. Then replace pagination element in DOM via jQuery on success.
For SF 4.3 you can use my approach
To be able to inject the Processor in controller you have to add alias for autowiring in services.yaml
Knp\Bundle\PaginatorBundle\Helper\Processor: '#knp_paginator.helper.processor'
Based on injected PaginatorInterface you should build your $pagination object (PaginationInterface)
Use Processor to build the context array for Twig.
$paginationContext = $processor->render($pagination);
render method expects SlidingPagination object, but got $pagination which is PaginationInterface - however it seems that is ok
Get the Twig and render a final string
$twig = $this->get('twig');
$paginationString = $twig->render($pagination->getTemplate(), $paginationContext);
Example of working controller
if ($request->isXmlHttpRequest()) {
$view = $this->render('#App/Frontend/Travel/list.html.twig', array(
'pagination' => $pagination
))->getContent();
$paginationContext = $processor->render($pagination);
$twig = $this->get('twig');
$paginationHtml = $twig->render($pagination->getTemplate(), $paginationContext);
$response = new JsonResponse(['view' => $view, 'paginationHtml' => $paginationHtml]);
return $response;
}
then in jQuery
success: function (msg) {
if (msg["ok"] === undefined) {
alert('error');
} else {
$("#mydiv").html(msg["view"]);
$("#myDivContainingPagination").html(msg["paginationHtml"])
}
}

CodeIgniter 2.1 form_validation library not working with ajax

I had a form which when submitted, either returned an error if there was one, or it subbmited the data to the DB table if validation passed, and it worked fine.
Now I wanna do the same thing with ajax, but the validation seems to always return false, no matter if I type in something or not.
My controller:
function add_new_category_ajax()
{
// make sure it's the admin, else redirect
if ( ! $this->session->userdata('is_admin') ) {
redirect('admin/login');
exit();
}
// load form validation library
$this->load->library('form_validation');
// validate fields
$this->form_validation->set_rules('category_title', 'Category Title', 'trim|required');
// if validation failed
if ($this->form_validation->run($this) == FALSE)
{
// dummy var
$data['dummy'] = '';
// generate error message
$data['error'] = '<p class="errormsg">You must enter a category title.</p>';
// load the view
$this->load->view('new_category_view', $data);
}
else
// validation passed, add new category
{
// get category_title
$ct = $this->input->post('category_title');
// check if category title exists
$cte = $this->mdl_categories->category_title_exists($ct);
if ( $cte )
{
$data['msg'] = '<p class="errormsg">That category title already exists, please choose another.</p>';
}
else // it does not, proceed with insert
{
// prepare data
$data = array(
'title' => $ct
);
// add new page
$this->db->insert('categories', $data);
// show success message and add another page link
$flag = $this->db->affected_rows();
if ($flag == 1)
{
$data['msg'] = '<p class="successmsg">The category has been added!</p>';
$data['aac'] = '<br><p><a href='.base_url().'admin/add-new-category/>Add another category +</a></p>';
}
}
$data['msg'] = '<p class="successmsg">The category has been added!</p>';
// load the view
$this->load->view('new_category_view', $data);
} // end else
}
My ajax:
$('body').on('click', 'a.submitnewcat', function(e) {
e.preventDefault();
// alert('code');return;
$('#ajaximg img').addClass('act');
setTimeout(function() {
$("#ajax").load('<?php echo site_url('admin/add-new-category-ajax'); ?>');
$('#ajaximg img').removeClass('act');
}, 200)
});
Linking to admin/add-new-category-ajax is not a mistake, routes are set up that way.
Why does it always return a failed validation?
As I said in the comment, you need an extra parameter to make load uses POST method instead of GET method :
$("#ajax").load('<?php echo site_url('admin/add-new-category-ajax'); ?>', { "category_title " : "myTitle" });
The run method doesn't take a parameter if I'm not wrong :
if ($this->form_validation->run() == FALSE)

Error with ajax and zf2 controller action

I was trying to use ajax to redirect to a controller action in zend framework 2 but the ajax is not responding rightly as well as I am not receiving the data alert.
Here is the ajax code:
$(".save_btn").click(function (){ //the class of submit button is save_btn
$.ajax({
type : 'POST',
url : '/template/addtemplate',
data : {'id':'test'},
success : function(data,status)
{
alert(data.message);
}
});
});
this is my controller code:
public function addtemplateAction()
{
$result = array('status' => 'error',
'message' => 'There was some error. Try again.'
);
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$data = $request->getPost();
if(isset($data['id']) && !empty($data['id'])){
return new JsonModel($result);
$result['status'] = 'success';
$result['message'] = 'We got the posted data successfully.';
}
}
return new JsonModel($result);
}
I have also added these particular things in my module.config.php file :
'strategies' => array (
'ViewJsonStrategy'
),
I think the problem lies in $request->isXmlHttpRequest() which returns blank.
Any help will be accepted..
Use any kind of developer tools. Chrome => f12 => Network tab and check your response

Unable to get_the_content(); of a post in Wordpress via AJAX

I'm trying to ajaxify my Wordpress theme and I use the ajax-in-WordPress method and I'm now trying get_the_content of post via functions.php. Using jQuery, when I do alert(data) I get the 'title' echo but not the content of the existing post I want (returns 0).
What am I doing wrong?
The jQuery part
$('.ajaxed,.ajaxed a,.menu-item-home a,.menu-item-object-page a').live('click', function(event) {
event.preventDefault();
var link = $(this).attr('href');
var toRemove = MySettings.url;
var rewritepath = link.replace(toRemove,'');
var handler = function(data) {
$('title').html($('title', data).html());
$('#primary').html($('#primary', data).html());
$('#primary').hide().fadeIn('slow');
$.address.title(/>([^<]*)<\/title/.exec(data)[1]);
};
$.post(ajax_object.ajaxurl, {
action: 'ajax_action',
post_id: $(this).find('input.post_id').attr('value')
},function(data) {
alert(data.post_title);
alert(data.post_content);
});
/*$.ajax({
url: link,
error: function(XMLHttpRequest, textStatus, errorThrown) {
handler(XMLHttpRequest.responseText);
},
success: function(data, textStatus, XMLHttpRequest) {
handler(data, function(){
});
}
});*/
$.address.state(MySettings.path).crawlable(true).value(rewritepath);
return false;
});
The functions.php part
<?php
function javascripts() {
if( !is_admin()){
$blogurl = get_bloginfo('url');
$thumbnail_width = get_option('thumbnail_size_w');
$thumbnail_height = get_option('thumbnail_size_h');
$path = parse_url(get_bloginfo('siteurl'), PHP_URL_PATH);
$url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js';
wp_deregister_script('jquery');
if (get_transient('google_jquery') == true) {
wp_register_script('jquery', $url, array(), null, true);
}
else {
$resp = wp_remote_head($url);
if (!is_wp_error($resp) && 200 == $resp['response']['code']) {
set_transient('google_jquery', true, 60 * 5);
wp_register_script('jquery', $url, array(), null, true);
}
else {
set_transient('google_jquery', false, 60 * 5);
$url = get_bloginfo('wpurl') . '/wp-includes/js/jquery/jquery.js';
wp_register_script('jquery', $url, array(), '1.7', true);
}
}
wp_enqueue_script('plugins.js', get_bloginfo('template_directory') . "/js/plugins.js" , array('jquery'));
wp_enqueue_script('ajax-script', get_bloginfo('template_directory') . "/js/scripts.js", array('jquery'));
wp_localize_script('ajax-script', 'ajax_object', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_localize_script('jquery', 'MySettings', array('width' => $thumbnail_width,'height' => $thumbnail_height,'url' => $blogurl,'path' => $path));
}
}
add_action('wp_enqueue_scripts', 'javascripts');
add_action('wp_ajax_ajax_action', 'ajax_action_stuff'); // ajax for logged in users
add_action('wp_ajax_nopriv_ajax_action', 'ajax_action_stuff'); // ajax for not logged in users
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
echo json_encode($post_data);
}
?>
What am I doing wrong? Thanks
Without seeing the entire scope of your code, it appears that you might be calling get_the_content() outside of the context of The Loop. If so, the function doesn't understand which post you'd like to retrieve the content for. Try organizing the function this way:
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
$title = $post_data->post_title;
$content = $post_data->post_content;
echo $title;
echo $content;
}
Here we've used get_post() to return an object with all of the post data.
The jQuery function you've created...
function(data) {
alert(data);
});
... should essentially contain a string in the data object that contains your title and content.
Here's a recommendation though, on how you can return your data in a more organized fashion, if you like.
The 'data' object (which is what you've echoed in the php function ajax_action_stuff()) is just a string value. The problem though is that the data isn't really structured in a way for jQuery to fully understand and use to its full potential. If you change your php function to return a JSON object though, then you can use all your properties in jQuery individually. I'll show you how...
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
echo json_encode($post_data);
}
Then in the jQuery function you have access to each property like this:
$.post(ajax_object.ajaxurl, {
action: 'ajax_action',
post_id: $(this).find('input.post_id').attr('value')
},function(data) {
alert(data.post_title);
alert(data.post_content);
});
Have a look at the get_post() function to see all of the properties that you have available to you.
You aren't telling get_the_content() which post to retrieve the content for. Internally, this function checks for the global $post object and filters the content of that object.
So change your ajax function to something like this:
function ajax_action_stuff() {
global $post;
$post_id = $_POST[ 'post_id' ];
update_post_meta( $post_id, 'post_key', 'meta_value' );
$post = get_post( $post_id );
$title = 'title';
$content = get_the_content();
echo $title;
echo $content;
}
This will use the ID you've passed in to query the database for a specific post and populate the global $post object. Now, get_the_content() and even get_the_title() should function normally.

Resources