codeigniter view won't show up from passing javascript/ajax parameter - php

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.

Related

JS file not loading via ajax call

So what I'm doing is that when someone clicks on search button it loads carousel's html code via ajax call, which is in another file and places under the <div id="filter_product"></div>. And it's css and js is linked in file's header and footer where I am making ajax call. I am calling only html of carousel. Let me show you my code
ajax call is
function submit() {
$.ajax({
method: "POST",
url: "<?php echo base_url() ?>public_controller/search_product",
dataType:'html',
data: {color:color, year:year, cat:cat, brand:brand, model:model},
success: function(data){
console.log(data);
$('#filter_product').html(data);
}
});
}
$(document).on('click','#serch_btn',function(){
submit();
})
controller code is
public function search_product(){
$data['cat'] = $this->input->post('cat');
$data = $this->load->view('public/result_product',$data,TRUE);
echo $data;}
If i don't call carousel code via ajax call and simply place that in index.php it is working fine. but when i call code via ajax call then it's js file is not working and display is scrambled but html is loading fine. is there any way to solve this.
thanks in advance
Function name submit is reserved. You can't use it. Try to rename it.
Suggestion: in PHP method you don't need to echo and base_url() you can use in the next way
public function search_product(){
$data['cat'] = $this->input->post('cat');
$this->load->view('public/result_product',$data);
}
//////////////////////////////////////////////////////////
url: "<?= base_url('public_controller/search_product') ?>",
Put line $('#filter_product').owlCarousel(); after $('#filter_product').html(data); in your AJAX request success function.

Pass a variable with JQuery to the Controller - PHP Codeigniter

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);
});

Pass variable from JavaScript to PHP on new page

I am pretty new to JavaScript and PHP.
I'd like to create a JavaScript function that contains a variable, passes this on to PHP on another page and opens that page.
Here is what I got so far (not working):
My JS:
function test()
{
$.ajax(
{
url: "my-new-page.php",
type: "POST",
data:
{
varJS: "XXX"
},
error:function(err)
{
alert(err.statusText);
},
success: function(data)
{
window.open("my-new-page.php");
}
});
}
My PHP (on the new page):
$varPHP = $_POST['varJS'];
As I understand your question, you just want a simple javascript function that redirects to another page / PHP-script with some params?
my-new-page.php
<?
$varPHP = $_GET['varJS'];
echo $varPHP;
?>
javascript
function reDirect(varJS) {
var page='my-new-page.php?varJS='+varJS;
document.location.href=page;
}
reDirect('test')
To just open a new window passing it a variable, you can do that within a query string.
Simply call
window.open("my-new-page.php?varJS=XXX);
And Handle Query String on my-new-page.php
-Shakir
The entire point of using Ajax is that it doesn't take the user to a new page. Don't use Ajax.
If you need to make a POST request then generate a form and hidden inputs with document.createElement and friends, append it to the current document, and then call its submit() method.

Pass values into an external js file

Hey I hope someone can help me out,
I have an external js file that resides in the webroot/js folder that I insert into my view using:
echo $this->Html->script('script');
In the js file I have an ajax request to insert data into my database:
var assetData = {
"project_id": $("#projectId").val(),
"asset_id":"??",
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData
});
In my view I created a hidden form field with the project_id so that I can get it in the js file, however the asset items are created dynamically, the are created and saved into the assets table, and now I want to update that asset with the content.
What would be the best way to get the asset? I can't get the id and save it, for example, in the div's id because it was created in the js file.
I would really appreciate any suggestions!
/assets/add should return the ID of the asset it created.
If you're inserting into a mysql database, then one option is to use mysql_insert_id (there are mysqli and pdo equivilents on the manual).
var assetData = {
"project_id": $("#projectId").val(),
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData,
dataType:'text',
success:function (data)
{
assetData['asset_id'] = (int)data;
}
});
And then your /assets/add should echo out the ID after it is created
echo $asset_id; // some INT id
So you may want to consider HTML partials. These are little bits of HTML representing anything from a single tag, to a popup. The important thing is that it does not have the or tag.
$.post('/assets/add', data, function (html) {
$('#assets').append(html);
}, 'html');
After you POST data, your call returns a snippet of HTML. You can then append that HTML to a DIV on the page.
<div id="assets">
<div class="asset" id="asset-1">
<p>Asset content</p>
</div>
</div>
In your controller (I assume it's CakePHP), you have:
if ($this->Asset->save($this->data)) {
$this->autoLayout = false;
$this->render('asset_partial.html');
}
Using the suggestions I received this is how I managed to solve the problem:
javascript file:
$.ajax({
url:'/assets/create',
type:"POST",
data:assetData,
dataType:'text',
success: function (response) {
if (response.success) {
alert("response: "+response);
} else {
//console.log(response.data, response.code);
alert("response: "+response);
}
}
});
Controller:
public function create($id = null) {
if ($this->data != null) {
$this->Asset->save($this->data);
$this->autoRender = false;
echo $this->Asset->id;
}
}

php website and Jquery $.ajax()

The website I'm developing is structured in this way:
It has a function that switches the module for the homepage content when $_GET['module'] is set, example:
function switchmodules()
{
$module=$_GET['module'];
switch($module)
{
case 'getnews': news(); break;
default: def();
}
}
As you can see, this switch calls another function for each module.
For example I wrote getNews() to work in this way:
function getNews()
{
$id=$_GET['id'];
if(!id)
{
//CODE TO LIST ALL NEWS
}
if(isset($id))
{
//CODE TO GET ONLY 1 NEWS BY ID
}
}
So, as you can see I'm not using an unique file for each module; all operations of a module are part of an unique function in which an action is switched again to change the result.
If I want to get a news from database I should use an url like this: ?index.php&module=getnews&id=1
My question now is:
With jQuery and $.ajax() method is there a way to get a news (for example) using this structure based on functions switched by a get? Or do I have to change everything and make a file for each function?
you can simply call the same url via $.ajax(). the only thing which should be changed for axjax calls is that you don't output your layout, but only the news itsself.
in php you can check for an ajax request like
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// dont output layout
}
If this code is in say 'test.php' you can do:
<script>
$.get(
'/test.php',
{
module: 'news',
id: 1
},
function( data ) {
alert( data );
}
);
</script>
And js will send GET request to test.php with needed params. Then your server script will decide how to process request.
jQuery
$(document).ready( function() {
var form = '#my_awesome_form';
$(form + ' input[type=submit]').click(function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: 'index.php',
data: $(form).serialize(),
success: function( response ) {
alert('DONE!');
}
});
});
});
HTML
<form id="my_awesome_form" // OTHERS PROPERTIES //>
// LOT OF FIELDS HERE //
<input type="submit" value="Send">
</form>

Categories