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

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

Related

Laravel 5.2 post route returns plain html text

whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')

Returning values in 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);

ajax success print multiple data

i am new in this ajax . i got a problem that is in my ajax coding i get a multiple data in loop so how can print that multiple data in ajax success
here is my code :
$.ajax({
url: 'ajaxdate',
data: {ending:ending},
type: 'POST',
success: function(data) {
$('#info1').text(data);
console.log(data.length);
alert(data);
/*for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}*/
}
});
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
echo $data['full_name'] = $detail['list']['full_name']."\n";
}
}
How i print that multiple data in ajax success
What you can do with is expect JSON as response.
I see the problem in your function if you are printing the full_name in loop and expecting HTML response, all it will be just a string.
What you can do is something like this
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
$data[]['full_name'] = $detail['list']['full_name'];
}
die(json_encode($data));
}
This will return a json array with collection of object of full_name eg [{full_name: 'ABC'},{full_name: 'cde'}]
Then add dataType : 'json' in you ajax.
Now you can iterate thorough the response you get in ajax success.
For an example you have this <ul id="showResultHere"></ul> tag, where you would like to show the result, then TRY this in your "success" AJAX :
success: function (data){
$.each(data, function(index) {
//alert(data[index]);
$("#showResultHere").append("<li>" + data[index] + "</li>");
});
}
Or, another way to show your "full_name" from your guestbook array, here is another option too :
success: function (data){
data.forEach(function(data) {
$("#showResultHere").append("<li>" + data + "</li>");
});
}

Putting a JSON response into a hidden field and retrieving it into a function

I'm retrieving the number of rows contained by a table in my database with the following function using JSON.
function rowCount()
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
In the success handler, the response is arriving as expected. There is no problem on the server side.
The response is just mapped with the long type of Java which represents the number of rows in a database table.
I'm putting this response in a hidden field whose id is rows using $("#rows").val(response); in the success handler.
The above function is invoked when the form is submitted using the following jQuery function.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the above function that makes a JSON request.
var rows=$("#rows").val();
alert("rows = "+rows);
return false;
});
});
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time. It alerts the actual value only when I press the submit button once again (without a page refresh).
Also tried to replace the preceding function with the following.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the first function that makes a JSON request.
var form = $(this),
url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
return false;
});
});
But it didn't work either. Why does this happen? What is the way of retrieving the correct value of that hidden field into the preceding jQuery function?
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time.
Ajax calls are asynchonrous. When you call rowCount, you start the call, but then rowCount returns and your code continues. The call doesn't complete until later (which is why ajax accepts a callback).
If you trigger the next step in what you're doing from the callback, you'll have the value. You typically do this by having rowCount accept a callback of its own, like this:
function rowCount(callback) // <==== Accept the callback
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
callback(); // <==== Call the callback
},
error: function(e)
{
alert('Error: ' + e);
callback(); // <==== Probably want to give it a value telling it things failed
}
});
}
Then using it:
$(function() {
$('#dataForm').submit(function() {
var form = $(this); // <== Grab this outside the callback
rowCount(function() {
var url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
});
return false;
});
});
If you want to decide whether to allow the form to be submitted on the basis of the callback, you'll have to always cancel the submission, and then trigger submitting it programmatically from the callback if you want to allow it.

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