First of all thanks all for your help, it's very useful. Im starting with yii and Im a bit lost yet.
I have create a jquery script where I validate a form and then I send it to my controller to work with it and save in the db.
But Im doing it wrong I think I cant connect with my controller. Here is the code:
Jquery script(after all the validate stuff, the variables are fine):
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
data:
{
post_nombre: nombre,
post_empresa: empresa,
post_fechaI: fechaI,
post_fechaF: fechaF,
post_descripcion: descripcion
},
success: function(result)
{
alert(result);
}
});
And my controller ProcesoController:
public function actionGuardarProceso(){
$nombre = $_POST['post_nombre'];
$empresa = $_POST['post_empresa'];
$fechaI = $_POST['post_fechaI'];
$fechaF = $_POST['post_fechaF'];
$descripcion = $_POST['post_descripcion'];
echo $nombre;
}
Im not working with the db yet, I only want to see if I have done it well and the alert(result) shows me the content of $nombre, but instead of that the alert shows me all the html code of the view(yes all xD)
I have done it too:
public function accessRules()
{
return array(
array(
'allow',
'actions'=>array('index','guardarproceso'),
'users'=>array('*'),
),
);
}
But nothing...
Anyone cuold help me or give me some idea? Thank you all again
1st error: url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
replace guardarproceso with guardarProceso
2nd error:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
dataType is missing; it should be json
read here http://api.jquery.com/jquery.post/
also, in the controller action actionGuardarProceso, use:
echo json_encode(array('key'=>$nombre));
exit
If a ajax or jquery result prints the html of the page its usually a error in the url.
check your network jumps to see if it goes to the controller action you want.
also baseurl is slower than createUrl. try Yii::app()->createUrl and edit that until it goes to the correct destination.. But the base of my theory is that your url is incorrect.
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
data:
{
post_nombre: nombre,
post_empresa: empresa,
post_fechaI: fechaI,
post_fechaF: fechaF,
post_descripcion: descripcion
},
success: function(result) {
alert(result);
},
error:function(jqXHR, textStatus, errorThrown){
alert('error::'+errorThrown);
}
});
first try this you will get post data or not
public function actionGuardarProceso(){
echo "<pre>";
print_r($_POST);
exit;
}
if not getting any data , try with your model
public function actionGuardarProceso(){
$model = new modelname;
echo $_POST['modelname']['post_nombre'];
exit;
}
else try with the following
public function actionGuardarProceso(){
echo Yii::app()->request->getPost("post_nombre");
exit;
}
i hope you will get now from the above any methods
Related
I would like this function:
After I select an option I want to update right away the database and then show it right away also inside a certain div. How can I achieve this?
Here's my HTML:
<select id="category1" name="cat1">
<option>Hardware</option>
<option>Software</option>
<option>Network</option>
</select>
AJAX code:
$('#category1').on('change',function(){
var data = $("cat1").val();
var ticket = '<?php echo $ticket_details[0]["cTicketNo"];?>';
if(data){
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo base_url();?>User/TicketView/update_cate",
data: {data: data,ticket: ticket},
success:function(response){
alert('successful');
},
error: function(response){
alert('tangina!');
}
});
}
});
Controller:
function update_cate(){
$this->TicketView_m->update_cat1();
redirect($_SERVER['HTTP_REFERER']);
}
Model:
function update_cat1(){
$ticket_id = $_POST['ticket'];
var_dump($cat = $_POST['data']);
$this->db->set('vCategory',$cat);
$this->db->where('cTicketNo',$ticket_id);
$this->db->update('tconcerns');
}
THanks for all the help!
Drop that redirect($_SERVER['HTTP_REFERER']);, You don't need that.
First of all, AJAX will allow you to send data to server without redirecting to another page.
Based on your AJAX dataType. It is JSON. So for you to get the result, You have to encode it to JSON like json_encode(['result' => 'things you want to show']).
Then you can access it in your response like this:
success:function(response){
alert('successful');
var res = response.result; //Access the JSON
$("#certainDiv").html( res ); //Print to the div you want
}
And it is also better to get the post request in your controller then pass it to your model:
function update_cate(){
$ticket_id = $this->input->post('ticket');
$cat1 = $this->input->post('cat1');
$this->TicketView_m->update_cat1($ticket_id, $cat1);
echo json_encode(['result' => 'things you want to show']);
}
I am new in codeigniter. I am writing a code. AJAX response is not returning.
Here is my controller:
public function getValue()
{
$this->load->helper('url');
$data = array(
'username' => $this->input->post('username'),
'email'=>$this->input->post('email'),
'address'=>$this->input->post('address')
);
echo json_encode($data);
die;
}
and it is view code:
$( document ).ready(function() {
$('#btn_submit').on("click", function(event){
event.preventDefault();
var username = $('#username').val();
var email = $('#email').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/MyApp/getValue",
dataType: 'json',
async:true,
crossDomain:true,
data: {username: username, email: email, address: address},
success: function ( data) {
console.log(data);
},
error: function ( data ) {
console.log('error');
}
});
});
});
I am new with codeigniter, so I don't know how to return response and work with AJAX. I have coded with the help of web but still getting errors. Please guide me how to fix this. Thanks
Simple answer remove die; from the getValue() function.
Codeigniter does not actually output anything until after the controller finishes execution. The call to die; short circuits the normal operation of the framework and so nothing gets output. In other words, echo json_encode($data); never actually happens.
Please try after setting content-type for the response like below.
header('Content-Type: application/json');
echo json_encode($data);
die;
Ajax response expects json data since your code set dataType: 'json'
After looking at a solution on ci-ajax-csrf-problem I added the following line into the script and it works fine.
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
inserted into
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
data: post_data,
Thank you for the help everyone :)
I am new to Ajax/Jquery and was following a guide on Ajax for CodeIgniter from jorge torres to implement a simple ajax call on my website and ran into problems.
I created a Controller Ajax and this is the code snippet.
class Ajax extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function test() {
$output_string = 'This is a test';
echo json_encode($output_string);
}
public function test2(){
$this->load->view('test.php');
}
}
And this is the view for that controller, its identical to the one from the tutorial except I added loaded the url helper $this->load->helper('url'); on the first line
Here is the snippet for the script code.
The #getdata is a button type and #result_table is a div
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url().'ajax/test';?>',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
I can successfully access localhost.com/codeigniter/ajax/test2 but when I clicked the button, nothing happen.
I tried looking at the page source info and the url is correct
$.ajax({
url: 'http://localhost/codeigniter/ajax/test',
type:'POST'
....
Accessing localhost/codeigniter/ajax/test directly is also possible and it display the output message.
I am using CodeIgniter 2.1.3 and my localhost is running on XAMPP 1.7.3
Thank you in advance :)
After looking at a solution on ci-ajax-csrf-problem I added the following line into the script and it works fine.
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
inserted into
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
data: post_data,
Thank you for the help everyone :)
Did your .click() event handler works as expected?
$('#getdata').click(function(){
alert('clicked');
........
if no, try to wrapped the jquery code in $(document).ready(function() { ... }); as #Sudhir suggested:
$(document).ready( function() {
$('#getdata').click(function(){
alert('clicked');
........
});
if yes, in case you don't know it yet, there's a tool called firebug to check your AJAX request.
I thinks there's no problem with your AJAX url.
So far, this is my answer. Hope this helps too.
Do you have output compression enabled(gzip) in your config.php? If you compress your output it will fail when you use echo and return the 500 server errors.
I think there is an issue with your ajax call . Should be like this I think :
$(document).ready (function () {
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
If the firebug console says that The action you require is not allowed, then it may be a CSRF token issue, turn it off in the codeigniter config.
Add this in config file.
$config['csrf_protection'] = FALSE;
Hope this helps :)
Have you tried
$(document).ready (function () {
$('#getdata').click(function(){
$.ajax({
url: '/ajax/test',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
as apposed to <?php base_url; ?>
Have you entered your site url into the CI config?
I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.