laravel 5.2 cannot sent large string via ajax and get method - php

i try to send a parameter with url to server with ajax in laravel 5.2 but when the length of url become more than 5000 char i face the error that Http not found in route
here is my ajax code :
$.ajax({
url: '/uploadQuestionMod5/',
type: 'GET',
data: {_token: CSRF_TOKEN , jcategory2:jcategory2 , jquestionText:jquestionText , jkind:jkind},
dataType: 'JSON',
success: function (data) {
}
});
and my controller is :
$jcategory2 = $request['jcategory2'];
$jquestionText = $request['jquestionText'];
$jkind = $request['jkind'];
$category2 = json_decode($jcategory2);
$questionText = json_decode($jquestionText);
$kind = json_decode($jkind);
$now = date("Y-m-d H:i:s");
$insertquestion = DB::table('questionsInfo')->insert(
['userId' => $userId ,'categoryId' => $category2 ,'questionKind' => $kind ,'questionText' => $questionText , 'questionFileUrl' => null ,'date' => $now]
);
i try to find the limit of url size in get method please help me thank you :)

Quick and Easy Solution try would be using AJAX POST not GET method.
Make your AJAX post and change your route (/uploadQuestionMod5/) in route file (/App/Http/routes.php) as
Route::match(['get', 'post'],'/uploadQuestionMod5', [
'uses'=>'YourController#method'
]);
Note: this route will accept both get and post ajax request.
If you only do post ajax then your route looks like:
Route::post('/uploadQuestionMod5', 'YourController#method');
This route will accept post request comming from ajax call or any toher source (Client)
Update: Token Mismatch Error means following
1. You have missed to submit CSRF tokens fields via AJAX post.
2. Tokens might have changed but you did not have refreshed your page, just making ajax request again and again.
It seems you are submitting your CSRF_TOKEN correctly, so refresh the page and try again to make ajax call.

Related

Laravel Route jQuery

I'm using Ajax to get and display content in a Laravel view. I'd like to know how I can access the second parameter in the URL. It's currently giving me back a random string:
for(var i=0;i<array.length;i++){
html+="<a href={{ route('showAnnouncement',"array[i].id_announcement") }}>";
}
When I alert array{i].id_announcement I get its value, but it doesn't pass in the URL.
Thank you!
You can't access a JS value inside a php code.
{{route('showAnnouncement',"array[i].id_announcement") }}
This not possible, If you are making ajax request you try something like this below.
var an_id = array[i].id_announcement;
$.ajax({
url: '{{route('showAnnouncement')}}',
data: {'an_id':an_id },
type: 'POST',
success: function (result)
{
}
});
Route
Route::post('showAnnouncement/{an_id?}', ['as' => 'showAnnouncement', 'uses' => 'YourController#showAnnouncement']);
Guys finally I found a solution and it worked like a charm
for(var i=0;i<array.length;i++){
var url = '{{ route("showAnnouncement", ":id") }}';
url = url.replace(':id', array[i].id_announcement);
html+="<a href='"+url+"'>";

CakePHP 3 : Cannot get JSON data from controller

I'm trying to return a query made in a controller to the view file so I can use that data in my form. But I am unable to successfully return the data without errors. I know the function is working because it returns the right data but has an error.
Here is my CustomersController fill function which is running the sql query.
public function fill(){
$layout = 'ajax';
$this->autoRender = false;
if ($this->request->is('post')) {
$id = $this->request->data['id'];
$query = $this->Customers->find()
->where([
'id' => $id
])->first();
echo json_encode($query);
}
}
and here is my blah.ctp which is the view file.
<?php use Cake\Routing\Router; ?>
<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?php
echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
?>
<?= $this->Form->end() ?>
<script>
document.getElementById('customers').addEventListener('change',function(){
var id = this.value;
var csrfToken = $('[name=_csrfToken]').val();
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
data: {'id' : id},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
alert(data);
}
});
});
</script>
Currently this is what happens when I select a customer in my drop down box which triggers the script in the view.
As you can see it returns the array of data I need but also has the error cannot emit headers. I have tried solving this error following other questions on stack overflow but can't solve it.
I've tried using $this->set instead of echo json_encode but it always returns nothing. I'm not sure what other way to do this.
First of all, If you're selecting a single record by a unique ID, you can call
->get($id) on the table object directly, instead of building a query chain with ->find().
CakePHP 3.x should automatically handle converting your view to JSON by using the RequestHandlerComponent. Typically, you must enable it if your scaffolding or installation didn't.
1) Enable request handler component. (If not already enabled) https://book.cakephp.org/3.0/en/controllers/components/request-handling.html
2) Remove the echo json_encode($query) line; you should not echo anything as this will break the request/response cycle. This is the cause of your error.
Instead, you should serialize your data to the view. Assuming you have the fetched data in $data: $this->set(compact('data')). Then, make sure you add $this->set('_serialize', ['data']) (again, assuming the data is stored in variable name 'data').
3) Reference this doc for information on how you can request the json. You can use a file extension (.json, .xml).
Also, make sure you add the 'Accept: application/json' header to your request.(https://book.cakephp.org/3.0/en/development/routing.html#Cake\Routing\Router::extensions).
I apologize for the fuzzy response. There are many ways to achieve this with CakePHP3. Please see this doc page for more information: https://book.cakephp.org/3.0/en/views/json-and-xml-views.html

Laravel send data such as 1-2-3 by ajax and get Missing argument error

i try to use below ajax to send data such as 1-2-3-4-5 to controller action but i get error:
Ajax:
$.ajax({
type: "GET",
url: " {{ url('changeMenuItemOrders') }}",
data: {orders: "1-2-3"},
success: function (data) {
}
});
Route:
Route::get('changeMenuItemOrders','SystemController#changeMenuItemOrders');
changeMenuItemOrders action:
public function changeMenuItemOrders($orders)
{
dd($orders);
}
Firebug:
http://localhost/sample/public/changeMenuItemOrders?orders=1-2-3 500 Internal Server Error
Laravel error:
ErrorException in SystemController.php line 114: Missing argument 1 for App\Http\Controllers\SystemController::changeMenuItemOrders()
try
public function changeMenuItemOrders()
{
$orders= Input::get('orders');
dd($orders);
}
in changeMenuItemOrders action:
The issue you're facing is query string parameters vs routing parameters. Right now, you have:
public function changeMenuItemOrders($orders)
looking for the route parameter $orders. In order to make this work, you would require the route:
Route::get('changeMenuItemOrders/{orders}','SystemController#changeMenuItemOrders');
and you would access this function by navigating to (GET):
http://localhost/sample/public/changeMenuItemOrders/1-2-3
Since you are creating a query string via your ajax request, you shouldn't have $orders in your function, but you should instead be accessing the orders via the GET array, using
$orders = Input::get('orders');
Hope that helps clear things up. Also, as a side note, if you're passing multiple orders (ie 1, 2 and 3), consider posting an orders[] (orders[0] 1, orders[1] 2, orders[2] 3) instead of a string ("1-2-3") that you would have to split on the backend.

Adding Item to Database in Laravel with AJAX and then showing Item

After hours of Googling, I can't seem to find an answer to this seemingly simple problem. I can't add data to a database and show that data without refreshing the page. My goal is to be able to create an object from a form to upload to a database, and then show all the items in database (without the page refreshing). I have tried to get AJAX working many times, but I can't seem to do that. The application works by adding stars to students, so basically I would want to be able to update a students star count without reloading the page. But right now I can't even console.log the submitted form data. My Controller code is like so:
public function addStar(){
$id = Input::get('id');
$user_id = Input::get('user_id');
if(Auth::user()->id == $user_id){
Student::addStar($id);
}
return Redirect::back();
}
And my form:
{{Form::open(array('action'=>'HomeController#addStar','id'=>'addStar','method'=>'post'))}}
{{ Form::hidden('id', $student->id, array('id'=>'id_value')) }}
{{ Form::hidden('user_id', $student->user_id, array('id'=>'user_id_value'))}}
{{ Form::submit('+')}}
{{ Form::close() }}
And my extremely poor attempts at AJAX:
$('#addStar').on('submit',function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: '/addstar',
data: $('#addStar').serialize(),
success: function(data) {
console.log(data);
},
});
return false;
});
The code works fine if I settle for allowing page reloads, but I don't want that. So essentially, my question is, how do I add data to a database and show it without the page reloading? Thanks so much!
Your controller is doing a redirect after the logic, ajax won't be able to do anything with the response. A one take would be, after adding a start returning the new star rating.
public function addStar(){
$id = Input::get('id');
$user_id = Input::get('user_id');
if(Auth::user()->id == $user_id){
Student::addStar($id);
}
$star_count = //get new star count;
return Response::json(['star_count' => $star_count]);
}
Since controller now returns a json response, the success callback on $.ajax can grab it and do something (update the star count).
#codeforfood,
If you want to grab the response and show it immediately in the page without a reload then you may go with returning a JSON reponse and then handle that response at the client side Javascript for Success or Failure conditions.
Can try something like this if you want:
In the controller addStar() method response:
$data = ['star_count' => 'COUNT OF STARS'];
return json_encode($data);
In the View for that specific Star Div:
<script>
$('#stardiv).on('submit', function (e) {
$.ajax({
type: 'POST',
url: "{{URL::to('xxxxx')}}",
data: $(this).serialize(),
dataType: "JSON",
success: function (data) {
Handle the success condition here, you can access the response data through data['star_count']
},
error: function (data) {
Handle the error condition here, may be show an alert of failure
}
});
return false;
});
</script>
After all this is just one approach, you may try different one which ever suits your need.

cakephp send and get json

i have tag in cakephp like this:
var url_save = "<?php echo $this->Html->url(array('controller' => 'users','action' => 'save_template')) ;?>";
$.ajax({
url : url_save,
type : "POST",
data : JSON.stringify(templates),
dataType : 'json'
});
how the controller can take the data value?
You can use $this->request->data on the Controller the usual way.
you can get json data using $this->data in controller, you can check if the request is ajax if you want using $this->RequestHandler->isAjax() but you must also add RequestHandler in component variable.

Categories