laravel 5 ajax request controller app not working - php

i want to use this code buy it stays in Procesando, espere por favor....
Jquery:
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ajax/pregunta',
type: 'POST',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (data) {
$("#resultado").html(data.resultado)
}
});
Html
Introduce valor 1
<input type="text" name="caja_texto" id="valor1" value="0"/>
Introduce valor 2
<input type="text" name="caja_texto" id="valor2" value="0"/>
Realiza suma
<input type="button" href="javascript:;" onclick="realizaProceso($('#valor1').val(), $('#valor2').val());return false;" value="Calcula"/>
<br/>
Resultado: <span id="resultado">0</span>
Route
Route::post('ajax/pregunta', [
'as' => 'ajax/pregunta', 'uses' => 'AjaxController#pregunta'
]);
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Response;
class AjaxController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function pregunta(){
$resultado = Request::input('valorCaja1') + Request::input('valorCaja2');
return response()->json(['resultado' => 'Roberto']);
}
}
When i clic in "Calcula" button " Procesando, espere por favor..." apears in the screen but it dont load the succes code, any solution??
Thanks!!

I think that you need provide a token , i'm not sure but i believe that is necesary
in your page blabla.blade.php add
<input type="hidden" name="_token" id="_token" value="{{{ csrf_token() }}}" />
and then in your ajax call
var tok = $('#_token').val();
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2,
"_token" = tok
};
regards...

Related

laravel ajax insert data form comment success only in firts column

Sory my english is not good, I have a problem with comment input form in my program. the comment field in the process will only succeed if the filled column is the top column. if the comment field other than the above will fail. please enlighten him
this is a successfull process in first column comment
but if I write in the comment field other than the above will fail
token and field with_id same as comment column above, whereas value from barengan_id if in inspect element differ its contents. and also comment field so empty value
and this is my code
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Barengan;
use App\BarenganComment;
use App\User;
class CariBarenganCommentController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request,Barengan $id)
{
$data = [
'user_id' => auth()->id(),
'barengan_id' => $id->id,
'comment' => $request['comment'],
];
return BarenganComment::create($data);
}
public function destroy(Barengan $barengan_id,$id)
{
BarenganComment::destroy($id);
}
}
And this my form in view
<div id="form">
<form method="post" data-toogle="validator" class="form-horzontal">
{{ csrf_field() }}
{{method_field ('POST')}}
<input type="hidden" name="id" id="id">
<input type="hidden" name="barengan_id" value="{{$d->id}}" id="barengan_id">
<div class="styled-input">
<input class="input inputkoment" type="text" placeholder="Tulis Komentar ..." name="comment" id="comment">
<span></span>
<button type="submit" class="btn btn-default pull-right btn-custom-komen"><i class="fa fa-chevron-circle-right"></i></button>
</div>
</form>
</div>
<script src="{{asset('js/jquery-1-11-0.js')}}"></script>
<script>
function deleteComment(id) {
var popup = confirm("apakah anda yakin akan menghapus data?");
var csrf_token = $('meta[name="csrf-token"]').attr('content');
if(popup == true){
$.ajax({
url: "{{ url('caribarengancomment')}}/"+id,
type: "POST",
data: {'_method': 'DELETE','_token': csrf_token
},
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert("Opppps gagal");
}
})
}
}
$(function () {
$(document).on('submit','#form form',function (e) {
if (!e.isDefaultPrevented()) {
var barenganId = $('#barengan_id').val();
console.log(barenganId);
url = "{{ url('caribarengan')}}/" + barenganId + "/comment";
// url= '{{route('caribarengancomment.store',$d)}}';
$.ajax({
url: url,
type: "POST",
data: $('#form form').serialize(),
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert('Oops! error!');
}
});
return false;
}
});
});
</script>
and my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BarenganComment extends Model
{
protected $fillable = ['user_id','barengan_id','comment'];
public function user()
{
return $this->belongsTo(User::class);
}
public function barengan()
{
return $this->belongsTo(Barengan::class);
}
}
I am very tired these days stack here :(
you use multiple forms on page? look like id`s of inputs conflict.
try this way
<form method="post" data-toogle="validator" class="form-horzontal" data-barengan="{{$d->id}}">
...
if (!e.isDefaultPrevented()) {
var barenganId = $(this).data('barengan');

How to take value from textarea to textarea with Laravel + Jquery Ajax?

How do I take value from one textarea to another with laravel and jquery ajax.
I have this files so far.
Route:
Route::post('/post', 'PostController#post');
Controller:
class PostController extends Controller
{
public function post(Request $request)
{
$request->json()->all();
}
}
JQuery file:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(data);
}
});
});
});
and the html :
<textarea class="form-control" name="firsttextarea" rows="10" id="firsttextarea" ></textarea>
<button id="insert" class="btn btn-md btn-primary"><span class="glyphicon glyphicon-circle-arrow-right"></span>Insert</button>
<textarea class="form-control" name="secondtextarea" rows="10" id="secondtextarea" ></textarea>
When i push the button nothing happens.
First problem probably can be in CSRF Verify. You can disable it if it so or add {{ csrf_token() }}.
Then your post action should be looks like this:
public function post(Request $request)
{
return response()->json($request->all());
}
I checked it and it's work fine. but in textarea insert [Object object] because it JSON. You can add JSON.stringify in your Jquery script like this:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(JSON.stringify(data));
}
});
});
});
Try this, you're not returning a response in your Controller method.
class PostController extends Controller
{
public function post(Request $request)
{
return response()->json([
'data' => $request->get('intrare'),
]);
}
}
then, add this to your head in your blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
and replace your JS with the below:
$(function() {
// We need CSRF Token in our ajax request so we can
// validate the POST request
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
// Insert text from first textarea to the other textarea
$("#insert").on("click", function(e) {
e.preventDefault();
var intrare = $("textarea#firsttextarea").val();
$.ajax({
type: "POST",
url: "/post",
data: { intrare: intrare },
success: function(response) {
$("textarea#secondtextarea").val(response.data);
}
});
});
});

laravel Redirect from Controller to View when Login Success with Session not working

I'm new to Laravel 5.2 . I have been trying to create a login Page using Session and i wanted to redirect to another page when user login is successfull ...I validate users in Controller create Session and Redirect to a Success Page View but its not returning ...i tried to solve it but i am unable to do so ...the Controller is not returning the View success page ..am i doing it correctly or im missing something
<form id="loginForm">
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" id="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" required>
<button type="button" id="loginButton">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</body>
<script type="text/javascript">
$(function(){
$('#loginButton').click(function(){
//alert(SERVER_NAME);
var formData = new FormData($('#loginForm')[0]);
$.ajax({
url : SERVER_NAME+"/api/userLogin",
type :"POST",
data :formData,
processData: false,
contentType: false,
dataType :"json",
beforeSend: function(){
},
success : function(response)
{
console.log(response);
//return false;
if(response.status==1){
alert(response.message);
// window.location.href = 'home';
}else{
alert(response.message);
}
},
complete:function(){
}
});
});
});
</script>`
MY Controller
public function userLogin(Request $request)
{
$input = $request->all();
//return $input;
$userName=$input['username'];
$password=$input['password'];
//return $userName;
$results = wowza::authenticate($userName,$password);
if (sizeof($results)>0){
if($results[0]->email==$userName && $results[0]->password == $password)
{
Session::set('variableName', $userName);
$results['status']=1;
return \View::make('user.home')->with('results',$results);
// return response()->json($results);
}
}
return sizeof($results);
}
My Success Page
{{Session::get('variableName')}}
My Route
Route::get('/', function () {
return view('user.login');
});
Route::get('home', function () {
//Session::get('username');
return view('user.home');
});
$api->version('v1',function($api){
$api->post('userLogin','App\Http\Controllers\Api\V1\wowzaController#userLogin');
});
You can change at auth controller as
protected $redirectTo = '/dashboard';
or
at route as
Route::get('dashboard', function () { return redirect('your-path');
}); `
Your page is not redirecting because you are loading the view file in your controller. Instead of this code:
return \View::make('user.home')->with('results',$results);
You should use redirect('home') method.
Let me know if that does not work.

How to load another view by using ajax in codeigniter

here is my first view
<form id="bussearch">
<input class="form-control" id="value1" name="start" type="text" />
<input class="form-control" id="value2" name="value2" type="text" />
<input class="form-control" id="value2" name="value3" type="text" />
<button class="btn" type="submit">Search for Bus</button>
</form>
here is the script
$("#bussearch").submit(function(e) {
$.ajax({
type: "POST",
url: "http://siteurl/controller/test",
data: $("#bussearch").serialize(),
success: function(data)
{
$("#div_result").html(data);
//alert(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
Here is my controller
function test()
{
$response = $this->load->view('welcome_message',TRUE);
echo $response;
}
here is the view welcome_message
<div id="div_result"></div>
I need to load a view after ajax sucess function, but view welcome_message is not loading
I do something similar to this to load data into modals.
In my controller I just call for the view:
public function update_user_modal()
{
$this->load->view('modals/update_user_modal');
}
The ajax is like this:
$.ajax({
url: "<?php echo base_url('admin/get_user_details'); ?>",
type: "POST",
data: { id: id }
}).done(function(msg) {
console.log(msg); // this will have the content of the view
}.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus + " - Please try again.")
})
I presume it is a typo in the ajax url you have provided as you are calling function test() within the controller but you are providing the function bus_test() in your controller.
Hope this helps.

TypeError in Ajax call

I'm getting the following error on Ajax call in Laravel 5:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,
The form is as follows:
<form id="comment_form">
<input type="textarea" class="form-control_comment" id="comment" placeholder="Type your comment here...">
<input type="hidden" name="uid" id="uid" value="{{$user->id}}">
<input type="hidden" name="pid" id="pid" value="{{$post->id}}">
<input type="hidden" id="token" value="{{$csrf_token()}}">
<button type="button" class="btn btn-sm btn-success" id= "comment_button">Submit</button>
</form>
The Ajax part:
<script>
$("#comment_button").click(function(e){
e.preventDefault();
var token = $("#token").val();
var a= $("#comment").val();
var uid= $("#uid").val();
var url = "<?php echo Request::root();?>";
$.ajax({
url: url+"post/comment_action",
type: "POST",
async: false,
data: {newComment:a, uid:uid, pid:pid, _token: token},
success: function (newResult){
if(newResult!="")
{
newResult= JSON.parse(newResult);
$("#all_responses").append(newResult);
}
}
}).error(function()
{
alert("Error");
});
});
</script>
in routes.php:
Route::post('post/comment_action', array('as'=>'post/comment_action', 'uses'=>'PostController#postComment_action'));
And the action part in PostController:
public function postComment_action()
{
if(Auth::check())
{
if(Request::ajax())
{
$inputs= Input::all();
}
$new_comment= $inputs['newComment'];
$uid= $inputs['uid'];
$pid= $inputs['pid'];
$com= new Comment;
$com->content= $new_comment;
$com->userId= $uid;
$com->postId= $pid;
$com->save();
$data= array();
$all_comments= Comment::where('postId', $pid)->first();
$u= User::where('id', $uid);
foreach($all_comments as $coms)
{
$data= $coms->content;
}
$data= json_encode($data);
echo $data;
}
else
{
return Redirect::route('signin_user')->withErrors("You must sign in to perform this action");
}
}
Any help would be greatly appreciated :)

Categories