Ajax post request from Backbone to Laravel - ajax

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.

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.

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')

how to access a controller function from outside of controller in codeigniter

I have a folder (suppose it's name is "test") outside of controller folder which contains a file name "error404.php" and my controller name is "test_controller.php" which has a method name "tst()". error404.php is a view page in where i want to access data from test_controller.php via ajax.
<script>
$(document).ready(function(e) {
$('#search_items_err').keyup(function(e) {
if($('#search_items_err').val().trim()==''){$('#sugglist').html(''); return false;}
search_key=$(this).val().trim();
var data = {
search_key: search_key
};
alert(search_key);
$.ajax({
data: data,
type: "post",
url: "test_controller/tst",
success: function(response) {
var options = JSON.parse(response);
alert(options);
}
});
});
});
</script>
My tst function is:
public function tst(){
$search_key = $_POST['search_key'];
echo "success";
}
But my ajax doesn't work. I suspect that it may contain some problems in the (url: "test_controller/tst",). So how can i solve it? What is the syntax of accessing test_controller's method from error404.php page?How do i access base url?
Take a look at this ajax concept
in your ajax function :
url : baseURL+'test_controller/search', //Make sure this url is working properly
data : {'search_key' : search_key},
in you test_controller/search
public function search()
{
//generate data and load your view
$data = "Generated Data array";
$this->load->view('test_folder/search', $data); //Load your view from application/view/ not from outside the controller
}

Backbone set model inside ajax request

Hi all I have an app in Backbone where inside a function I want to convert price from GBP to EUR for example using a php file called with ajax.
In the success function I want to assign the converter data to my object.
But seems that not setting this because into the template uin underscore there is always the old value.
This is my function inside my model:
toJSON: function() {
var json = _.clone(this.attributes);
json.rooms = this.rooms.toJSON();
_.each(json.rooms, function(room){
var converter ="<?php echo(site_url('/backend/hotel/ajax_currency')); ?>";
$.ajax({
url: converter,
type: "POST",
data: {
from_currency : room.currency,
amount : room.price_adult
},
dataType: "json",
success: function(data) {
console.log(data);
room.price_adult = data;
}
});
});
return json;
},
I have also tried:
room.model.set('price_adult',data);
but return me error that don't find model.
How can I solve?
This is not a thing you want to put in toJSON function, I can think of several reason why it should work for you. The most important one is that toJSON function is synchronous and the AJAX response is async. so your render function is happening before you get the response from your ajax.
I would suggest having a Room model that will be responsible for the concurrency, and it's view will render it when ajax has returned and the price_adult is ready.
var Room = Backbone.Model.extend({
initialize:function(){
this.convertConcurrency();
},
convertConcurrency:function(){
var model = this;
$.ajax(.....,
success:function(data){
model.set("price_adult", data);
}
);
},
});
var RoomView = Backbone.View.extend({
initialize: function(){
this.listenTo(this.model, "change:price_adult", this.render);
if (this.model.has("price_adult")) this.render();
},
.....
});
var Rooms = Backbone.Collection.extend({...})
var RoomsView = // Rooms collection view
This way the view will be rendered only when there is a price_adult ready.
Maybe you should create a model on the client that gather the concurrency information from the server and compute the concurrency conversation by itself, so you will only have one ajax and the model will compute it for you instead of the server.

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

Resources