Return a view with data from ajax - ajax

I has a error 500 when return a view with data from a Controller (Codeigniter 4) to ajax function:
In Codeigniter 3 no has this problem an is OK when
$this->load->view('some');
but un CI4 not use this method for show the view.
In Codeigniter 4:
JS:
<script>
function insertFotosNew(url){
var form = document.querySelector('#new-fotos-form');
var fd = new FormData(form);
$.ajax({
type: "POST",
url: '<?=base_url('subir_fotos')?>',
data: fd,
contentType: false,
processData: false,
success: function (resultado) {
console.log(resultado);
$('#card-fotos').html(resultado);
},
error: function (resultado) {
alert('Se ha producido un error al conectar con el servidor.');
}
});
}
The controller:
/**
* #return View
*/
public function run(){
$todo = $this->request->getPost();
$files = $this->request->getFiles();
$data = array();
if(count($files) > 0) {
$this->respuesta = $this->propiedadNewFotoUpload($todo['id_producto'], $files);
$data['fotos'] = $this->productosFotosRepository->getProductoFotos($todo['id_producto']);
} else {
$this->respuesta->mensaje = 'No hay ficheros para subir';
$this->respuesta->estado = EXIT_ERROR;
}
//return json_encode($this->respuesta);
return view('Administracion/Propiedades/propiedades_form_fotos',$data);
}
}

You have to echo your view, not returning it.
echo view('Administracion/Propiedades/propiedades_form_fotos',$data);
Go check the documentation and CI4's one is pretty good. https://codeigniter.com/user_guide/general/common_functions.html#view

Related

Laravel: update function creating new record instead of updating existing one

Hi guys i am trying to update my existing record in my edit page..so when i clicked on update button it is creating new record instead of updating existing one
Here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = new Qtype_editor();
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
And i have ajax call where i am updating records from ajax
Here is my ajax code
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#qtype_json').val();
var sort_order = $('#sort_order').val();
var jasondata = $('#jasonData').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log(sendInfo);
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
Here is my route file:
Route::post('eqtype-editor/update', 'QtypeEditorController#update');
Can anyone help me where i did mistake..thanks in advance.
There are two ways to achieve update of records
One - minor change in your code to just get it working
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
Second:
Following Laravel conventions - The Laravel Way
Route definition should be: PUT/PATCH methods for resource update
Route::match(
['PUT', "PATCH'],
'eqtype-editor/{qtype_editor}', //qtype_editor param for route model binding
'QtypeEditorController#update'
);
public function update(Request $request, Qtype_editor $qtype_editor)
{
//$qtype_editor will be resolved via route model binding
//object representing db record with id of $qtype_editor passed from frontend
//$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
Javascript
$.ajax({
url: `/eqtype-editor/${edit_qtype_id}`, //add the id to the route
type: "PUT",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});

Column can not be null in ajax laravel update function

Hi guys i am sending my updated values from ajax to my update function.i am getting error as "Column cannot be null"
Here is my input which i am sending json data:
<input type="text" id="jsonData" name="jsonData">
And here is my ajax form:
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#jsonData').val();
var sort_order = $('#sort_order').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log('json',jasondata);
//return false;
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
window.location.href ="/eqtype-editor";
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
and here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
From ajax when i console i am getting my json data..i am getting error as qtype_json cannot be null.
Can anyone help me where i am missing it.
Thanks in advance.
You use a wrong key for your data.
Change the line in your controller:
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
to
$qtype_editor->qtype_json = json_decode($request->input('qtype_json'));
and it will work.

WooCommerce programmatically deleting from cart

How do I programmatically remove an item from the Woocommerce cart using AJAX? I tried putting a function in my functions.php file and accessing that but nothing gets deleted. I tried hard-coding product 299 but it doesn't delete. Here's what I did:
functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = 299;
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
}
return true;
}
themes/mine/main.js
$.ajax({
type: 'POST',
dataType: 'text',
url: "http://www.../wp/wp-content/themes/mine/functions.php",
data: {
action: 'remove_item_from_cart'
},
success: function( data ) {
console.log(data);
}
});
Use proper ajax method of wordpress like this: This worked fine for me.
//functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
//main.js
$.ajax({
type: "POST",
url: 'http://localhost/your_site/wp-admin/admin-ajax.php',
data: {action : 'remove_item_from_cart','product_id' : '4'},
success: function (res) {
if (res) {
alert('Removed Successfully');
}
}
});
This seems to work.
HTML:
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
?<
<button class="remove-item" data-cart-item-key="<?=$cart_item_key;?>">
remove item
</button>
<?
}
?>
Javascript:
$('.remove-item').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'remove_item_from_cart',
'cart_item_key': String($(this).data('cart-item-key'))
}
});
});
In functions.php, inside the template folder:
function remove_item_from_cart() {
$cart_item_key = $_POST['cart_item_key'];
if($cart_item_key){
WC()->cart->remove_cart_item($cart_item_key);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
For WooCommerce 3.0+ you can do it using the built-in remove_cart_item() function
function findCartItemKey($cartItems, $productId){
foreach($cartItems as $cartKey => $item){
$product = $item['data'];
if($product->get_id() == $productId){
return $cartKey;
}
return false;
}
}
global $woocommerce;
$cartItemKey = findCartItemKey($woocommerce->cart->get_cart())
$woocommerce->cart->remove_cart_item($cartItemKey);

500 Internal server error in cakePHP 2 while trying to request using ajax

I get 500 internal server error if try get data from another Model(Product) in Cart model. using ajax. But if I only comment out the $this->Product->findBy(id) is working fine.
$('form#add_form').on('submit', function(e){
var thisForm = $(this);
$.ajax({
url: thisForm.attr('action'),
type: 'POST',
//dataType: 'json',
data: thisForm.serialize(),
success: function(count) {
var total_items = $('p#total-items');
total_items.html('Total items: ' + count);
console.log(count);
}
});
e.preventDefault();
});
this is my CartsController
class CartsController extends AppController {
public $uses = array('Product', 'Cart');
public function add() {
$this->autoRender = false;
$itemsInCart = $this->Session->read();
if ($this->request->is('POST')) {
$item = $this->Product->findBy($this->request->data['Cart']['product_id']);
}
echo $this->request->data['Cart']['product_id'];
}
}
there is no findBy method
You must change your controller code like this:
class CartsController extends AppController {
public $uses = array('Product', 'Cart');
public function add() {
$this->autoRender = false;
$itemsInCart = $this->Session->read();
if ($this->request->is('POST')) {
$productID = $this->request->data['Cart']['product_id'];
$item = $this->Product->findById($productID);
}
echo json_encode($this->request->data['Cart']['product_id']);
}
}

how to retrieve data sent by Ajax in Cakephp?

I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax.
This is my code in hot_products view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to,
success: function(data){
alert("success");
}
}
});
});
});
and my hot_products controller:
public function hot_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//code to get data and process it here
}
}
I dont know how to get 2 values which are start_time and end_time.
Please help me. Thanks in advance.
PS: im using cakephp 2.3
$this->request->data gives you the post data in your controller.
public function hottest_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
// get values here
echo $this->request->data['start_time'];
echo $this->request->data['end_time'];
}
}
Update
you've an error in your ajax,
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
If you method is POST:
if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->data['start_time'];
$this->autoRender = false;
ANd if method is GET:
if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->query('start_time');
$this->autoRender = false;

Resources