Using javascript function to load a view - javascript

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.

Related

Ajax request with codeigniter 403 (forbidden)

I'm trying to send an value with Ajax to Controller file in Codeigniter but without success.I have searched for that problem and i now this question is made many times here,but still can't find a sultion.Hope anyone can help me.
Thanks !
Js file.
function submitSend()
{
var message = $('#sms').val();
if(message == "")
{
$("#sms").attr("placeholder", "Type a message please...");
return false;
}
$.ajax(
{
url: "<?php echo base_url();?>/mychat/send",
type: 'POST',
data:{
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'message': message
},
success: function (data)
{
window.console.log('Successful');
},
error :function(data)
{
window.console.log('Failed');
}
});
}
Controller function.It's in file called MyChat.
public function send()
{
$message = $this->input->post('message');
echo $message;
}
Add this code in your footer view before including JS file
<?php $CI =& get_instance(); ?>
<script>
var csrf_name = '<?php echo $CI->security->get_csrf_token_name(); ?>';
var csrf_hash = '<?php echo $CI->security->get_csrf_hash(); ?>';
</script>
and just call these variables anywhere you need like this
data:{
csrf_name : csrf_hash,
'message': message
},
I'm afraid you can't use PHP tags in JavaScript files, as you've mentioned you have a JS file.
You must run your PHP codes in .php files.
Perhaps you can decouple your submitSend() function a bit and make it more modular by extracting the PHP tags as well as $('#sms').val(). These can be passed to the function as parameters from where you call it (.php files).
Most probably its because of the CSRF token try disable csrf and check if its due to csrf then do whitelist the specific function in csrf config
This work for me.
/app/Config/Security.php
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection cookie.
*
* #var string
*/
public $tokenName = 'csrf_token_name';
Inside my form
<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />
in the script.js
var tokenHash=jQuery("input[name=csrf_token_name]").val();
$.ajax({
method: "POST",
url: "/somecontroller",
data: { name: "John", location: "Boston" },
beforeSend: function (xhr)
{
xhr.setRequestHeader('X-CSRF-Token' , tokenHash);
},
})
.done(function( msg ) {
console.log( "Data Saved: " + msg );
});
For Codeigniter 4
First, go to app/Config/Security.php
change
public $regenerate = true;
To
public $regenerate = false;
Note: Changing $regenerate to false is not good practice.
Second, go to app/Config/Routes.php
create your rout that you will call to preform request.
$routes->post('url', 'ControllerName::FunctionName');
Then make sure u added csrf_token() and csrf_hash() to data you want to send.
So the code will look like this:
var data= {
"<?= csrf_token() ?>" : "<?= csrf_hash() ?>",// make sure this line exists
something: "Something"
};
$.ajax({
url: "<?= base_url('url_in_routes') ?>",
type: "POST",
data: data,
headers: {'X-Requested-With': 'XMLHttpRequest'},
success: function (response){
console.log("success");
},
error: function(xhr, status, error) {
console.log("Error: " + error);
},
complete: function(data) {
console.log(data.statusText);
}
});
Controller:
class Test extends BaseController{
public function handleAjaxRequest(){
$something = $this->request->getPost('something');
// Now u can use $something to save it to ur DB or do what you want.
}
}
Other thing in Codeigniter is that when a request fails the CSRF validation check, it will redirect to the previous page by default so the user can not see the error to turn it off, go to app/Config/Security.php
change
public $redirect = true;
to
public $redirect = false;
You can't use php tag in js file
url: "<?php echo base_url();?>/mychat/send", //this line in js file is wrong
You only use php tag in script tag in .php file like this
<script>
// ... some code here
url: "<?php echo base_url();?>/mychat/send",
// ... some code here
</script>
Or add this line in header html
<script>
var BASE_URL = '<?php echo base_url(); ?>';
</script>
and use it in js file
....
url: BASE_URL+"mychat/send",
....

Difficulties using AJAX to pass input value to controller

I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}

PHP function is not echoing anything in Zend Framework

I'm working on a website where clicking on a button will cause a variable to be initialized containing the contents of the associated text field.
However, I've noticed that none of my echo commands are executed and none of the related JS-alerts are showing up either. I have already checked the debugger and know that the action requests are being validated. It's just that nothing is showing up.
My controller:
public function validateuser2Action() {
echo 'asdasdfasdf';
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if (Zend_Auth::getInstance()->hasIdentity()) {
$model = new Application_Model_User();
$emailAddress = $this->getRequest()->getPost("emailAddress");
echo 'he';
} else{
echo 'whatever';
}
}
My PHTML-file:
<script>
$(document).ready(function() {
$(".btn-test").click(function() {
var form_data = document.getElementById("textbox").value
var form_url = "/workspace/validateuser2";
var form_method = "POST";
alert("cool");
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
success: function(data){
alert(data);
},
error: function(){
alert("tpai");
}
});
})
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

Ajax not making function call to php function

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.

ajax request to codeigniter controller from javascript

I am making an ajax request from my codeigniter view in javascript function but nothing happens and the success alert (ok) pops up
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success: alert('ok'),
});
}
This is my controller it is working perfect, when i copy paste the url (used in ajax request) in my browser every thing goes good, controller makes a call to the model and it works perfect
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data['userid']= $this->search_peoplee->get_userid_from_email($email);
foreach ($data['userid'] as $row)
{
$one=$row->userid;
}
$this->search_peoplee->delete_notifications($one);
return;
}
View :
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success:function(
console.log("success");
)
});
}
Controller :
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data= $this->search_peoplee->get_userid_from_email($email);
$res=$this->search_peoplee->delete_notifications($data[0]->userid);
if($res){
echo json_encode(array('success'=>true));
}else{
echo json_encode(array('success'=>false));
}
}

Categories