Problema sending json file from javascript to laravel controller - javascript

im having problems trying to send a JSON file from javascript to Laravel controller, when i press my button from the view i didnt get any response.
This is my code, i appreciate any help or suggestion, thnks.
This is the the JS code:
var horarios= { Lunes: arrLunes, Martes: arrMartes, Miercoles: arrMiercoles, Jueves:arrJueves, Viernes:arrViernes};
var schedule = JSON.stringify(horarios);
//console.log(schedule);
var varurl= 'http://localhost/registerEntrance';
$.ajax({
type: "POST",
url: varurl,
data: {json:schedule},
dataType:'json',
success: function(res) {
var message = res.mesg;
if (message) {
$('.flash').html(message).fadeIn(300).delay(250).fadeOut(300);
};
}
});
When i press my button, doesnt happend anything. The next id the route and the controller code, the JSON file not arrive there yet.
Route::post('registerEntrance', array('as' => 'registerEntrance','uses' => 'CursoController#regisEnt'));
public function regisEnt(){
if(Request::ajax()) {
$data = Input::all();
return $data;
}
}
Thnks for any help.

What are you using to debug your requests? Have you checked your storage/logs/framework/laravel.log (if your log is HUGE you can always delete it and re-run your request)
Working with AJAX can get tricky when it comes to debugging your requests.
My recommendation would be
Open up your browser Inspector, and monitor Network Requests
Analyze the request you're sending.
Set debug to true under config/app.php to actually see a debug
Hope this helps!

I get resolv my problem, i post it if someone is getting a similar inconvenience.
In my view i wasnt create a form.
{!! Form::open(['route' => ['route'], 'method' => 'POST', 'id' =>'form-name']) !!}
{!! Form::close() !!}
This part create a implicit token that is necesary in laravel for use ajax method.
My code JS was modified for getting and send the csrf token.
var form = $('#form-name');
var myurl = form.attr('action');
crsfToken = document.getElementsByName("_token")[0].value;
$.ajax({
url: myurl,
type: 'POST',
data: {data:data},
datatype: 'JSON',
headers: {
"X-CSRF-TOKEN": crsfToken
},
success: function(text){
bootbox.dialog({
closeButton: false,
message: "Ok!",
title: "Perfect!!",
},
error: function(data){
console.log("Error");
}
});
With this change i get arrive to my controller.
Anyway Thnks.

Related

Laravel Using AJAX to pass Javascript variable to PHP and retrieve those

How can I use Ajax to pass a Javascript variable to Php and retrieving those?
I am using a Jquery Ui Slider and on each slide I want to pass the javascript slider value to php so to say.
I have no ( not much ) experience in Ajax and really appreciate help.
This is how my slider looks:
$("#sliderNumCh").slider({
range: "min",
min: 0,
max: 20,
step: 1,
value: numbersOfChapters,
change : function(e, slider){
$('#sliderAppendNumCh').empty();
var i = 0;
var sliderValue = slider.value;
var getSliderVal = document.getElementById('sliderValue').value = sliderValue;
$.ajax({
type: 'POST',
url: '',
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
value: getSliderVal
},
success: function (option) {
console.log(getSliderVal);
}
});
...
}
})
My route example:
Edit my route looks like this now:
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController#editProduct']);
Edits what I have tried:
url: '{{ route("editProductWeb") }}',
and got this error:
POST http://localhost/myApp/public/product/edit/%7BproductID%7D 500 (Internal Server Error)
and tried this:
url: 'edit',
and got this error:
POST http://localhost/myApp/public/product/edit 500 (Internal Server Error)
Edit my edit controller method:
public function editProduct($productRomID = 0)
{
$product = ProductRom::find($productID);
$sheets = Chapters::where('product_id', '=', $productID)->get();
$productId = $product->id;
$sheetCount = count($sheets);
return view('product.edit', [
'productId' => $productId,
'product' => $product,
'sheets' => $sheets,
'sheetCount' => $sheetCount,
'type' => 'edit',
'route' => 'updateProductRom'
]);
}
Edit using haakym suggestion so far:
$.ajax({
type: 'post',
url: "{{ Route('editProduct', $product->id) }}",
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
value: getSliderVal,
productId : getPrId
},
success: function (option) {
console.log(getSliderVal);
}
});
does print me the id + the current slider value in my debug, so that works so far. Now I need to get that value and use it in my view(php) any suggestion how to proceed?
using this in my controller method:
$sliderValue = $request->input('value');
returns me
null
Edit I also tried this:
$sliderValue = Input::get('value');
which also returned me
null
Edit I added a Log:
Log::info(Input::all());
This shows the correct slider value and product id on slide.
But my Input::get('value') still returns me null
Edit I think I should add this information:
I changed my routes to this now:
Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController#editProduct']);
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController#editProductPost']);
The get shows the data from the database for a specific product and shows them in my view, I added the post one to post the slidervalue data to the editProductPost method and returns afterwards the value(sliderValue) in the edit view, is this correct?(Btw still does not work)
EDIT
If I put this in my controller method:
if ($request->isMethod('post')){
return response()->json(['response' => 'This is post method']);
}
return response()->json(['response' => 'This is get method']);
I keep getting the following error (if I slide):
POST http://localhost/myApp/public/product/edit/54 500 (Internal
Server Error)
I have this in my head:
<meta name="csrf-token" content="{{ csrf_token() }}">
and put this before my ajax post:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
EDIT:
Doing this returns the correct current slider value in the logs:
Log::info($request->get('value'));
I tried this:
return view('productRom.edit', [
'value' => $value,
]);
But I get an error in the console:
Failed to load resource: the server responded with a status of 500
(Internal Server Error) http://localhost/myApp/public/product/edit/73
As #julqas stated you need to include the URL in your $.ajax() method.
As you have a named route editProduct, you can output the link using blade:
$.ajax({
type: 'POST',
url: '{{ route("editProduct" }}',
...
Edit 1:
Your route is get and your ajax method is post, I guess this is the issue. You need to make them the same.
If you change the route to post you will need to add the CSRF token to the ajax request when it is sent. There is some guidance on the docs how to do this here:
https://laravel.com/docs/5.2/routing#csrf-x-csrf-token
The docs recommend adding this in your HTML head:
<meta name="csrf-token" content="{{ csrf_token() }}">
then use the following code before sending the request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
alternatively you can add it to the request in the ajax call.
Edit 2
A side point - I was just guessing what the error is, it would have been better if I'd asked you if you could debug it yourself in order to see what the error was. Learning to debug ajax requests is very useful and not too difficult.
The best way to do that is by using the developer console in your browser of choice when making the ajax request. If you're using Chrome for example open Developer tools and then click on the Network tab before making your request. After making the request you can inspect the request and its details. Hope that helps!
Edit 3
I would change your editProduct() method to not accept any parameter and instead get the id value for the product from the request
public function editProduct()
{
// value here is referring to the key "value" in the ajax request
$product = ProductRom::find(\Request::get('value');
...
}
Consider changing the value key in your json to something more useful, such as productId
data: {
productId: getSliderVal
}
you haven't entered value for 'url'. Create any route then put it in url:'{any_route_name}' and then check in console weather your value has been posted or not
You have to do some R&D at your level for this .

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

Django + Ajax | File Upload | Server doesn't recognise Ajax Request

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

Laravel 4: manipulating ajax data through controller

I'm new at Laravel and ajax. I'm trying to get the data from a form via ajax and calling a method in the controller via that same ajax. The method in the controller searches the database and then returns a json response that gets handled by ajax(that last part I'm still thinking about, I haven't really done it yet).
Let me show you what I have now:
Routes.php:
Route::get('/', 'HomeController#getIndex');
Route::post('/', 'HomeController#postIndex');
HomeController:
public function getIndex()
{
return View::make('index');
}
public function postIndex()
{
$match = Input::get('search');
$results = Customers::where('name', 'like', '%'.$match.'%')->get();
return Response::json(array('results' => $results));
}
And my index.blade.php View :
<script>
$(document).ready(function() {
$('form#find').submit(function() {
$.ajax({
url : 'CustomerSearch/Public',
type: 'post',
dataType: 'json',
data: $('form#find').serialize(),
});
return false;
});
});
and the form:
{{ Form::open(array('url' => '', 'method' => 'POST', 'id' => 'find')) }}
{{ Form::text('search', '', array('class' => 'search-query', 'placeholder' => 'Search')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
{{ Form::close() }}
So I should be getting the data from the form then sending it to the "postindex" method in the controller so it gets processed and then sent back, right? Except I get the error "Controller method [index] not found." when I don't actually call any index method since they are both named differently.
I'm new at this so sorry if it's not clear.
UPDATE:
Like I said in the commentaries, I found out combining the route into a route::controller got rid of my previous problem but unfortunately I'm still unable to get the ajax to send data to my controller. I get no errors, but the ajax doesn't load anything to the controller. Any idea what might be wrong with my ajax?:
$(document).ready(function() {
$('form#find').submit(function() {
$.ajax({
url : '{{URL::to('/')}}',
type: "POST",
dataType: 'json',
data: { search: $('.search-query').val() },
success: function(info){
console.log(info);
}
});
return false;
});
});
Just use in your controller:
return json_encode(array('key' => 'val'));
For the input of data, I moved to a JQuery plugin that works nicely for me. Follow this link.
This is how a function looks like:
function someName(){
// A plugin is used for this function
$('#form_id').ajaxForm({
url: '/',
type: 'post',
dataType: 'json',
success: function(response){
alert(response.key);
}
});
}
and the corresponding form:
<form id="form_id">
<!-- Put your fields here -->
<input type="submit" onclick="someName()">
</form>
I would suggest you use this method, which may depend on the plugin but is the simplest. Of course, you could use the .submit() statement instead of binding it to the onclick event

cakephp 2.2 retrieve json data in controller

I'm trying to send JSON data from a web page using JQuery, like this:
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
In cake2.2, I have a controller named Ajax that has a method named "login", like this:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input(); // MY QUESTION IS WITH THIS LINE
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
I just want to see if I'm passing in the correct data to the controller. If I use this line:
$data = $this->request->input();
I can see the debug printout:
{username: "wiiNinja", password: "isCool"}
I read in the CakePHP manual 2.x, under "Accessing XML or JSON data", it suggests this call to decode the data:
$data = $this->request->input('json_decode');
When I debug print $data, I get "null". What am I doing wrong? Is my data passed in from the Javascript incorrect? Or am I not calling the decode correctly?
Thanks for any suggestion.
============= My own Edit ========
Found my own mistake through experiments:
When posting through Javascript, instead of this line:
data: '{username: "wiiNinja", password: "isAnub"}',
Change it to:
data: '{"username": "wiiNinja", "password": "isAnub"}',
AND
In the controller code, change this line:
$data = $this->request->input('json_decode');
To:
$data = $this->request->input('json_decode', 'true');
It works.
Dunhamzzz,
When I followed your suggestions, and examine the "$this->request->params" array in my controller code, it contains the following:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
As you can see, the data that I'm looking for is not there. I've already got the the proper routes code. This is consistent with what the documentation for 2.x says here:
http://book.cakephp.org/2.0/en/controllers/request-response.html
So far, the only way that I found to make it work, is as stated above in "My own Edit". But if sending a JSon string to the server is not the right thing to do, I would like to fix this, because eventually, I will have to handle third party code that will send JSon objects.
The reason you are struggling wit the data is because you are sending a string with jQuery, not a proper javascript object (JSON).
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
Now the data will be available as a PHP array in $this->request->params.
Also for sending a JSON response, please see this manual page. Most of your code there can be reduced to just 2 lines...
//routes.php
Router::parseExtensions('json');
//Controller that sends JSON
$this->set('_serialize', array('data'));

Categories

Resources