I have big array, it is result of controller
public function actionAaaa()
{
//somoethig, effect array
return $this->render('test', [
'array' => $array
]);
}
For example in view:
<pre>
<?print_r($array);
</pre>
Now I want pass this array from view to another action controller.
I don't know how do this.
I'm try:
<button type="submit" id="test" class="btn btn-lg btn-primary">Test</button>
<script>
$(document).ready(function () {
$("#test").click(function () {
var variable = <?=$array?>;
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'controller/action',
data: variable,
success: function (data) {
alert("success!");
}
});
});
});
</script>
but when I try use next controller, I don't see anything:
public function actionBBBB()
{
$request = Yii::$app->request;
$tablica = $request->post();
echo 'Tablica POST';
echo '<br />';
echo '<pre>';
print_r($tablica);
echo '</pre>';
echo '<br />';
echo 'XXXxxxXXX';
}
Any idea?
You are not able to post the entire array like that. You can however serialize it to do so:
var variable = <?serialize($array);?>
Then you can unserialize it later.
This is just one alternative. Some would say its bad. Probably is. You can also use SESSION
Related
I need to display objects of an array in a view that has been posted to controller from another view.
Jquery ajax call
details is an array with few objects
$(document).ready(function () { // working
$("#nxt").click(function() {
var tmp = details;
var more_details = JSON.stringify(tmp);
$.ajax({
type: "POST",
url: 'http://localhost/application/index.php/Welcome/detailsLoad',
data: {more_details : more_details },
success : function(){
console.log('Posted');
location.href="http://localhost/application/index.php/Welcome/detailsLoad"
},
error: function(){
alert('Error!');
}
});
});
});
Controller
public function detailsLoad()
{
$moreDetails= $this->input->post('more_details');
$this->load->view('simulation',$moreDetails);
}
View
<?php
foreach($moreDetails['more_details'] as $result) {
echo $result['object1'], '<br>';
echo $result['object2'], '<br>';
}
?>
help me to modify and fix this code
If you want to data from the ajax call to move from your controller to your view you should set the name of the variable to be used inside your view:
$data = [];
$data['moreDetails'] = $this->input->post('more_details');
$this->load->view('simulation',$data);
Then you can use the variable $moreDetails inside the view:
foreach ($moreDetails as $result) {
echo $result['object1'], '<br>';
echo $result['object2'], '<br>';
}
i am trying to make an search box which search the name from elastic search database, but when i run the it always give me an error that ----
Notice: Undefined index: value in the line --> $query = $_GET['search_keyword'];
but from my script i believe it should get the "search_keyword".
Search box --
<form method="GET" action="/latest/helloTestData">
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</form>
Script --
<script>
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
$.ajax({
type: "GET",
url: "/latest/helloTestData", // address to the php function
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
</script>
PHP ---
public function helloTestDataAction() {
$paramss = array('hosts' => array('localhost:9200'));
$client = new Elasticsearch\Client($paramss);
$query = $_GET['search_keyword'];
if ($query != "") {
$params = array();
$params['size'] = 1000000000;
$params['index'] = 'myindex';
$params['type'] = 'mytype';
$params['body']['query']['bool']['must'] = array(
array('match' => array('name' => $query)), // search data by input data
);
$esresult = $client->search($params);
if ($esresult < 1) {
echo "Your search did not match any documents. Please try different keywords.";
} else {
echo $esresult; //results found here and display them
}
}
return new Response('ok');
}
Can anyone knows how to fix this problem. Thanks a lot in advanced.
Modifiy $_GET['value'] into $_GET['search_keyword']
So
public function helloTestDataAction() {
[...]
$_GET['search_keyword'];
[...]
}
You're searching for a key that will not be into $_GET array, as, into your ajax request, you're passing a key named search_keyword and so this is the error
Simply replace
$_GET['value'] to $_GET['search_keyword']
Quick and simple! The front-end pass the typed text via GET by url.
In this test I put the 2 files in the same folder. Change as you need.
Front-end:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="my_header" style="background-color:lightblue">
</div>
<input type="text" id="foo" value="bar" onkeyup="loadlink(this)" />
<script>
function loadlink(e){
$('#my_header').load('back.php?var='+e.value,function () {
$(this).unwrap();
});
}
</script>
Back-end (back.php):
<?php
echo "received: " . $_GET["var"] . ' <br>at ' . gmdate('Y-m-d h:i:s \G\M\T', time());
?>
Edit:
It was a problem with localhost and I think with the htaccess file. Although I couldn't make it in localhost, the script is running fine on the web host.
I want to store my form data in to the database using ajax in codeigniter. The problem is that everything is fine, except I'm getting a 500 server internal error.
My contoller:
public function order()
{
$order = $this->main_model->order($_POST);
if($order)
{
return true;
}
else
{
return false;
}
}
my model:
function order($options = array())
{
$options = array(
'client_Name' => $this->input->post('oName'),
'client_Phone' => $this->input->post('oPhone')
);
$this->db->insert('md_orders', $options);
return $this->db->insert_id();
}
and of course I'm using stepsForm script and this is the js code I have:
var theForm = document.getElementById( 'theForm' );
new stepsForm( theForm, {
onSubmit : function( form ) {
var form_data = {
oName: $('#oName').val(),
oPhone: $('#oPhone').val(),
};
$.ajax({
url: "<?php echo base_url() . 'main/order/'; ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
}
} );
and this is the HTML code:
<form id="theForm" class="simform" autocomplete="off">
<ol class="questions" id="questions">
<li>
<span><label for="oName">Your name:</label></span>
<input class="finput" id="oName" name="oName" type="text"/>
</li>
<li>
<span><label for="oPhone">Your Phone Number:</label></span>
<input class="finput ltr" data-validate="number" id="oPhone" name="oPhone" type="text"/>
</li>
</ol>
</form>
and the error I'm getting is :
POST http://localhost/123/main/order/ 500 (Internal Server Error)
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and nothing is stored in the database. What am I doing wrong?!
Try to check your input in controller before send it to model, although it is not mandatory. In your model you need just feed of your array. So you can just set name of parameter.
Your model something like this:
public function order($options) {
$data = array();
$data['client_Name'] = $options['oName'];
$data['client_Phone'] = $options['oPhone'];
$this->db->insert('md_orders', $data);
if($this->db->affected_rows() > 0) {
return $this->db->insert_id();
else {
return false;
}
}
Your controller something like this:
public function order() {
$order = $this->main_model->order($this->input->post());
if( $order !== false ) {
echo "Inserted!";
} else {
echo "Not inserted!";//These are your ajax success function msg parameter
}
}
Also, I can't see the logic of form parameter inside onSubmit property's function( form ). Maybe you could remove it?
In your view,place the following code in your script,please...
one_field = $('#one_field').val();
second_field = $('#second_field').val();
$.ajax({
type:"post",
data:{one_field:one_field, second_field:second_field},
url :'<?=base_url("directory/controller_name/your_method_name")?>',
success: function(data)
{
alert("success");
}
});
Now the place the following in your controller.
function your_method_name()
{
$your_data = array(
"table_field_1" => $this->input->post('one_field'),
"table_field_2" => $this->input->post('second_field')
);
$last_id = $this->your_model->insert_data_function($your_data);
if(isset($last_id)
{
//your code
}
else
{
//your code
}
}
In your Model,place the following.
public function insert_data_function($your_data)
{
$this->db->insert("your_table",$your_data);
return $this->db->insert_id(); //will return last id
}
Instead of using base_url() in your JS, you should try and use site_url()
Your CodeIgniter website runs through the index.php file.
The base_url() function will return the URL to your base directory.
The site_url() will return the URL to your index.php file.
Your form is trying to access "http://localhost/123/main/order" when it should be trying "http://localhost/123/index.php/main/order"
Hope this helps.
Edit
You should also have a look at the form helper.
https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
I am new to codeigniter ajax and i have a problem with sessions.My sessions are not being set and unset
asynchronously and i have to refresh the page just to see the changes.
view/header:
<?php
if(!empty($product)){
$pid=$product[0]['product_id'];
}
?>
<script>
$(document).ready(function(){
if($('.add_to_basket').find('img')){
$('.add_to_basket').click(function(){
var message=$('#badgemessage');
$('#msgcart').append(message);
message.show('slow');
var trigger=$(this);
var param=trigger.attr("rel");
var item=param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url()."cart_c/myfunk/".$pid?>',
data: { id: item[0], job: item[1] },
dataType:'json',
success: function(data) {
console.log(data);
},
error:function(){
alert("error");
}
});
return false;
});
}
});
</script>
model/basket_model:
<?php
class Basket_model extends CI_Model{
function activeButton($sess_id){
$e=$this->session->userdata('basket');
if(isset($e[$sess_id])){
$id=0;
$label="<img src='".base_url()."images/remove.png' />";
}else{
$id=1;
$label="<img src='".base_url()."images/add.png' />";
}
$out="<a href='#' class='add_to_basket' rel='".$sess_id."_".$id."'>".$label."</a>";
return $out;
}
function setItem($pide,$qty=1){
$e=$this->session->userdata('basket');
if(isset($e)){
$e[$pide]['qty']=$qty;
$this->session->set_userdata('basket',$e);
}else{
$arr=array($pide=>array('qty'=>$qty));
$this->session->set_userdata('basket',$arr);
}
}
function removeItem($pide,$qty=null){
$e= $this->session->userdata('basket');
if($qty != null && $qty < $e[$pide]['qty']){
$e[$pide]['qty']=($e[$pide]['qty']-$qty);
$this->session->set_userdata('basket',$e);
}else{
$e[$pide]=null;
unset($e[$pide]);
$this->session->set_userdata('basket',$e);
}
}
}
?>
controller/cart_c:
<?php
class Cart_c extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function myfunk($id){
if(isset($_POST['id']) && isset($_POST['job']))
$out=array();
$pid=$_POST['id'];
$job=$_POST['job'];
if(!empty($id)){
switch($job){
case 0:
$this->basket_model->removeItem($pid);
$out['job']=1;
break;
case 1:
$this->basket_model->setItem($pid);
$out['job']=0;
break;
}
echo json_encode($out);
}
}
}
?>
controller/products:
<?php
class Products extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function product($id){
$kitties['cats']=$this->catalogue_model->get_categories();
$data['product']=$this->products_model->get_product($id);
$data['active_button']=$this->basket_model->activeButton($id);
$this->load->view('header',$data);
$this->load->view('sidebar',$kitties);
$this->load->view('product',$data);
$this->load->view('footer');
}
}
?>
view/product:
<div class="contentwrap">
<div id="content_area">
<?php
$e=$this->session->userdata('basket');
print_r($e);
if(!empty($product)){
foreach($product as $p){
?>
<h1><?=$p['product_name']?></h1>
<div id="product_image">
<img src="<?=base_url()?>/images/<?=$p['image']?>" width="400" height="300" />
</div>
<div id="product_desc">
<?=$p['description']?>
<br><br>
<?=$active_button?>
</div>
<?php
}
}else{
echo "Product unavailable";
}?>
</div>
</div>
The problem is my $active_button in the product view is not changing asynchronously but the sessions are being set and unset
i can see items being pushed into and out of the session array when i refresh the page.When i hit the button my chrome console displays: object{job:0}
ok after looking and studying youre code. you can implement what you want by retrieving the button again when making your AJAX call. The way to retrieve it is by calling that model again, then using jquery to replace the current button. Try the following:
Controller - Cart_c
function myfunk($id) {
if (isset($_POST['id']) && isset($_POST['job'])) {
$out = array();
$pid = $_POST['id'];
$job = $_POST['job'];
if (!empty($id)) {
switch ($job) {
case 0:
$this->basket_model->removeItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
case 1:
$this->basket_model->setItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
}
echo json_encode($out);
}
}
}
JS in header view:
<script>
$(document).ready(function() {
function add_to_basket($this) {
var param = $this.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url() . "cart_c/myfunk/" . $pid ?>',
data: {id: item[0], job: item[1]},
dataType: 'json',
success: function(data) {
console.log(data);
$this.replaceWith(data.active_button);
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
},
error: function() {
alert("error");
}
});
return false;
}
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
});
</script>
Ok I think perhaps we should start by discussing the proper flow of your app. Assuming that your URL looks something like this Products/product/10 and you intially load the page, your function runs providing you with right button and products as expected.. Lets say in this case product 10 does not exist in the session/cart so you see the ADD image button come up.. All good.. Now, when you click add, and from what you are saying, it adds the product to the session/cart, and you get a return JSON of ‘job:0’. So far it works as expected from the code I am seeing. A return of job:0 means that you ran the setItem function. Now the problem you are saying is that the view “is not changing asynchronously”. By this, do you mean that you expect the page to reload and run the function again so that the image can now say “remove”?
This function, ajax ... every thing is working well.
When I want to reload the $users it return the same $users
Is there any way after loading ajax to reload the $users with new data?
Controller
function list_of_users_by_skills($project_ids){
$project_id = json_decode($project_ids);
/* Generate Users by Skills
* By Isaac
*/
$this->loadModel('Training');
//Get list of users by skills
$users_return = $this->Training->find('all', array('conditions' => array('Training.Project_id' => $project_id)));
//some code here to return the $users :)
asort($users);
$this->set('users', $users);
}
View
var page = 'http://localhost/index.php/shifts/list_of_users_by_skills/[176,196]/';
console.log(page);
$.ajax({
url: page,
success: function(data) {
<?php echo "var user_array = [" . json_encode($users) . "];\n"; ?>
console.log(user_array);
console.log(<?php echo json_encode($users); ?>);
}
});
You have hard-coded your users variable in your javascript:
<?php echo "var user_array = [" . json_encode($users) . "];\n"; ?>
This will only be filled once, on the initial page request.
You need to make sure that the script that you are calling with ajax, returns the actual user list and use that:
Something like:
$.ajax({
url: page,
dataType: "json",
success: function(data) {
var user_array = data;
console.log(user_array);
}
});
And your page script should do something like this at the end:
echo json_encode($users);
you're pushing the same user_array on the succes callback...
You should declare the var before the function and overwrite the var ín the function{
var page = 'http://localhost/index.php/shifts/list_of_users_by_skills/[176,196]/';
var users = [<?php echo json_encode($users); // or make in an array so json_encode is sufficient ?>];
$.ajax({
url: page,
success: function(data) {
users = data.users;
}
});
where you're gateway (the PHP side of things) would return an array (or object) with a key 'users' => array(user1, user2 etc etc);