I see you have the crossDomain: true set in your AJAX. Are you actually posting to another domain? Even though you set that to true, still may not allow by the browser. Using your browser network tools, does the request sent to the server respond with a 200 status, or is it being rejected (500 status)?
Also, you will likely need to set a header on the server to allow cross posting there as well.
Use with caution:
header('Access-Control-Allow-Origin: *');
This need to placed in the top of your controller method before any other output is sent to the browser. This header allows AJAX requests to come from anywhere.
pickupman said:
I see you have the crossDomain: true set in your AJAX. Are you actually posting to another domain? Even though you set that to true, still may not allow by the browser. Using your browser network tools, does the request sent to the server respond with a 200 status, or is it being rejected (500 status)?
Also, you will likely need to set a header on the server to allow cross posting there as well.
Use with caution:
header('Access-Control-Allow-Origin: *');
This need to placed in the top of your controller method before any other output is sent to the browser. This header allows AJAX requests to come from anywhere.
Heyy! well in the console i was getting the status of 500 after the post request, then i googled why it is so, so i learned to do crossDomain=true to avoid the error. So i did that, it worked too. Now when the post request is sent, there is no 500 status error, but the things actually doesn't work as i expect, the Database record creation in the database. Well the status shown is also 200 ok, i can't get why the database record is not getting created. I tried putting this header, doesn't work.
What other thing i noticed is when i run User::create command the record is getting created with ajax and doesn't throw 500 status error, but when i use Event::create it throws 500 status error, why so? Do i need to override something in my Event Model? Am i forgetting something?
POST http://localhost:8000/events
500 (Internal Server Error) jquery.js:26
Y.cors.a.crossDomain.send jquery.js:26
_.extend.ajax jquery.js:25
(anonymous function) main.js:14
_.event.dispatch jquery.js:25
q.handle
Alright i solved the problem, what i did was, first i tried to create the event without ajax, and the time i was creating the event, it showed that 'Event' is some internal laravel command and so they cannot create the record, and hence i deleted all the migrations and Model 'Event.php' and replaced the Model with 'Events.php'.
<?php
class Events extends Eloquent {
protected $fillable = ['eventname','eventdesc','eventvenue'];
protected $table = 'events';
}
and then i created the migration again of the event table, not needed may be, but its good to be on safe side, i redo all the things related to the database.
And then in the controller i replaced Event::create with Events::create, lemme give you the whole code.
class EventsController extends BaseController{
public function showEvents()
{
return View::make('events.newevent');
}
public function postEvents()
{
$token = Input::get('token');
if(Session::token()!= $token)
{
return "The token doesn't match!";
}
else
{
$eventname = Input::get('eventname');
$eventdesc = Input::get('eventdesc');
$eventvenue = Input::get('eventvenue');
$event = Events::create( array(
'eventname' => $eventname,
'eventdesc' => $eventdesc,
'eventvenue' => $eventvenue,
'remember_token'=> $token
));
if($event){
return 'The event has been created successfully.';
}
else{
return 'The event cannot be created.';
}
}
}
}
And then what i noticed was i had put the Route::post('/events') request in the ('before' => 'csrf') array, but i was actually taking care of that in the ajax request by passing the token and comparing it with the session token, so the main thing here is grab that out of the CSRF array, like this.
Route::group(array('before'=>'auth'),function(){
Route::group(array('before'=>'csrf'),function(){
Route::post('/account/change-password',array(
'as'=>'account-change-password-post',
'uses'=>'AccountController@postChangePassword'
));
});
Route::post('/events',array(
'as'=>'events-post',
'uses'=>'EventsController@postEvents'
));
Actually this was the main culprit as i noticed, for the internal server error 500.
And also there is no need for crossDomain : true in ajax handling.
Improved js file is as follows :
jQuery(document).ready(function(){
jQuery("#preloader").hide();
jQuery('.createevent').click(function(e){
e.preventDefault();
var eventname = jQuery("#eventname").val();
var eventdesc = jQuery("#eventdesc").val();
var eventvenue = jQuery("#eventvenue").val();
var token = jQuery("input[name=_token]").val();
var req = jQuery.ajax({
url : "/events",
type: "POST",
data : { eventname : eventname, eventdesc : eventdesc, eventvenue : eventvenue, token : token}
});
$(document).ajaxStart(function(){
$("#preloader").show();
});
req.success(function(data)
{
jQuery(".notify").append(data);
});
req.complete(function()
{
jQuery("#preloader").hide();
});
});
});
Done.
Happy Coding! :)
Hey Parthchokshi,
I am trying to implement your above explained code in my project for testing pourpose, but no luck man.
#view :- test.blade.php
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
jQuery(document).ready(function($){
$('#category').change('select', function()
{
$.ajax({
type: "POST",
url : "test",
datatype:"json",
data : "user_id="+$("#category").val(),
success : function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<h1>hi</h1>
<form id="user_form" method="get">
<?php $user_list= array('' => '--- Select Category ---')
+User::lists('name', 'id') ?>
{{ Form::select('category', $user_list,NULL ,array('id'=>'category')) }}
</form>
<br>
<div id="userInfo"><b>User info will be listed here.</b></div>
</body>
</html>
#route.php
Route::get('test',function()
{
return View::make('test.test');
});
Route::post('test' ,'test@post_index');
#controller:- test.php
<?php
class test extends \BaseController {
public function post_index()
{
$data = Input::all();
if(Request::ajax())
{
$user=User::find($data['user_id']);
echo "<table border='1'>
<tr>
<th>name</th>
<th>email</th>
<th>DOJ</th>
</tr>";
echo "<tr>";
echo "<td>" . $user->name . "</td>";
echo "<td>" . $user->email . "</td>";
echo "<td>" . $user->create_at . "</td>";
echo "</tr>";
echo "</table>";
return 1;
}
}
}
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
I am getting below ajax response from server:- 301 Moved Permanently
AJAX seems to be nightmare for me. :( Please guide me ... thanks in advance.
Hi All, If I am using GET method, my code is working fine.
#view :- test.blade.php
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
jQuery(document).ready(function($){
$('#category').change('select', function()
{
$.ajax({
type: "GET",
url : "my_test",
#route.php
Route::get('test',function()
{
return View::make('test.test');
});
Route::get('my_test' ,'test@get_index');
#controller:- test.php
<?php
class test extends \BaseController {
public function get_index()
{
$data = Input::all();
if(Request::ajax())
{
Any clue man? Its wired.. what's wrong with post method? In both method I am not using slash '/' in end of URL.
Heyyy! Sorry, i wasn't around for these many days!
Some Solutions, some seems nonsense, but works sometimes!
Firstly have you set local server, because these issue comes with the server management. However, remove Request::ajax() and then try. Use absolute URL. use URL : "/test" instead of "test". Its good to set up a server instead of file:/// , this kinda URL.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community