Codeigniter jQuery problem - php

I am building an application with codeigniter and I want to post some data using jQuery but for some reason it doesn't work. Here is the code what am I doing wrong ?
$.ajax({
url: "<?=site_url('requests/save')?>",
type: "POST",
data: data,
success:function(msg){
alert(msg)
}
});
I haven't written any code in the controller yet, just something simple to test it. Also as long as javascript is concerned that's about it. The ajax is trigered when the user clicks a button.
function save()
{
if($this->input->is_ajax_request()) {
echo 'ajax';
}
else
{
echo'sdfs';
}
}

Dante,
First make sure you load your helper:
$this->load->helper('url');
Also post the JAVASCRIPT for us, not the PHP. The Javascript is what is failing, not the CI PHP. You might have a PHP issue also on your controller for 'requests/save', have you checked that?

I believe you need to pass a cross site request forgery token.
If you set XSS to true in your config, then your form helper creates a hidden field that is required to be passed to your server.
Make sure you are properly collecting your form data. Easiest to use jquery the .serialize() function.
Load the url helper in the autoload.php. Your url in the ajax call should just be 'requests/save'.
Also php shorthand echo tags are a bad practice stick to
<?php echo ?>
for better code portability
Moved my comment to an answer

EDIT : to test the ajax, use the relative url instead use a php tag inline in your js, to your controller, which will work in any condition (in CI) whether you already removed the index.php from your url (using htaccess) or not by include the index.php in your url.
$.post('/index.php/request/save', { foo: 'bar' }, function (html) {
alert(html);
});
At targeted controller
function save()
{
if($this->input->is_ajax_request())
{
echo $this->input->post('foo') ? $this->input->post('foo') : 'Not Bar';
}
else
{
echo'Not from AJAX';
}
}
EDIT :
also make sure you have already load the url helper before using its function
$this->load->helper('url');

Related

CakePHP 3 View to Variable

my question is give it a way to parse a view file (.ctp) into a variable ?
I want to create a ajax function that gives a ctp file or better says the content of this back.
The call from the javascript to cakephp's controller work but now i doesnt now how i can get my specified ctp file in the template folder parse it into a variable and send it back to the javascript function.
Lets say, you are using the controller sites and the view is index.
app/Controller/SitesController.php:
public function index() {
if($this->request->is('ajax') {
// prepare output for ajax. best way to do is to prevent styled output
$this->render('TestView/index');
}
}
In your TestView/index.ctp you can now prepare your output for ajax and just call the controller/action URL by AJAX:
$.ajax({
url: "/sites/index",
success: function(reponse) {
console.log(response); // here comes the output from /sites/index
}
});

CodeIgniter best practices: where to store jQuery/Ajax callback script?

I'm working with CodeIgniter 3 and I would have some advices about where storing scripts. I want to call with jQuery a php script that will send JSON datas to my Javascript function.
How to do a connection with my database inside this script using CodeIgniter database config file?
Here is my jQuery callback structure :
<?php
session_start();
header('Content-Type: text/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
$callback = array();
echo json_encode($callback);
I've stored this script in app/callback folder that I have made, but I don't know if I should store it outside app folder or not... How do you structure your CodeIgniter's projects?
Thanks for your advices :)
setup;
in your application/config/database.php configure your database connection
in your application/config/autoload.php ensure that the database library is enabled
here for more info for database setup
model;
in application/models/ create your thing_model.php which functions for accessing your database. for this example public function get_data() this function would produce your database JSON data output when called
here for more info to query your database
controller;
in your application/controllers/thing.php create an ajax function;
public function ajax()
{
if ($this->session->loggedin && $this->input->is_ajax_request()){
$action = $this->uri->segment(3);
if ($action === "pull"){
$forms = $this->thing_model->get_data();
//actions here
}
if ($action === "test"){
//actions here
echo "hello world!";
}
} else {
redirect('/homepage');
}
}
whats happening;
if ($this->session->loggedin && $this->input->is_ajax_request()){
here you are checking for security and that the request is ajax in nature
$action = $this->uri->segment(3); is grabbing a segment from the URI for actioning. eg. http://example.org/controller/ajaxmethod/this_action
if ($action === "pull"){ is returning data if your ajax was invoked to http://example.org/thing/ajax/pull
ajax;
in the jquery JSON ajax in your .js file (load the .js file in the footer of your view)
$('#buttonAction').click(function() {
//Jquery Ajax code here
$.ajax({
method: "POST",
dataType: "json",
url: global_path + "thing/ajax/pull",
data: { user_id: "1", data: "ABC" }
})
.done(function( data ) {
//process your JSON data here
});
});
whats happening;
jquery ajax datatype see here
url: global_path + "thing/ajax/pull", calls your controller ajax() method with the pull action.
notes;
in your __construct for the controller i would recommend putting in some testing here to secure only ajax requests to your function, and not the others for strict operations and unwanted unknowns.
you could put ajax to another controller if it suits your application. but this can create security headaches with duplicating checks etc.
If you want to call backend functions from jQuery you have to go with AJAX. Check docs here. See a simple example below.
$.ajax({
method: "POST",
url: "PATH_TO_YOUR_CONTROLLER_FUNCTION",
data: { field_name1: "Field value 1", field_name2: "Field value 2" }
}).done(function( msg ) {
console.log(msg);
});
If you have this script in your view (which is a php file), you'll be able to use php functions to set the path. For example:
url: "<?php echo base_url('your_controller/your_function')?>"
The db connection and all logic stays in the controller and is implemented as usual.

PHP send form data more than one form/pages

I am a PHP beginner.
I want to send a form data to more than one form/pages. Is it possible?
It sends data to use.php. But I want that it also sends data to two more PHP files: lock.php and unlock.php.
How is it possible?
Make your formdata go to one script, and simply include to the other scripts and they'll have access to the $_POST variable as well.
I use this a lot myself. I have a script where everything runs through the index.php file, but functions are stored in different php files depending on what they're doing. My index.php includes all the php files I need, and inside these php files I have scripting like this:
index.php:
<?php
include('pagename.php');
include('otherpage.php');
echo $return; //output from previous pages
?>
and pagename.php:
<?php
if( $_GET['page'] != 'pagename' )
{
return ('');
}
if( isset($_POST['var']) )
{
// some code
}
You can use Ajax on a client side. I recommend Jquery because it is very easy to start with, or you can use CURL on server side, but it is much more complicated, you can find a bunch of tutorials, just google: sending post data with curl.
Now Jquery Ajax approach:
Lets say your form has an ID of myForm:
make a selector:
$(document).ready(function () {
$("myForm").submit(function (e) {
e.preventDefault(); //prevent default form submit
var url1 = 'your path to url1';
var url2 = 'your path to url2';
var url3 = 'your path to url3';
sendAjax(data,url1);
sendAjax(data,url2);
sendAjax(data,url3);
//do the regular submit
$(this).submit();
});
function sendAjax(data,url){
$.ajax({
url: url,
type:'POST',
data: data,
success: function (data) {
//here you do all the return functionality
},
cache: false
});
});
}
What have we done here:
prevented default sending of form,
made X ajax requests, and send the form normally.
We have made a function for simple ajax handeling just to make our code cleaner.
The problem with this method is that you must make form checking in javascript before you start sending.

Receive data on php file send by jquery function

I have the following function that is called when I click on a button to submit a form:
function dadosFormularios(preenchimentoForm){
//var path = document.location.pathname;
//alert(path);
alert(preenchimentoForm);
//window.location.href = 'wp-content/themes/template/index.php';
var qstringA = '';
//dados dos campos
var nome=document.getElementById("nome").value;
qstringA = 'nome='+ nome;
//alert(qstringA);
if(preenchimentoForm==false){
alert('Please correct the errors in the Form');
}
else{
if(preenchimentoForm==true){
window.location.href = 'index.php?'+qstringA;
return false;
}
}
}
Since I'm using this way of processing the data, how can I alert my page index.php that the data sent by the function arrived on the index? I can't use a if (isset($_POST['button']..) since I send the information by the function and not through the button of the form, right?
window.location.href = 'index.php?'+qstringA;
This line is just redirecting to index.php with a query string ?nome=nome_value.
For example. index.php?nome=nome_value
So, in your index.php You can simply get everything posted with $_GET.
Check it by doing a print_r($_GET); there.
In index.php, you can simply check
if(isset($_GET["nome"])){
//Nome is set
//Do something here
}
P.S. Although, without knowing the other circumstances or reasons behind usage of this function, it can be said that this function is just doing what a simple <form action=index.php> would have done.
P.P.S. Although you have mentioned jQuery in title and also tagged it, I am not sure this function is using any of the jQuery code. I think it is just a simple Javascript function.
If you're using jQuery, check out .ajax(). Just remember, it's asynchronous, so the results may not be what you think they are. You don't need to reload the whole page (which is what your window.location.href = 'index.php?'+qstringA; would do) just to submit information.
If you want to alert or something when the ajax call completes, you can define a function to call on a successful ajax call.
Use ajax() like :
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
http://api.jquery.com/jQuery.ajax/

Yii Jquery AJAX Call not firing

I have been researching and trying to learn the proper method to accomplish this. I have done the following but, I still have no change on my form. Is there anyway to see if the ajax call is even being made? Could anyone correct this code to figure out why I am not getting any change on the field in my form.
In my model I have the following function
public function standardRate($country)
{
$country_std_rate = Yii::app()->db->createCommand()
->select('AVG(rate_syr_mh)')
->from('packaging_metrics')
->where(array('like', 'country', '%'.$country.'%'))
->queryRow();
echo CJSON::encode($country_std_rate);
}
In my controller I have added this function as well as added 'countryRate' to my access control for all
public function countryRate()
{
$input_country = $_POST['country'];
$model = PackagingMetric::model()->standardRate($input_country);
echo CJSON::encode($model);
Yii::app()->end();
$this->render('countryRate',array(
'model'=>$model,
));
}
This is my Jquery call in my form
$('#PackagingMetric_std_rate').live('click',function()
{
var country = $('#country').val();
$.ajax({
type: 'POST',
url: 'PackagingMetric/countryRate',
data: {country:country},
success: function(data)
{
$('#PackagingMetric_std_rate').html(data);
}
});
});
However, nothing on my form changes with a value, I am using Yii-Debug-toolbar and not seeing any POST calls or any sql queries upon clicking the appropriate field on my form.
Rename the function in the controller to actionCountryRate()
When a post request is made to a controller, it looks for an action using the action prefix.
Your url parameter for the $.ajax(); is wrong could be wrong.
That is if you are not hiding the entry script (index.php), you will have to write:
url: 'index.php/controllername/actionname'
instead of:
url: 'controllername/actionname'
It would be better to use createUrl():
url: '<?php echo $this->createUrl('PackagingMetric/countryRate'); ?>'
(Ofcourse the echo above and how you include php code in js will depend on how you are including the js in the first place)
And name your countryRate as actionCountryRate().
I consider to use absolute url while firing an ajax call.
Try to make your url in this way, it will solve your problem.
url: '<?php echo Yii::app()->createAbsoluteUrl('PackagingMetric/countryRate'); ?>',
and your controller action name should be "actionCountryRate" because this function is hit from url, not internally called from controller, also set its accessRule if you are using access control otherwise the function will not execution.

Categories