How to switch called php page using AJAX in wordpress - php

I have an several online application forms built into a (they differ per country) and I need to switch from one to the other with a users button click.
The code I have does this however it also produces a 500 error which breaks any other scripts.
Can anyone give me an idea of what I am doing wrong?
//Update appURL
if (jQuery('button[id="ukApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/uk/uk-application.php";
} else if (jQuery('button[id="itlApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/itl/it-application.php";
}
//Get URL path
function getContextPath() {
var ctx = window.location.pathname,
path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx;
return path + (/\/$/.test(path) ? '' : '/');
}
//Country Application URL
function getOutput() {
jQuery.ajax({
url: getContextPath() + appURL,
complete: function (response) {
jQuery('#output').html(response.responseText);
},
error: function () {
jQuery('#output').html('Bummer: there was an error!');
}
});
return false;
}

here is your ajax function
$.ajax({
url: ajax.url,
...
dataType: "json",
success: function(response) {
$('#myDiv').html(response.html);
},
})
and the php function
function my_ajax_load() {
$post_id = $_POST['post_id'];
ob_start();
include(locate_template('my-template-file.php',false,false));
$page_template = ob_get_contents();
ob_end_clean();
$response['html'] = $page_template;
wp_send_json($response);
}
in your template file you can use your variables declared in the function, in this example you can you $post_id inside the my-template-file.php
For example:
<?php /* Template name: My template */
if($post_id) {
echo get_the_title($post_id);
}
?>
500 error is caused by php error not ajax or jquery, check out your template file for a php errors

There was a missing image being called by the page I was trying to load, the error only showed up in the logs. Thanks all :)

Related

POST admin-ajax throwing error 400 - not finding custom functions

I am adding a function that should be called when a button is clicked, i have a js file with the following jquery code and the ajax call :
jQuery(document).ready( function() {
function getUrlParameter(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
jQuery('#upload_btn').click( function(e) {
e.preventDefault();
var flag = true;
var postId = getUrlParameter('preview_id');
var files = jQuery('#file_tool').prop('files');
console.log(files);
var dataS = {
'action': 'upload_button',
'preview_id': postId,
'files': files,
'set': flag
}
jQuery.ajax({
type : 'post',
url : diario.upload,
processData: false,
contentType: false,
data : dataS,
success: function(response) {
if(response.type == "success") {
console.log('jquery works');
} else console.log(response);
}
});
});
});
When i click the button the console.log shows the files obj so at least the onClick works, but just after that it shows up jquery.js:4 POST custom/wp-admin/admin-ajax.php 400. This is how my functions.php looks like :
add_action( 'wp_enqueue_scripts', 'enqueue_onClick_upload' );
//custom_js_enqueuer
function enqueue_onClick_upload() {
wp_register_script( 'onClick_upload', WP_CONTENT_URL.'/themes/microjobengine/onClick_upload.js', array('jquery') );
wp_localize_script( 'onClick_upload', 'diario', array( 'upload' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'onClick_upload' );
}
add_action('wp_ajax_upload_button', 'upload_button');
add_action('wp_ajax_nopriv_upload_button', 'upload_button');
// upload button function
function upload_button() {
$postID = $_POST['preview_id'];
if ($_POST['set']) {
if($_POST['files']['size'] === 0 )
echo "<script>console.log('There's no images.');</script>";
}
$result['type'] = 'success';
echo json_encode($result);
wp_die();
}
I have no idea why it doesn't find the action, it's all done as wp says it should, I hope somone could give a hand, thanks.
--EDIT--
Okay so now i tried to only pass 'action': 'upload_button', the error does not appear but the response doesn't get success, I did this with all the code inside my function commented and just leaving the las 3 lines, in order to return the success, but it doesn't, so it might find the function but for some reason it doesn't get performed, and of course that means something wrong happens when i pass the extra data, any thoughts about why this happens?
Sorry i wasn't getting the right thing to get feedback from the functions, i just had to delete all echos and save everything i needed into an array and returne it json encoded.

Asynchronously query the database by using ajax and jquery and post the result back in codeigniter View

I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this

my jquery code is not working code igniter

this is my javascript code ...i have written a function in my controller in which if false is return then i am echoing the 'userNo' other wise echo the json .. here is my javascript in which only else part is working not if part ... i have checked in firebug also .. i am getting a response "userNo" but dont know why it is not running the first part
<script type="text/javascript">
$(document).ready(function(){
$('#hide').hide();
$('#bill_no').blur(function(){
if( $('#bill_no').val().length >= 3 )
{
var bill_no = $('#bill_no').val();
getResult(bill_no);
}
return false;
})
function getResult(billno){
var baseurl = $('.hiddenUrl').val();
$('.check').addClass('preloader');
$.ajax({
url : baseurl + 'returnFromCustomer_Controller/checkBillNo/' + billno,
cache : false,
dataType: 'json',
success : function(response){
$('.check').removeClass('preloader');
if (response == "userNo") //this part is not working
alert("true");
else
$('.check').removeClass('userNo').addClass('userOk');
// $(".text").html(response.result);
$('#hide').show();
$(".text1").html(response.result1);
$(".text2").html(response.result2);
$(".text3").html(response.result3);
}
})
}
})
</script>
my Controller
function checkBillNo($billno)
{
$this->load->model('returnModel');
$query = $this->returnModel->checkBillNo($billno);
//$billno = $this->uri->segment(3);
$billno_results = $this->returnModel->sale($billno);
if (!$billno_results){
echo "userNo";
}else{
echo json_encode($billno_results);
}
}
Instead of echo "userNO", try to use it:
echo json_encode(array('return' => 'userNo'));
... and in your JS, use this:
if (response.return == "userNo") { // ...

CodeIgniter ajax call using jquery when call redirect it prints the whole page i div

no title that fits this bug but this how it goes, i have form with a submit button when pressed jquery ajax calls the controller and the form validation is done if it fails the form is redrawn if it passes the page is redirected to the home page with flash message successes and thats where the bug happens it redraws the whole page in the content(header header footer footer). i hope it makes sense seeing is believing so here is the code
side notes: "autform" is a lib for creating forms "rest" is a lib for templates.
the jquery code:
$("form.user_form").live("submit",function() {
$("#loader").removeClass('hidden');
$.ajax({
async :false,
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
data: $(this).serialize(),
success: function(data) {
$("#center").html(data);
$('div#notification').hide().slideDown('slow').delay(20000).slideUp('slow');
}
})
return false;
});
the controller
function forgot_password()
{
$this->form_validation->set_rules('login',lang('email_or_login'), 'trim|required|xss_clean');
$this->autoform->add(array('name'=>'login', 'type'=>'text', 'label'=> lang('email_or_login')));
$data['errors'] = array();
if ($this->form_validation->run($this)) { // validation ok
if (!is_null($data = $this->auth->forgot_password(
$this->form_validation->set_value('login')))) {
$this-> _show_message(lang('auth_message_new_password_sent'));
} else {
$data['message']=$this-> _message(lang('error_found'), false); // fail
$errors = $this->auth->get_error_message();
foreach ($errors as $k => $v){
$this->autoform->set_error($k, lang($v));
}
}
}
$this->autoform->add(array('name'=>'forgot_button', 'type'=>'submit','value' =>lang('new_password')));
$data['form']= $this->autoform->generate('','class="user_form"');
$this->set_page('forms/default', $data);
if ( !$this->input->is_ajax_request()) { $this->rest->setPage(''); }
else { echo $this->rest->setPage_ajax('content'); }
}
}
function _show_message($message, $state = true)
{
if($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
}else{
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
redirect(base_url(),'refresh');
}
i think it as if the redirect call is caught by ajax and instead of sending me the home page it loads the home page in the place of the form.
thanks for any help
regards
OK found the problem and solution, it seemed you cant call a redirect in the middle of an Ajax call that is trying to return a chunk of HTML to a div, the result will be placing the redirected HTML in the div.
The solution as suggested by PhilTem at http://codeigniter.com/forums/viewthread/210403/
is when you want to redirect and the call is made by Ajax then return a value with the redirect URI back to Ajax and let it redirect instead.
For anyone interested in the code:
The Jquery Ajax code:
$("form.user_form").live("submit", function(event) {
event.preventDefault();
$("#loader").removeClass('hidden');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
dataType:"html",
data: $(this).serialize(),
success: function(data) {
var res = $(data).filter('span.redirect');
if ($(res).html() != null) {
[removed].href=$(res).html();
return false;
}
$("#center").html(data);
},
error: function() {
}
})
return false;
});
The PHP Controller
function _show_message($message, $state = true, $redirect = '')
{
if ($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
} else {
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
if ( !$this->input->is_ajax_request())
{
redirect(base_url() . $redirect, 'location', 302);
}
else
{
echo '<span class="redirect">'.base_url().$redirect.'</span>';
}
}
just use individual errors
json_encode(array(
'fieldname' => form_error('fieldname')
));
AJAX
success: function(cb)
{
if(fieldname)
{
{fieldname}.after(cb.fieldname)
}
}
see this

Ajax method calls same function in controller but needs to load different results in different areas

I am a bit stuck with my website, currently on the new section of my site(among others) the user rolls over a thumbnail and gets the articles abstract displayed below it, and then when they click on said thumbnail the article appears on the left of the page,
The ajax works by pulling the href from the link that surronds the thumbnail image and using that as the url for the method call, the problem is that the click version will also be using the same function call, I cannot work out how to show the different content depening on what even happends, currently I have this as my code,
<?php
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class='$v[category_name]'><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
?>
<script>
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
});
</script>
The method that gets called is,
public function get_content_abstract() {
$this->load->model('content_model');
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
This is called by the ajax following the link /get_content_abstract/3, where 3 or any other number is the articles ID.
How can I sort so that I can use this function again, but only show that body content of the article instead of the abstract if the link is clicked and mouseovered?
You can pass a call type variable and check for it in your php code. Notice I added data to your ajax calls.
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
data: "calltype=abstract",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
data: "calltype=full",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
pass a GET variable in the url of the ajax call.
You just pass an variable to the handler via GET or POST that tells the handler which content to show. As your AJAX calls are simple, you can simplify the calls and use load(). If you can't use $_GET or $_POST, just append the data in the URL:
$("a.contentlink").mouseover(function() {
// URL becomes index.php/home/get_content_abstract/3/abstract
$('#abstract').load($(this).attr("href")+'/abstract');
});
$("a.contentlink").click(function(ev) {
$('#main_menu').hide();
// URL becomes index.php/home/get_content_abstract/3/full
$('#left-content').load($(this).attr("href")+'/full');
return false;
});
And in PHP, you can use something like this:
public function get_content_abstract() {
$this->load->model('content_model');
if($this->uri->segment(4) == 'full') {
// Load full content
} else {
// Load abstract
}
$this->load->view('template/abstract', $data);
}

Categories