Returning values in Magento - magento

Following is the function in controller which returns the values of a product
public function productsAction()
{
$sku=$this->getRequest()->getparam('subvalue');
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$upsell_product_collection = $_product->getUpSellProductCollection();
$upsel=$upsell_product_collection->addAttributeToSelect('product_type')
->addAttributeToFilter('product_type', 133);
$products1 = $_product->getData();
return $products1;
}
Below is the ajax request for fetching the values at the frontend
$.ajax
({
type: "POST",
url: "<?php echo $this->getUrl('finder/index/products');?>",
data:"subvalue="+subval,
success: function(response)
{
alert(response);
$("#responseproducts").html(response);
};
});
I m not able to fetch the values in the front end ..Please tell me ways to fetch the values at the front end

Decode as JSON in php:
return json_encode($products1);
and decode it in javascript:
JSON.parse(response);
This should work. You can test it afterwards with:
console.log(response);

if your ajax request is sent successfully then add this code in you controller action.
$response['prodcutdata'] = $products1;
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
After that in ajax request success access it like below:
alert(response.prodcutdata);

Related

How to make layout false in Laravel If request is ajax

I have trying to load a page using simple get request
<script>
$(document).ready(function(){
$("li").click(function(e){
e.preventDefault();
var href = $("a",this).attr('href');
$.ajax({
async: true,
type: "GET",
url: href,
success: function (response) {
$('#main-content').html(response);
}
})
});
});
</script>
In response I am getting content with full layout. But Here I am trying to get only content without layout. In controller I have written code like below
public function index()
{
if ($request->ajax())
{
$this->layout = null; //but same result
}
$tags = Tag::orderBy('id', 'desc')->paginate(10);
return view('admin.tags.index')->with('tags',$tags);
}
But I am getting same result with layout, how can I make layout false ? Or can change layout in controller ?
you can use the renderSections
return view('admin.tags.index')->renderSections()['content'];
https://laravel-tricks.com/tricks/render-view-without-layout
Well, you are still returning a view. Why not do:
return response()->json(["data"=>"some data"]);
after your Ajax check? This will return a JSON response to your frontend.

How to display the corresponding table value of the response in AJAX

I have an ajax response that is equal to 1. And,in my success function, I want to display not the 1 to my view but the corresponding column_name which is 'brands_name' in the brands table which is 'Apple' in this case. I want to display this after a successful post request. Any ideas?
You need to send your response from your controller (json)
// controller
$data['ajax_response'] = 1;
$data['brands_name'] = $brands_name;
return json_encode($data);
You need to catch the success function to get the variable you want from php
// javascript
$.ajax({
url:link,
dataType:"json",
data:data,
type:"post",
success: function(data)
{
if(data.ajax_response == 1)
{
console.log(data.brands_name);
}
},
error: function()
{
}
});

pass an array to action using ajax YII

Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.
The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.

Ajax post request from Backbone to Laravel

I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.

Ajax Response from CakePHP Controller returning null

I'm tryin to validate an input field with an ajax call to a cakephp controller
My Ajax is:
$("#UserAlphaCode").change(function () {
$.ajax({
type: "post",
url: '<?php echo $this->webroot ?>' + "/alpha_users/checkCode",
data: ({code : $(this).val()}),
dataType: "json",
success: function(data){
alert (data);
},
error: function(data){
alert("epic fail");
}
});
});
My controller code
function checkCode() {
Configure::write('debug', 0);
$this->autoRender = false;
$codePassed = $this->params['form']['code'];
$isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
if ($isCodeValid == 0){
$codeResponse = false;
} else {
$codeResponse = true;
}
echo json_encode ($codeResponse);
}
I'm pretty sure I'm using $this->params wrong here to access the data sent from the ajax request. What should I be doing instead?
Try something like:
$codePassed = $_POST['code']
you might also try putting:
$this->log($codePassed,LOG_DEBUG);
somewhere in there and examine the output in tmp/logs/debug.log
Using firebug will help debug the transport.
Don't know why it would be returning null, but I normally use $this->data to fetch form data.
And did you try debug($this->params)? If you don't have a non-AJAX form to test the request from, use Firebug or Wireshark to see what is being return by the server for the debug() call—since it will break jQuery's AJAX handler by not being in JSON.

Resources