Ajax not making function call to php function - javascript

I have ajax function in script as:
$.ajax({
url: 'http://www.somesitename.com/admin/exportToCSVAction',
type: 'GET',
data:{},
cache: false,
success: function() {
alert("sucess");
},
error: function () {
alert("error");
}
});
exportToCSVAction function in php as:
public function exportToCSVAction()
{
$exportBatch = 10;
$order = $this->getTableGateway('order');
$select = new Select();
$select->from('order');
$data = $order->selectWith($select)->toArray();
$batchDir = __DIR__ . '/../../../../../data/export/batch/' . $exportBatch;
mkdir($batchDir);
$fileNameWithFilePath=$batchDir . '/order2.csv';
if (file_exists($fileNameWithFilePath))
{
$this->downloadOrderCSVAction($fileNameWithFilePath);
}
else
{
$csvFile = fopen($batchDir . '/order2.csv', 'w');
$i = 0;
foreach($data as $record) {
if($i==0) fputcsv($csvFile, $this->getCsvHeader($record));
fputcsv($csvFile, $this->updateCsvLine($record));
$i++;
}
fclose($csvFile);
}
}
But every time its returning me error as alert.
When i run it directly through link:
http://www.somesite.com/admin/exportToCSVAction
It returns me result correctly. (downloads the file as expected)
But through ajax it gives me Error as a alert.
Through inspect element network tab i get following:
Please help me.
Where i am making mistake?
Note:
I also tried by removing data from ajax, but no effect
Edit :
$.ajax({
url: 'http://www.somesitename.com/admin/exportToCSV',
type: 'GET',
data:{},
cache: false,
success: function() {
alert("sucess");
},
error: function () {
alert("error");
}
});
exportToCSVAction function in php as:
public function exportToCSVAction()
{
$exportBatch = 10;
$order = $this->getTableGateway('order');
$select = new Select();
$select->from('order');
$data = $order->selectWith($select)->toArray();
$batchDir = __DIR__ . '/../../../../../data/export/batch/' . $exportBatch;
mkdir($batchDir);
$fileNameWithFilePath=$batchDir . '/order2.csv';
if (file_exists($fileNameWithFilePath))
{
//Code to download file
}
else
{
$csvFile = fopen($batchDir . '/order2.csv', 'w');
$i = 0;
foreach($data as $record) {
if($i==0) fputcsv($csvFile, $this->getCsvHeader($record));
fputcsv($csvFile, $this->updateCsvLine($record));
$i++;
}
fclose($csvFile);
}
}
Now with this code i am getting the alet sucess. But not downloading the file

You're getting a 404, so either there's a routing issue with your controller, or there's a fatal error somewhere in your controller action. One way to debug the controller action is try putting an error_log at the beginning of the exportToCSVAction function, something like:
error_log("BEGINNING OF FUNCTION");
Then check your apache error log and see if it logged the error. If it does log the error, then try putting another error_log statement after other statements inside the function and see if those are logged. You'll know which statement is causing the script to die if an error is not logged.

Related

How do you run Classes from an external file from the functions.php in Wordpress?

How do you run Classes from an external file from the functions.php?
I'm using WordPress and the Beaver Builder plugin. I have a pagination list with info from the WP db. This is on a page using a search template (search.php). It includes a file (get-jobs.php). In order to see the results, I have to use a PHP Snippet plugin to set a global variable on the page that recognizes the $result variable provided by get-jobs.php, as I use the built-in modules to layout the page.
This works so far. I can see my formatted results.
When the pagination button is clicked, a function is called from my js file(custom-script.js) to update the results.
function selectJobs() {
$.ajax({
url: site_url + '/get-jobs.php',
type: "GET",
data: {
ajax': '1',
'state': GetURLParameter('country'),
'limit': GetURLParameter('limit')
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
This doesn't work and I received a 403(Forbidden) error. I changed it to this:
function selectJobs(country) {
var country = country;
$.ajax({
url: ajaxurl,
type: "POST",
data: {
'action':'country_ajax_request',
'country' : country
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
...which got rid of the error, and submitted the request.
In my functions.php, I have this:
function country_ajax_request() {
//include_once( get_stylesheet_directory() .'/get-jobs.php');
MY FUNCTIONS GO HERE
}
add_action( 'wp_ajax_country_ajax_request', 'country_ajax_request' );
add_action( 'wp_ajax_nopriv_country_ajax_request', 'country_ajax_request' );
Here's an bit of what's in get-jobs.php:
<?php
$get = (!empty($get) ? $get : $_REQUEST);
if(isset($get['ajax']) && $get['ajax'] == 1) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
}
class GetJobs {
private $wpdb;
public function __construct($input) {
global $wpdb;
$this->wpdb = $wpdb;
$this->tableName = $this->wpdb->prefix . 'job_postings';
$this->country = (!empty($input['country']) ? $input['country'] : '');
$this->page = (!empty($input['page']) ? $input['page'] : '');
$this->limit = (!empty($input['limit']) ? $input['limit'] : 10);
}
public function getLocations() {
$result = [];
$states = $this->wpdb->get_results("SELECT country FROM " . $this->tableName . " WHERE deleted_at = '0000-00-00 00:00:00'");
foreach ($country as $key=>$row) {
$result[$row->country] = $row->country;
}
return $result;
}
// almost 200 more lines of this
}
$get['page'] = (!empty($get['page']) ? $get['page'] : 1);
$jobs = new GetJobs($get);
$query = $jobs->getQuery();
$jobsQuery = $jobs->getJobsQuery($query,(!empty($get['limit']) ? $get['limit'] : $jobs->limit));
$result['postings'] = $jobs->formatPostings($jobsQuery);
if(isset($get['ajax']) && $get['ajax'] == 1){
echo json_encode($result);
}
I tried to include the file, but that didn't work. It pulled data, but didn't seem go through the functions.
I want to reuse the existing file to perform the update list task. I don't want to rewrite get-jobs.php, if possible. I've used this same code just fine on other projects. Just not with this plugin.
Any thoughts or assistance as how I can approach this problem is appreciated.
Thanks.
UPDATE
I took another look at that include. It is pulling data. However, it's generates a json file, following by all of the html. The HTML is malformed. Here's what the beginning looks like:
<div id="postings" style="display: block;">{"states":{"AB":"AB","AZ":"AZ","BC":"BC","CA":"CA","FL":"FL","GA":"GA","IL":"IL","KS":"KS","NC":"NC","NS":"NS","ON":"ON","PA":"PA","QC":"QC","WA":"WA"},"category":{"":"","Accounting":"Accounting","Customs":"Customs","Finance":"Finance","Human Resources":"Human Resources","IT":"IT","Information Technology":"Information Technology","International":"International","Marketing":"Marketing","Marketing and Communications":"Marketing and Communications","Operations":"Operations","Project Management":"Project Management","Reception":"Reception","Sales":"Sales","Warehouse":"Warehouse"},"postings":"\n\t\t\t\t\t

How to post a value to a controller function on button click using Ajax and also redirect to new page at the same time?

I have a button Next that changes the page -
<a class="disabled" href="step">
<button class="btn btn-primary launch-btn disabled next">NEXT</button>
</a>
Also, when this button is clicked, I have an Ajax function that sends data to a controller function -
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: a,
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
And I'm using this to receive the value from Ajax -
public function CreateData() {
$data = $this->input->post('data');
return $data;
}
When the Next button hits its controller where it changes to a new page, I'm trying to retrieve the value posted by Ajax to the CreateData() function -
public function step()
{
$data = $this->CreateData();
if(!empty($data)){
print_r($data); exit;
}
else {
echo "blank"; exit;
}
$this->load->view('step2');
}
However, this keeps echoing blank. This obviously means that the $data being returned is empty but I'm not sure why. The success function in my Ajax script is logging data, so it's posting the value to CreateData(). What am I doing wrong here?
Your javascript should be something like this
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: {my_data: a},
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
Notice the data property. I have changed it to an object containing the variable a.
Now you should be able to retrieve this in your php function using
public function CreateData() {
$data = $this->input->post('my_data');
return $data;
}
Adr's answer solved part of the problem. In order to actually store and access the data, storing it in the session instead of a variable did the trick -
public function CreateData() {
$data = $this->input->post();
$this->session->unset_userdata('createData');
$this->session->set_userdata('createData', $data);
}
This prevented the $data variable from being overwritten when called the second time.

Using javascript function to load a view

I trying to load a view into my div #teste with this.id through JavaScript without success. What's wrong on my function?
JavaScript function below
<script type="text/javascript">
var baseurl = '<?php site_url(); ?>'; //raiz do website
function navbutton(id) {
$.ajax({
type: 'GET',
url: baseurl+'main/'+id,
dataType: 'html',
success: function(html) {
$('#teste').html(html);
}
});
}
HTML button
<li>Contato</li>
My main Controller (one function to call all others views)
class Main extends CI_Controller {
var $_data = array();
public function index()
{
if (!$this->uri->segment(1) && !$this->uri->segment(2)) {
$view = 'inicio';
}
if ($this->uri->segment(1) && !$this->uri->segment(2)) {
$view = $this->uri->segment(1, 'inicio');
}
if ($this->uri->segment(1) && $this->uri->segment(2)) {
$view = $this->uri->segment(1, 'inicio') . '/' . $this->uri->segment(2, '');
}
if (!file_exists(APPPATH . 'views/' . $view . EXT)) {
$view = "404";
header("HTTP/1.0 404 Not Found");
}
$this->load->view('templates/header');
$this->load->view($view, $this->_data);
$this->load->view('templates/footer');
}
to avoid to get 'Uncaught ReferenceError: navbutton is not defined' error
attach on click event function with javascript:
var baseurl = '<?php site_url(); ?>'; //raiz do website
function navbutton(id) {
$.ajax({
type: 'GET',
url: baseurl+'main/'+id,
dataType: 'html',
success: function(html) {
$('#teste').html(html);
},
error:function(v1,v2,v3){
alert('Something went wrong'); }
});
}
$("#contato").on('click',function(event){
event.preventDefault();
navbutton(this.id);
});
And on HTML use
<li>Contato</li>
JSFIDLE test - in this example the ajax request will get error 404 because the url is not defined proper but in you code must work.
HINT to make sure all code is in the proper place, take a look in the source code of page after is loaded in browser (CTRL+U)
Are you trying to load string to element? In that case you need to pass third argument TRUE when loading view method.
$view = $this->load->view('templates/header', '', TRUE);
$view .= $this->load->view($view, $this->_data, TRUE);
$view .= $this->load->view('templates/footer', '', TRUE);
echo $view;
Check in docs here.

How to avoid 500 Internal Server Error if a JS session variable null

I created this script to read from various web sources. This script updates all notifications (mail, post, friends) and their own drop-down window's details and also two side update bars together. I used this script in my top manu.php page.
This script is working well for login user.
Now I pass a session id variable with JavaScript var uid = '<? echo $session->id; ?>'; So when a user is not logged in, my browser console displays 500 Internal Server Error because here the session has no ID so it passes uid= ''
How do I overcome this problem?
Here is my JavaScript script:
var uid = '<? echo $session->id; ?>';
function addmailno(type, msg){
//Do something for display mail/friend/post notification
}
function addmailup(type, msg){
//Do something for display mail/post/friend drop-down.
}
function addside(type, msg){
//Do something for display all friend/new post in side bar.
}
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
setTimeout(waitFormailno, 15000);
},
error: function(){
setTimeout(waitFormailno, 15000);
}
});
}
$(document).ready(function(){
waitFormailno();
});
serverforupandside.php
<?php
include("db.php");
include_once("mysession.php");
while (true) {
if($_GET['uid']){
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
flush();
mysqli_close($dbh);
}
}
mysqli_close($dbh);
}
?>
Your Javascript code should be modified to:
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
}
});
}
$(document).ready(function(){
setInterval(waitFormailno, 15000); // calls a function or evaluates an expression at specified intervals (in milliseconds)
});
PHP Code:
<?php
include("db.php");
include_once("mysession.php");
if (!empty($_GET['uid'])) {
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
}
}
Also, you should add validations before filling $data array.

ajax setTimeout not working on json_encode

AJAX function
var stopTime = 0;
var checkRequApprove = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkApproveReq',
success:function(output){
jsn=JSON.parse(output);
if(output==false){
stopTime = setTimeout(checkRequApprove, 3000);
}
else {
bootbox.dialog({
message: "Battle",
title: "Request Accepted",
buttons:
{
success: {
label: "Approve",
className: "btn-success",
callback: function() {
$.ajax({
"type" : "POST",
"url" : "finalBattleApprove",
"data" : {'username' : jsn.user_name},
success: function(data){
$('#example').html(data);
$('#loadingmessage').show();
}
});
}
},
}
}
});
}
stopTime = setTimeout(checkRequApprove,3000);
Controller
public function checkApproveReq(){
$id = $this->session->userdata('userID');
$requApprove = '1';
$check = $this->lawmodel->checkRequApprove($id,$requApprove);
foreach($check as $row){
if($row->requApprove == '1')
{
$reqID = $this->lawmodel->getID($row->requestedID);
foreach($reqID as $row){
echo json_encode(
array(
'user_name' =>$row->username,
)
);
}
}
else
echo false;
}
}
I have this code wherein there is a realtime check to the database and if the condition has meet..custom dialog will pop up.
Im having this problem on my checkRequApprove function..The bootbox.dialog will not showup if the condition is meet in the controller...
i believe that my problem is because in the controller which echo json_encode. I cant find any solution .im still a newbie in ajax..
EDITED
the custom dialog will only show after i refresh the page.
output is a string - the comparison output == false will always yield false, because a non-empty string is always true (not considering the edgecase "0" in which case "0" == false yields true).
Instead of
if(output==false){
...
}
it should be:
if (!jsn){ // or jsn == false if you like that better
...
}
Also you should consider not returning a simple value in your controller, but always a proper json-object like:
else{ // consider always using brackets, for more robustness
echo
array(
'error' => true
);
}
Now, in your js you just check for
if (jsn.error){
...
}
In any case, you should include an error callback for your json to handle possible errors with the json request.

Categories