I am working on a project using PHP Codeigniter. I want to know how can I sent a variable with JQuery to the controller. Below is my code
<script>
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id", {id: id}, function(page_response)
{
$(".modal-body").html(page_response);
});
}
</script>
Here I'm first getting the variable 'id' from function parameter. But when I run this code, it return the string 'id' instead of the actual user id from database. I want to view the user id. Below is my function from the controller..
public function Reset_User_Password()
{
$data['admin_id'] = $this->uri->segment(3);
$this->load->view('admin/user/reset_user_password', $data);
}
Send data by POST method is not append in url as GET method. So you can't get is using $this->uri->segment().
Instead use
$data['admin_id']=$this->input->post('id');
Use
$this->input->post('id');
Don't use $this->uri->segment(3); because you are posting id by post method if you want to use $this->uri->segment(3); then do a minior miodification in your function
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/"+id, function(page_response)
{
$(".modal-body").html(page_response);
});
You can take help with this code. It is working perfectly at my end
function Reset_User_Password(){
var currentpwd= document.getElementById("currentpwd").value;
var newpwd = document.getElementById("newpwd").value;
var cnfrmnewpwd = document.getElementById("cnfrmnewpwd").value;
var url = "<?php echo base_url('user/changepwd'); ?>"
$.ajax({
type:"POST",
data:{currentpwd:currentpwd,newpwd:newpwd,cnfrmnewpwd:cnfrmnewpwd},
url:url,
success:function(data){
if(data){
$('#newsleter').html(data);
}
}
});
}
try below code
you should get that id variable from GET method on the controller.
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id="+id
$(".modal-body").html(page_response);
});
Related
I Like to store a id in session using AJAX in laravel,In normal php and jQuery i am using the following method ,& how to attain the same in laravel
Normal Method:
$('.action').click(function(){
var editaction=($(this).attr("id"));
$.ajax({
type:"POST",
url:"test_session.php",
data:"test_id="+editaction,
success:function(results){
window.location.href="newredirect.php"
}
});
});
You can use same js code for Laravel. But you need to change "test_session.php" with your route url and "newredirect.php" with redirect route url.
Example Code:
$('.action').click(function(){
var editaction=($(this).attr("id"));
$.ajax({
type:"POST",
url:"ROUTE URL",
data:"test_id="+editaction,
success:function(results){
window.location.href="REDIRECTED ROUTE URL"
}
});
});
Here is example how to save session in Laravel Controller:
public function ExampleRoute(Request $request){
$username = Input::get('username');
if($username){
$request->session()->put('username', $username);
return 'success';
}
}
If you want to get your session, you can use that controller example:
public function ExampleRouteOfGetSession(Request $request){
$username = $request->session()->get('username');
return $username;
}
You can see Laravel Documentation for more information - https://laravel.com/docs/5.4/session#using-the-session
I am trying to send two variables through ajax into the php script in laravel.
It is actually not clear to me how to move these variables.
Would you mind guys to give me some advice on it? the newComment contains some string, and id is just a number.
var newComment = document.getElementById('newComment').value;
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id},
success:function(){
alert('success');
},
error:function(){
alert('failure');
}
});
});
Here is my route:
Route::any('/editcomment/{id}/{newComment}', 'HomeController#editComment');
And here goes the function in homecontroller:
public function editComment(){
$aaa = Input::all();
return $aaa;
}
I am struggling with this for last 2 days, constantly looking at documentations and tutorials but have no idea how to do this.
You don't need to add the variables to the url for this request. The data you include in your ajax request will be send to the server as a post body.
Try changing the route to Route::any('/editcomment', 'HomeController#editComment');
And use
public function editComment(){
return Input::all();
}
This should display the id and the newComment
you have to change your route file like this :
Route::any('/editcomment', 'HomeController#editComment'); because yo dont need to ajax request parameter to send in route file.
And yes in your controller method editComment change like this:
public function editComment(){
if(Request::ajax()) {
return Input::all();
}
}
We have to check that requested by ajax call.
Try,
$_GET['newComment'] and $_GET['id']. This will work.
Thank you :)
I have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>
I'm integrating codeigniter with phpgrid, and I'm having a trouble with passing the row values from phpgrid (in VIEW A) to another view (VIEW B) through javascript and codeigniter controllers
I have a virtual column like this in PHPGRID (VIEW A):
$col_formatter = <<<COLFORMATTER
function(cellvalue, options, rowObject, rowid){
var sessid = rowObject[0];
return '<input type="button" value="View" onclick="btnView('+sessid+')">';
}
COLFORMATTER;
and the javascript in VIEW A:
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
}
});
return false;
}
in the Codeigniter CONTROLLERS:
public function tes(){
$data['sessid'] = $_POST['sessid'];
$this->load->view('view_b', $data);
}
I can't seem to load the view. I used Mozilla's Firebug to know the response, it's true that the response is the code of my view_b view, but how can I switch to that view?
//Your are using ajax for some operation and want to reload the view page the you can test these options:
1) take a div in current view page and assing ajax retrun message to that div
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
$("#divid").html(msg);
}
});
return false;
}
//Or 2)just redirect to your view page again
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
window.location.href=path to your view page;//<?php echo base_url()."index.php/controller/function"; ?>
}
});
return false;
}
If I understand correctly you want to go from VIEW A to VIEW B (meaning an actual change in the window location) and pass a value to VIEW B so it can generate some dynamic content. Well, AJAX is not the solution here since it will not trigger a change of page but instead will return the markup/text of the response as a string.
But there are still a number of ways you can achieve what you want, using Codeigniter the simpler way would be to use an argument for your controller method that you can send as part of the uri in a link:
HTML
View
Since you're using Javascript to generate the markup you would need something like this
return 'View';
*Note that you will now have a link instead of a button but you can use CSS to style it any way you want it.
You would now retrieve the value in your controller like this:
PHP
public function tes($sessid){
$data['sessid'] = $sessid;
$this->load->view('view_b', $data);
}
Pretty simple. A second option will be to use a form instead of your button to send the value using either GET or POST, forms do trigger a change in page whenever they are submitted:
HTML
<form action="http://example.com/index.php/main/tes" method="get">
<input type="submit" value="{ssid}" name="sessid" />
</form>
Again using javascript:
return '<form action="<?php echo site_url('main/tes')?>" method="get">'
+'<input type="submit" value="'+sessid+'" name="sessid" />'
+'</form>';
And to get the value in your controller:
PHP
public function tes(){
$data['sessid'] = $_GET['sessid']; //OR $_POST['sessid']
$this->load->view('view_b', $data);
}
Turns out that passing a variable from javascript to codeigniter controller is just:
function btnView(sessid){
window.location = "printvo/"+sessid;
}
I was using ajax because I don't know how to pass the variable, I always thought that passing variable is using brackets: window.location = "printvo("+sessid+")"; and that didn't work.
I have a CodeIgniter MVC application.
I have a model called city that has a method:
<?php
class Cities_model extends Model{
function Cities_model(){
parent::Model();
}
function get_cities($id = null){
$this->db->select('id, city_name');
if($id != NULL){
$this->db->where('country_id', $id);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->city_name;
}
return $cities;
}else{
return FALSE;
}
}
...
Controller:
function Post(){
$this->load->helper('form');
$this->load->model('cities_model');
$this->load->model('country_model');
$this->load->model('field_model');
$data['cities'] = $this->cities_model->get_cities();//optional $id parameter
$data['countries'] = $this->country_model->get_countries();
$data['fields'] = $this->field_model->get_fields(); //subject field
$this->load->view('post_view',$data);
}
This method is used to fill the contents of a dropdown list. I have a similar model for countries, which also has a dropdown.
You can see that the get_cities method is set up to accept a country_id. This would be used to filter the results if a country was selected.
My question is I need help calling this method using Ajax (preferably jQuery). I'm new to ajax and have never done anything like this before.
Any help most appreciated!
Billy
UPDATE
I've added jquery library and have created method in my controller:
function get_cities($country){
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
here is my javascript on my view:
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>home/get_cities/"+country_id,
data: ({country : country_id}),
success: function(cities){
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
});
});
});
This is the json reply:
[{"2":"Accra"}]
So it is successfully retriving the correct data. the only problem is it's adding blank values/text to the drop down. and each time I change the city the data is being added on, so I guess i'd have to clear the dropdown first?
extending Alpesh's answer:
you should have a controller's function which return cities filtered by country:
/controller/get_cities/<country>
i'm assuming that your controller's function will return a json object, you can obtain it by doing:
function get_cities($country)
{
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
then on the view you'll have 2 select boxes:
one filled up with the contries
one empty and to be filled up with the cities retrived via ajax
now, you have to write something like Alpesh did in order to retrive the cities of the selected country; URL will be
url: '/controller/get_cities/'+country_id
while the success function would be something like
success: function(cities)
{
$('#cities').empty();
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
UPDATE
in your ajax success function you are dealing with a json objects, infact you are doing this:
opt.val(city.value);
opt.text(city.text);
where city is a json object and value and text are its properties.
when you generate the json via php you have to respect what you use in jquery so your model should return an array like this:
array
(
array("value"=>"2","text"=>"Accra"),
array("value"=>"3","text"=>"Kumasi"),
....
);
the json_encode that array and it should work. Maybe you don't need to wrap the model call into an array but i'm not sure depens on how you return the array
echo(json_encode(array($this->cities_model->get_cities($country))));
or
echo(json_encode($this->cities_model->get_cities($country)));
You can do it this way by jquery -
lets say you have 'country' as an id for the select for country -
then on change of country you can bring it's specific cities as follows -
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "the url you want to call",
data: ({id : country_id}),
success: function(cities){
//populate the options of your cities dropdown here.
}
});
});
});
you can refer detailed documentation here -
JQuery
Ajax API
Ajax