Laravel 4, jQuery .ajax, No post input received - javascript

I must be missing something, didn't think this would have been a issue.
I have a login form that has no connection to laravel form, although its on the same domain, and a POST route with laravel at "login".
I can change it to GET and everything works, but I would like to use POST.
/online/index.html
$("#login").click(function(e){
console.log( $("#loginForm").serialize() );
var request = $.ajax({
url: "../login/",
type: "POST",
data: { test : "someuser" },
dataType: "json"
});
request.done(function( data ) {
console.log("Complete");
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log("Failed");
console.log(textStatus);
});
});
Route::post('login', array('as' => 'login', 'uses' => 'AuthController#doLogin'));
( which is below /online/ )
class AuthController extends Controller {
public function doLogin(){
$username = Input::get('username');
$password = Input::get('password');
return Response::json(Input::all());
}
}
In the javascript console, when you press login, it shows...
Complete
[]
When it should say something like this...
Complete
[ test => "someuser" ]
Using Laravel 4, jQuery 1.8.3. Any ideas would be great... Thanks!

I just removed the trailing slash in the Ajax request URL and everything worked as planned.

Related

Internal Server Error 500 when creating in laravel using ajax jQuery, wrong variables format from ajax to controller

I'm trying to create a new service option while creating a bill (a bill can have many services), it's like creating a new tag, or category while writing post without reloading, but i have this internal server error 500, i think the problem is in the Controller because it works fine when i comment the create in controller, route and csrf and stuff are checked, thanks for helping me !
In my javascript :
var max_service_id = {{$max_service_id}};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#add_service_button").on("click",function(e){
e.preventDefault();
var service_name = $("input[name=service_name]").val();
var service_category = document.getElementById('service_category').value;
var service_description = $("input[name=service_description]").val();
$.ajax({
type:'POST',
url:'/service/add-in-bill',
dataType: 'json',
data:{
name : service_name,
category_id : service_category,
description : service_description
},
success:function(data){
if (data.message) {
//This is error message
alert(data.message);
}
if (data.success) {
alert(data.success);
var newService = new Option(service_name, max_service_id, false, true);
$('.multipleSelect').append(newService).trigger('change');
max_service_id++;
$("#add_service_div").hide("fast");
}
}
});
})
});
In my controller :
$validator = Validator::make($request->all(), [
'name' => 'required|unique:services',
'category_id' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message'=>$validator->errors()->all()]);
} else {
// It works fine when i comment this, so i think the problem is something about variables from javascript to php stuff
Service::create($request->all());
return response()->json(['success'=>'Create service success !']);
}
//
// I think the problem is in the Controller because it works fine when i comment the "Service::create($request->all());"

wp_verify_nonce returns false on staging server but returns true on localhost

I'm trying to verify a very simple ajax request in WordPress (in order to diagnose a probem with a bigger form), and wp_verify_nonce keeps failing on my staging server, but on my localhost it works perfectly!
My setup is like this:
In my plugin __construct function I have:
wp_register_script('request-quote', plugins_url('scripts/request-quote.js', $this->root), array('jquery'));
wp_enqueue_script('request-quote');
wp_localize_script('request-quote', 'pqimageupload',
[
'ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce( 'my_text' )
]);
add_action('wp_ajax_prq_checknonce', [$this, 'prq_checknonce'] );
add_action('wp_ajax_nopriv_prq_checknonce', [$this, 'prq_checknonce'] );
Then in my request-quote.js I have this:
$('#verify_nonce').on('click', function(){
console.log('checking nonce');
let data = {
action: 'prq_checknonce',
security: pqimageupload.security,
}
$.ajax({
url: pqimageupload.ajax_url,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
console.log(data);
}
});
return false;
});
My prq_checknonce function is:
function prq_checknonce()
{
$response = [];
$response['nonce'] = $_REQUEST['security'];
$response['verify'] = wp_verify_nonce($_REQUEST['security'], 'my_text');
$json = json_encode($response);
echo $json;
die();
}
My HTML link:
Verify nonce
So it's about as simple as you can get! And when I click on the link on my local server: http://abc.localhost/form/' the console log shows thatverifyis 1, however when I upload this to my staging serverhttps://abc.myserver.com/form/` console log shows verify as false!
Does anyone have any ideas?
Much appreciated
Lar
Gaaahhh I'm so stupid!!! It was a caching issue, so whilst I was removing my temp files, I didn't delete my cookies... deleting my cookies did the trick!!

jQuery Ajax post is not working

I know that there is a lot of questions like this out there, but I have been surfing them and other website for like 4 hours trying to figure this out. I am trying to get main.js to post the data via ajax and then the php should echo that data. If it does not work, it will echo "null". It keeps echoing "null" instead of "John". I know that the jquery and main.js links work, I have tested them. Here is main.js:
$(document).ready(function(){
$.post("index.php", { test: "John"} );
});
And here is the php part of index.php:
<?php
$var = "null";
if(isset($_POST['test'])) {
$var = $_POST['test'];
}
echo $var;
?>
I hope you can solve my problem, and thank you in advance.
You are missing the callback function with the response from the server.
$.post( "index.php",{ test: "John"}, function( data ) {
alert(data);
});
Or you can do something like this:
$.post( "index.php",{ test: "John"})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Please check the documentation Documentation
Give this a shot
jQuery
var available agent = 1;
jQuery.ajax({
type: "POST",
url: "your-url",
data: available_agent,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data){
owner = data['round_robin_agent'];
},
error : function () {
alert("error");
}
});
PHP Script
public function round_robin() {
//Do your work
$round_robin_agent = 'rob';
$results_array = array(
'round_robin_agent' => $round_robin_agent
);
return json_encode($results_array);
}
Download HTTP Trace chrome extension, traceback ajax call and share a screenshot.
https://chrome.google.com/webstore/detail/http-trace/idladlllljmbcnfninpljlkaoklggknp

Problema sending json file from javascript to laravel controller

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.

POST Request not working using Ajax in Laravel

I tried implementing ajax post request in laravel 4, but I am unable to obtain the post data. I have tried implenting both input::get() and input::all().
Here is the ajax code:
$.ajax({
url :url,
type:'POST',
data:{username:username},
dataType:'JSON',
success:function(data){
console.log(data);
}
});
Controller Class code:
class UserController extends Controller
{
// Obtain the response text
protected function _make_response( $response_str, $type = 'application/json' ) {
$response = Response::make( $response_str );
$response->header( 'Content-Type', $type );
return $response;
}
// User Login Function
public function loginAction()
{
// $setting_name = Input::get( 'username' );
$username = Input::get('username');
$response = array(
'username' =>$username,
);
return $this->_make_response( json_encode( $response ) );
}}
I am not able to paste the image here. So I am pasting the result that obtained from Firebug.
POST http://localhost/d/dthKerala/public 200 OK 117ms
Object {...}
But I change the request Type to GET. I am able to obtain the data.
GET http://localhost/d/dthKerala/public?username=render 200 OK 119ms
Object {username="render"}
How can I be able to obtain POST data ?
The mistake you made is sending data with a field value pair called => . Just change data to have a name "username" with value username
$.ajax({
url :url,
type:'POST',
data:{"username":username},
dataType:'JSON',
success:function(data){
console.log(data);
}
});
Hope this helps.
$.ajax(
{
url :url,
type:'POST',
dataType:'JSON',
data:{'username':username},
success:function(data){
console.log(data);
}
});
Will you be able to specify your route portion
Also I would like to suggest to use Response::json() instead of writing more line of codes:
public function loginAction()
{
return Response::json(array('str'=>$response_str))
}

Categories

Resources