Javascript file not being able to make an Ajax call to laravel - ajax

Hi I was hoping someone can help me. my root folder for my app is cloudapp.azure.com/index.php. cloudapp.azure.com/ is my public folder. So all my views are being rendered like so cloudapp.azure.com/index.php/welcome1 from my routes and controllers. It all workrs fine.
Route::post('/welcome1a', [
'uses'=>'UserController#postRegister',
'as' => 'register',
]);
Route::post('/welcome1', [
'uses'=>'UserController#postRegister1',
'as' => 'register1',
]);
public function postRegister1(Request $request){
$data1 = $request->all();
$data = JSON.parse($data1);
return response()->json(['result' => 'data1']);
}
The issue I'm facing is I will be working on phone gap so my views need to be in html. My HTML files are stored in my public folder (ie cloudapp.azure.com/) so a view will be like cloudapp.azure.com/register.html.
I am trying to send data from cloudapp.azure.com/js/script1.js in my cloudapp.azure.com/register.html view like so to the url that is recognised by my laravel application;
$.ajax({
url: url,
type: 'POST',
data: details,
dataType: "json",
success: function(result) {
console.log('result');
}
});
but it seems that the js file and the url are not communicating to each other. Is my file structure wrong? when I use blade view to do an Ajax call its fine but with my html files calling the url via ajax, it doesnt work. Even when I try to get my old laravel views via;
$.get("cloudapp.azure.com/index.php/welcome1"); it doesnt work.
I have triend making the ajax call to the following urls;
cloudapp.azure.com/index.php/welcome1
index.php/welcome1
and /welcome1.
There are no errors, but just not communication to each other.
If anyone can help you will be a LIFE SAVER

public function postRegister1(Request $request){
$data1 = $request->all();
$data = json_decode($data1);
return response()->json(['result' => 'data1']);
}
JSON.parse is javaScript not PHP.
json_decode() is what you use in PHP.
http://php.net/manual/en/function.json-decode.php
But you shouldn't have to json_decode it either, $request->all() returns an array of the posted values.
I would say, remove the whole json stuff and then see if your ajax call is getting back the return value.
public function postRegister1(Request $request){
return response()->json(['result' => 'testing...']);
}
Then go from there...

You are calling a JS function JSON.parse in PHP.
So instead do
public function postRegister1(Request $request){
return response()->json([ 'result' => $request->all() ]);
}
Or if you simply return just an array, laravel will automatically cast it into JSON for you
public function postRegister1(Request $request){
return [ 'result' => $request->all() ];
}

You should try removing the <base> tag on your <head>

Related

How do I pass a variable from blade file to controller in laravel?

I have ProjectController that fetches data from the database and passes it to a blade file. One of the data items is the project_id. I want to pass the project _id from the blade file to another controller BidController.
ProjectController.php
public function show($id)
{
$project = Project::find($id);
return view('project.show',['project'=>$project]);
}
show.blade.php
div class="card-header">PROJECT <p>{!! $project->id !!}</p></div>
BidController.php
public function store(Request $request)
{
$bid = new Bid;
$bid->project_id = $project_id;
dd($project_id);
}
The dd(); does not output the project_id. I need help in passing the project_id from the blade file to the BidController method.
You can't directly set a model's id like you're doing in the line $bid->id = $project_id;. Are you trying to set up a relationship? That should be more like $bid->project_id = $request->project_id;.
Blade templates can't really pass things back to controllers, once they're in the browser your app is sort-of finished running. You need to create an HTML link/request on the page (like a form post request) that'll request the next thing from your app when the user clicks it.
If you want to create a button that creates a new bid for an existing project, you could do something like set up a form with a hidden field of 'project_id' that posts back to '/bids' which goes to the route 'bids.store'. You'll find 'project_id' under $request->project-id'.
You can send an AJAX request from Javascript:
View
<script type="text/javascript">
var project_id= {!! json_encode($project->id) !!}
$.ajax({
type: 'POST',
url: url, //Your bidController route
data: {project_id: project_id},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
},
success: function()
{
console.log('successful')
}
});
</script>
This will sent the data to the controller asynchronously so the user experience doesn't get affected.
One extra point: In your Bid controller, as project_id is coming from the request, you'll have to use:
$bid->id = $request->project_id;
I hope it helps!
PS: I'm using JQuery for this, so you'll have to include it if you don't already have.
I think this will solve your problem :
ProjectController.php
public function show($id)
{
$project = Project::findOrFail($id);
return view('project.show',compact('project');
}
web.php
Route::post('/bids/store/{id}' , 'BidController#store')->name('bids.store');
show.blade.php
div class="card-header">PROJECT <p>{{$project->id}}</p></div>
<form action="{{route('bids.store', $project->id)}}" method="post">
BidController.php
public function store(Request $request, $id)
{
$bid = new Bid;
$bid->id = $id;
$bid->save();
dd($id);
}

Form submit going to the wrong route

I am saving data from a simple form in my Laravel project.
While submitting, it should go to the route that is predefined for store() method. I use such code:
{!! Form::open(['action' => 'PostsController#store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
It goes to the route that is for index() method. Any help?
In store() method, I have such code:
$posts = new Post;
$posts->title = $request->input('title');
$posts->body = $request->input('body');
$posts->save();
return redirect('/');
My web.php contains:
Route::resource('/','PostsController');
Your code is correct bro.. The only reason you're going to index is because of the
return redirect('/'); in the store function... Check whether youdata is saved in the database or not...
Have you tested to see if this actually saves the data still? With Route resources, the route will be the same for both store and index methods, just a different HTTP method.
Maybe your code is working well & data saved in the database. You return redirect('/') it to your index() method, so you don't understand the difference. Check your database.

How to change response in Laravel?

I have RESTful service that is available by endpoints.
For example, I request api/main and get JSON data from server.
For response I use:
return response()->json(["categories" => $categories]);
How to control format of response passing parameter in URL?
As sample I need this: api/main?format=json|html that it will work for each response in controllers.
One option would be to use Middleware for this. The below example assumes that you'll always be returning view('...', [/* some data */]) i.e. a view with data.
When the "format" should be json, the below will return the data array passed to the view instead of the compiled view itself. You would then just apply this middleware to the routes that can have json and html returned.
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->input('format') === 'json') {
$response->setContent(
$response->getOriginalContent()->getData()
);
}
return $response;
}
You can use for this Response macros. For example in AppServiceProvider inside boot method you can add:
\Response::macro('custom', function($view, $data) {
if (\Request::input('format') == 'json') {
return response()->json($data);
}
return view($view, $data);
});
and in your controller you can use now:
$data = [
'key' => 'value',
];
return response()->custom('your.view', $data);
If you run now for example GET /categories you will get normal HTML page, but if you run GET /categories?format=json you will get Json response. However depending on your needs you might need to customize it much more to handle for example also redirects.
With your format query parameter example the controller code would look something like this:
public function main(Request $request)
{
$data = [
'categories' => /* ... */
];
if ($request->input('format') === 'json') {
return response()->json(data);
}
return view('main', $data);
}
Alternatively you could simply check if the incoming request is an AJAX call via $request->input('format') === 'json' with $request->ajax()

How to send PUT request with a file and an array of data in Laravel

I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.
Please see the code below :
web.php ( route )
Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController#update');
});
My angularjs product service :
function update(productId, data, onSuccess, onError){
var formData = new FormData();
formData.append('imageFile', data.imageFile);
formData.append('image', data.image);
formData.append('name', data.name);
formData.append('category_id', data.category_id);
formData.append('price', data.price);
formData.append('discount', data.discount);
Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined, {'Content-Type': undefined}).then(function(response) {
onSuccess(response);
}, function(response){
onError(response);
}
);
}
My ProductController update function
public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
This is what I see in Chrome inspectmen
Please share your experiences on this problem. Thanks.
what you need is Only normal POST request with new field named _method=put then your code will work normally:
You can't do that, according to this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing
Try this method:
public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
Also, make sure you're using Route::put or Route::resource for your route.

issues with backbone.js DELETE request and codeigniter restserver (phils)

I'm sure this is something I'm doing wrong, but I can't seem to figure it out. I'm using backbone.js to talk to my rest server (Philip Sturgeon's codeigniter restserver). I am running a normal model.destroy() on one of my backbone collections model.
//a basic example
tagCollection.at(5).destroy();
This creates a proper call to a url like:
DELETE http://mydomain.com/index.php/tags/tag/id/12
When I get inside my "tag_delete" php function, and do:
$this->delete('id');
This always returns nothing. I assume this has something to do with the way backbone.js sends it's requests, but nothing is jumping out at me. Details below.
Backbone is issuing a "DELETE" request.
Relevant code from my REST_Controller method:
function tag_delete () {
//delete the tag
$id = $this->delete('id'); //always empty
$result = $this->tag_model->delete($id);
if (! $result) {
$this->response(array('status' => 'failed'), 400);
}
$this->response(array('status' => 'success'), 200);
}
Any ideas? Any backbone.js experts run into this when using codeigniter and Philip Sturgeon's restserver?
This should be a cheap quick way to fix your delete request...
function tag_delete () {
$id = $this->uri->segment(4);
$result = $this->tag_model->delete($id);
if (! $result) {
$this->response(array('status' => 'failed'), 400);
}
$this->response(array('status' => 'success'), 200);
}
However, this is how I am structuring my requests using a combo of backbone and REST_Controller...
DELETE http://example.com/index.php/tags/12
(get rid of the /tag/id/ segment of the url... it's implied that you are deleting a 'tag' row from the 'tags' collection by id, appending /tag/id is unnecessary)
function tag_delete ($id) {
$result = $this->tag_model->delete($id);
if (! $result) {
$this->response(array('status' => 'failed'), 400);
}
$this->response(array('status' => 'success'), 200);
}
for the collection:
Backbone.Collection.extend({
url : '/tags'
});
tagCollection.at(5).destroy();
Then add something like this to your routes:
$route['tags/(:num)'] = 'tags/tag/$1';
which will set up the structure necessary for the restserver controller... it is just much more manageable that way if you are doing a lot of Backbone work.
As per tgriesser's suggestion, the best way to do this is to use the url property on the collection. I have used the following before and it works like charm (the following controller implemented using silex framework + paris library for data access):
// DELETE /{resource}/{id} Destroy
$app->delete('/api/todos/{id}', function ($id) use ($app) {
$todo = $app['paris']->getModel('Todo')->find_one($id);
$todo->delete();
return new Response('Todo deleted', 200);
});
In your backbone collection, add the following:
window.TodoList = Backbone.Collection.extend({
model: Todo,
url: "api/todos",
...
});
Recently, I have written a tutorial on how to do GET/POST/PUT/DELETE with Backbone.js and PHP http://cambridgesoftware.co.uk/blog/item/59-backbonejs-%20-php-with-silex-microframework-%20-mysql, might be helpful.

Resources