Laravel 5 - AJAX not working - php

I have one problem with my script on LARAVEL 5. This is my route:
Route::get('cms/section/addCategory', 'Cms\SectionController#showCategory');
Route::post('cms/section/addCategory', 'Cms\SectionController#addCategory');
Controller:
// SHOW FORM WITH ADD CATEGORY
public function showCategory()
{
if (Sentinel::hasAnyAccess(['section.create']))
{
return view('cms.viewSystem.section.addCategory');
}
else
{
return view('cms.viewSystem.error');
}
}
// ADD NEW CATEGORY
public function addCategory()
{
return http_response_code(200);
}
Ajax Script:
$(document).ready(function() {
$('form.ajax input[type=submit]').click(function(){
$.ajax({
type: 'POST',
utl: $('form.ajax').attr('action'),
data: new FormData($('form.ajax')[0]),
processData: false,
contentType: false
}).then(
function(error) {
console.log('good'+error);
},
function() {
console.log('bad');
}
);
event.preventDefault();
})
});
And when I add http_response_code script working good but when I change value for 500 I see in console still informations for error 200... Have you any ideas?

Related

Request data of AJAX POST is null in Laravel Controller

I'm trying to send via AJAX data, I'm doing a post and then receiving it on the laravel controller.
I'm getting an error that the data is null.
I tried multiples ways to fix it but I'm not able to figure out how to do it.
Ajax:
$(document).ready(function () {
$('table tbody').sortable({
update: function (event, ui) {
$(this).children().each(function (index) {
if ($(this).attr('data-position') != (index + 1)) {
$(this).attr('data-position', (index + 1)).addClass('updated');
}
});
saveNewPositions();
}
});
});
function saveNewPositions() {
var positions = [];
$('.updated').each(function () {
positions.push([$(this).attr('data-index'), $(this).attr('data-position')]);
$(this).removeClass('updated');
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(positions);
$.ajax({
url: 'cursos',
method: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(positions),
contentType: "application/json; charset=utf-8",
traditional: true,
})
}
Laravel Controller:
public static function updateOrder(Request $request)
{
foreach ($request->positions as $position) {
$index = $position[0];
$newPosition = $position[1];
$seccion = SectionCourse::findOrFail($index);
$seccion->order = $newPosition;
$seccion->save();
}
return response('success', 200);
}
Doing a dd of the request, I receive this:
I fixed it using $request->toArray() instead of $request->positions directly

Use Ajax in Fat free framework to render route every 5 seconds

I need for help in fat free
I want to use ajax to render to a specific route every 5 seconds
But I can't console any data the ajax page
and this is my php code :
elseif ($this->session->isRole(UserRole::TRAINEE)) {
$this->assets->addJs('meeting.js');
$f3->push('init.js', 'Meetings');
$f3->set('name', $name);
$f3->set('joinUrl', 'meeting/' . $meetingId);
$this->render();
}
and this is my ajax code
let Meetings = function () {
let joinMeeting = function () {
$(document).on('click', '.join-meeting', function (e) {
e.preventDefault();
let meetingId = data.meeting_id;
$.ajax({
type: 'GET',
url: '/meeting/' + meetingId,
contentType: 'application/json',
success: function (result) {
if (result.joinUrl === 'none') {
noty({text: 'Could not join the requested meeting.', type: 'error'});
} else {
setInterval(window.open(result.joinUrl, '_blank'), 5000);
}
},
error: function (jqXHR) {
noty({text: 'Application error', type: 'error'});
}
});
});
};
return {
//main function to initiate the module
init: function () {
joinMeeting();
}
}
}();
If you render a page, the page is loaded and the script is reloaded again and set interval is never ejecuted.

Get date from datepicker using Ajax with Laravel controller

i want to get the datepicker value when user selected a date and send that using ajax to a laravel controller. this code is not worked for me..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#date').datepicker({
format: 'dd-mm-yyyy',
onSelect: function(date, instance) {
$.ajax({
type: "POST",
url: '/process_date',
data: date,
success: function(result)
{
console.log(result);
}
});
}
});
here is my route,
Route::post('/process_date', 'TimeController#ajaxTime');
here is my controller,
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
Try changing your code to this because I have been reading the documentation and testing it with some code of my own and this is what I came up with
$('#date').datepicker({
format: 'dd-mm-yyyy',
}).on('changeDate', function(e) {
$.ajax({
type: "POST",
url: '/process_date',
data: {
date: e.date.toString(),
},
success: function(result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
})
and also change your TimeController class from
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
to
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
return $request->all(); // This will get all the request data.
}
}
to receive better results in your browser console.

Codeigniter validation not working with ajax but without ajax working well

when submitting the form using ajax codeigniter validation not working please resolve this issue i am facing this problem from last week
jQuery code that i am using for submitting form
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
data: contactForm.serialize(),
success: function(response){
}
});
});
});
Controller
public function add_account() {
if($this->form_validation->run('add_account')) {
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
} else {
$this->login();
}
}
Here is just the concept. I have not tried codeigniter but am php professional.
You will need to retrieve records as json and pass it to ajax. At codeigniter
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'Account Created Successfully !');
echo json_encode($result);
hence the code might look like below
public function add_account(){
if($this->form_validation->run('add_account')){
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'ok');
echo json_encode($result);
//$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
}else{
$this->login();
}
}
in ajax you can set datatype to json to ensure that you can get response from the server and then let ajax handle the response....
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function(response){
alert(response.message);
console.log(response.message);
//display success message if submission is successful
if(response.message =='ok'){
alert('message submited successfully');
}
}
});
});
});
You have a misunderstanding about what an ajax responder can and cannot do. One thing it cannot do is use PHP to make the browser redirect to a new page. You will have to send a clue back to the success function and then react appropriately.
A few minor changes to the answer from #Nancy and you should be good.
public function add_account()
{
if($this->form_validation->run('add_account'))
{
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post))
{
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
echo json_encode(array("result" => 'ok'));
return;
}
$message = '<span class="error">Account Not Created!</span>';
}
else
{
$message = validation_errors('<span class="error">', '</span>');
}
echo json_encode(array("result" => 'invalid', 'message' => $message));
}
In the Javascript, handle the various responses in the success function of $.ajax
$(function () {
$("#registratiom_form").on('submit', function (e) {
var contactForm = $(this);
e.preventDefault();
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function (response) {
console.log(response); // so you can examine what was "echo"ed from the server
if (response.message=='ok') {
// Simulate an HTTP redirect: to the right page after successful login
window.location.replace( "https://example.com/frontend/somepage");
} else {
//stay on the same page but show the message in some predefined spot
$('#message').html(response.message);
}
}
});
});
});

php yii 2.0 new action in controller page not found 404

I'm using Yii 2.0 basic version and I need some help.
I created one ajax function like this:
function eliminarColaborador(id) {
$.ajax({
type: "GET",
async: false,
url: "<?= urldecode(Url::toRoute(['colaborador/ajaxEliminarColaborador'])) ?>",
dataType: 'json',
data: {
'id': id
},
complete: function ()
{
},
success: function (data) {
if (data !== null)
{
// SUCCESS
}
else
{
// ERROR
}
}
});
}
My action in controller:
public function actionAjaxEliminarColaborador($id) {
if (Yii::$app->request->isAjax) {
$continuar = false;
if(isset($id) && $id > 0) {
var_dump($model); die;
$continuar = true;
}
echo CJSON::encode(array('continuar'=>$continuar));
Yii::$app->end();
}
}
I'm getting this erro in firebug: Not Found (#404): Page not found.
I tried everything, but i can't figure out what's the problem.
If I change ajax url to urldecode(Url::toRoute(['colaborador/delete'])) the error is gone and all works just fine.
Maybe I need to declare in ColaboradorController my new action ajaxEliminarColaborador, but I don't know how.
What is wrong?
controller
public function actionAjaxEliminarColaborador(){}
ajax
urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador']))
It should be <?= urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador'])) ?>. Here you can learn why.
Change the ajax response with:
url: '/colaborador/ajaxEliminarColaborador/$id',
data: {id: $id,_csrf: yii.getCsrfToken()},
Try to remove the word 'ajax' on your url.

Categories