Adding data to database using ajax jquery in laravel - javascript

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class categorycontroller extends Controller
{
public function display()
{
$cat=Category::all();
return view ('category',['cat'=>$cat]);
}
public function add(Request $request)
{
Category::create([
'Name' =>$request->name
]);
return response()->json(['success'=>'Data is successfully added']);
}
}
Route::get('/category','categorycontroller#display');
Route::get('/category/add','categorycontroller#add');
#extends('layout1')
#section('content')
<form id="myform">
<div class="form-group">
<!--<label for="name">Name :</label>-->
<table class="table table-bordered">
<thead><tr><th>Category</th><th colspan="2" align="center">Action</th></tr></thead>
<tbody>
</div>
#foreach($cat as $c)
<tr id='cat_{{$c->id}}'>
<td><input type="text" class="form-control" id="name_{{$c->id}}" value="{{$c->Name}}"></td>
<td><button class="btn btn-primary" id="btnupdate_{{$c->id}}" onclick="updatecat({{$c->id}})">Update</button></td>
<td><button class="btn btn-primary" id="btndelete_{{$c->id}}" onclick="deletecat({{$c->id}})">Delete</button></td>
</tr>
#endforeach
</tbody>
<tr><th colspan="2">New Category</th></tr>
<tr><td>
<div class="form-group">
<input type="text" class="form-control" id="name_0" value="">
</div>
</td>
<td>
<button class="btn btn-primary" id="btnadd">Add</button>
</td>
</tr>
</table>
</form>
<script type="text/javascript" src="{{asset('js/jquery.js')}}"></script>
<script>
$(document).ready(function(){
$("#btnadd").on('click',function(e){
e.preventDefault();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN':$('meta[name="_token"]').attr('content');
}
});
$.ajax({
url:"{{url('category/add')}}",
method:'get',
data:{
name:$('#name_0').val()
},
success:function(result)
{
$('.alert').show();
$('.alert').html(result.success);
//$('#tbcat').append(result.row);
}
});
});
});
</script>
#endsection
I write this code to display categories in the table from the database, it worked successfully. then I added ajax jquery code to add category to the database and display it after added to the table in the form. I wrote my codes in a blade.php and in the route and I used class category and category controller but when I click add button it's doesn't work successfully. Please can anyone help me to correct the error
h

In your resources/views/layouts folder, the main layout file should have those two elements to prevent CSRF attacks.
<!DOCTYPE html>
...
<meta name="csrf-token" content="{{ csrf_token() }}"/>
...
</head>
<body>
...
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
});
</script>
...
</body>
Also you need to remove this second part ($.ajaxSetup) from your onclick event handler. so it looks like this:
<script>
$(document).ready(function(){
$("#btnadd").on('click',function(e){
e.preventDefault();
$.ajax({
url:"{{url('category/add')}}",
method:'get',
data:{
name:$('#name_0').val()
},
success:function(result)
{
$('.alert').show();
$('.alert').html(result.success);
//$('#tbcat').append(result.row);
}
});
});
});

Related

How to run recaptcha 2 in html and php?

index html:
<!DOCTYPE html>
<html>
<head>
</head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<body>
<form method="post" action="/cms/common/sendEmail" enctype="multipart/form-data" class="valida tc" id="thisForm">
<input type="hidden" name="lang" value="tch" />
<tr>
<td>
<div class="g-recaptcha" id="recaptcha" data-sitekey="sitekey"></div>
</td>
</tr>
<tr>
<td class="submitBtnWrap"><input type="submit" value="送出" class="roundBtn" /><span class="at-error"></span></td>
</tr>
</table>
</form>
</body>
</html>
recaptcha.php:
<?php
$public_key = "6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ";
$private_key = "6Lc9oGIaAAAAAEthTaDOcm3VJ9Uldizbl6ZDKQ2_";
$url = "https://www.google.com/recaptcha/api/siteverify";
$q
=$_GET["q"];
echo $q;
if(array_key_exists('submit_form',$_POST)){
// echo "<pre>";print_r($_POST);echo"</pre>";
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
$response = json_decode($response);
// echo "<pre>";print_r($response);echo "</pre";
if($response->success == 1)
{
echo "Your information was valid...";
}else{
echo "You are a robot and we don't like robts.";
}
}
?>
Hello, I try to add the recaptcha 2 in my web. The site side and server side are done.
But how can I send the token to google server side verification using php file as the form action cannot be edited to action="recaptcha.php".
Or is any solution like using ajax, javascript to finish server side verification?
Please help me. Thank you all.
If you can't change action="recaptcha.php", you need to use AJAX to verify the responses.
So, Your index.html should be like
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="/cms/common/sendEmail" enctype="multipart/form-data" class="valida tc" id="thisForm">
<input type="hidden" name="lang" value="tch" />
<tr>
<td>
<div id="recaptcha" ></div>
</td>
</tr>
<tr>
<td class="submitBtnWrap"><input type="submit" value="送出" class="roundBtn" /><span class="at-error"></span></td>
</tr>
</table>
</form>
<!-- Add jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Add recaptcha explicitly -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<!-- render and verify by ajax -->
<script>
var onloadCallback = function() {
grecaptcha.render('recaptcha', {
'sitekey' : '6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ',
'callback' : verifyCallback,
});
}
var verifyCallback = function(response) {
$.post('recaptcha.php', {'g-recaptcha-response' : response}, function(data){
alert(data);
});
};
</script>
</body>
</html>
your recaptcha.php:
<?php
$public_key = "6Lc9oGIaAAAAAMK6Q4ZZ_qYzlvVCV1nydMLDUUoZ";
$private_key = "6Lc9oGIaAAAAAEthTaDOcm3VJ9Uldizbl6ZDKQ2_";
$url = "https://www.google.com/recaptcha/api/siteverify";
if(isset($_POST['g-recaptcha-response'])){
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
$response = json_decode($response);
if($response->success == 1)
{
echo "Your information was valid...";
}else{
echo "You are a robot and we don't like robts.";
}
}
?>

Autofilling an input field using JQuery

I have the following form:
<form method='post' id='myform'>
<div class="typeahead__container">
<div class="typeahead__field">
<input type="text" class="item" placeholder="Item" id='item' name='input_val'>
</div>
</div>
<input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>
<button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>
And the following function to handle live search:
$(document).ready(function(){
// Defining the local dataset
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
console.log(data)
let data = {
"results": [
{ "item": "First", "id": "1847" },
{ "item": "Second", "id": "4442" },
{ "item": "Third", "id": "3847" }
]
};
//LIVE-SEARCH
$(() => {
$('#item').typeahead({
source: {
data: data.results.map(record => record.item)
},
callback: {
onInit: function($el) {
console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
}
}
});
});
//END LIVE-SEARCH
});
});
I want to add another function to fill the default value of the input field item-id according to what the user chooses on the input field item. So, for example, if the user writes First, JQuery should set the default value of item-id to 1847 (see my previous block of code).
How can i do that? Am i supposed to do that inside my live search function or should i use another function?
Looking at your code, I assume you are using Bootstrap Typeahead which uses an updater callback that we can use in this situation.
I hosted this static Json to bring a solution with a close syntax.
Solution 1 : Using Bootstrap Typeahead (may be useful to someone else)
$(document).ready(function(){
$('input#item').typeahead({
source: function (query, process) {
return $.get('https://api.myjson.com/bins/hi1oo', function (data) {
//console.log(data);
//data = $.parseJSON(data);
return process(data.results);
});
},
display : 'item',
displayText: function(data){ return data.item;},
val : function(data){ return data;},
updater: function (data) {
$('#item-id').val(data.id);
return data.item;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" integrity="sha256-LOnFraxKlOhESwdU/dX+K0GArwymUDups0czPWLEg4E=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<form method='post' id='myform'>
<div class="typeahead__container">
<div class="typeahead__field">
<input type="text" class="item" placeholder="Item" id='item' name='input_val' autocomplete="off">
</div>
</div>
<input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>
<button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>
P.S : If your json is a result of a real-time search query where you look for item names and get this kind of data. Then you better change the source into something like following :
source: function (query, process) {
return $.get('inc/ajaxh.php', { query: query }, function (data) {
return process(data.results);
});
},
Solution 2 : using jQuery Typeahead
This one uses the callback onClickAfter. Notice that I made some changes on how you are mapping your data' response array and choose what to be displayed then use the item.id in the callback function.
$(document).ready(function(){
// Defining the local dataset
$.getJSON('https://api.myjson.com/bins/hi1oo', function(data) {
//LIVE-SEARCH
$(() => {
$('#item').typeahead({
source: {
//data: data.results.map(record => record.item)
data: data.results
},
display: ["item"],
callback: {
//I called it itemx to avoid confusion with available "#item"
onClickAfter: function (node, a, itemx, event) {
$('#item-id').val(itemx.id);
//alert('click');
}
}
});
});
//END LIVE-SEARCH
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha256-q6QA5qUPfpeuxzP5D/wCMcvsYDsV6kQi5/tti+lcmlk=" crossorigin="anonymous"></script>
<form method='post' id='myform'>
<div class="typeahead__container">
<div class="typeahead__field">
<input type="text" class="item" placeholder="Item" id='item' name='input_val'>
</div>
</div>
<input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>
<button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

jquery onclick function not defined

I have an ajax script and I am trying to post from a function. I am using a onlick href but its not coming up as undefined. This is using wordpress. I have tried to move the code around inside and outside the scope but I still cant seem to get it to work.
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name"/>
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>"/>
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
Submit Comment
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function(){
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html){
$('#displayComments').html(html);
});
}, 2000);
function submitComment(){
$.ajax({
method: "POST",
url: "template-live.php",
data: {submitComment:$('#chatBox').val(),submitName:$('#nameBox').val(),submitEmail:$('#emailBox').val()}
}).done(function(html){
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>
Thank you :)
When you do javascript:submitComment() that's calling a the global function submitComment. Since the submitComment is defined in the jQuery(function($) { ... }) function, it is not a global. Therefore, window.submitComment is undefined (hence undefined is not a function).
The globals are stored in the window object.
Therefore, you can expose that submitComment as a global:
window.submitComment = function () {...}
Note that you should avoid using globals as much as possible. In this case you can do that by adding:
$("#submit").click(submitComment);
// In this case, you shouldn't declare submitComment as a global anymore
And since you are in a form, you want to stop the default browser behavior when clicking the a element, by using return false at the end of the function.
Alternatively to #Ionică Bizău's solution.
You could use onclick="submitComment()" instead of href.
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name" />
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>" />
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function() {
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html) {
$('#displayComments').html(html);
});
}, 2000);
window.submitComment = function(){
console.log('submitComment called!');
$.ajax({
method: "POST",
url: "template-live.php",
data: {
submitComment: $('#chatBox').val(),
submitName: $('#nameBox').val(),
submitEmail: $('#emailBox').val()
}
}).done(function(html) {
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>

Form submission works with html but not javascript at the same time

I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});

Laravel 5.2 : How to post and delete data Using Ajax?

I want to post some data using Ajax and I also want to delete some data using Ajax.
But the problem is while inputting the data, data posted in database. But My UI faces some problem, after saving the data, my save Button always clicked. But as I'm using Ajax, it shouldn't load or previous data should automatically vanish.
Same as for deleting also, while deleting data get deleted, but it's redirecting to another page?
How do I solve the problem?
Here is my UserController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Http\Response;
use App\User;
use App\Post;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller {
public function postSignUp(Request $request) {
$this->validate($request, [
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'password' => 'required|min:4'
]);
$user = new User();
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
if ($request->ajax()) {
return response()->json();
}
}
public function delete(Request $request, $id) {
$user = User::find($id);
$user->delete($request->all());
}
}
?>
Here is my Post data View page:
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity = "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin = "anonymous">
</head>
<body>
<script src = "https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div class="container">
<h2>Register Form</h2>
<div class="row col-lg-5">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="Email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="send(event)" class="btn btn-default" >Submit</button>
</div>
</div>
<script type="text/javascript">
function send(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "{{route('signup')}}",
data: {name: $("#name").val(),
email: $("#email").val(),
password: $("#password").val(),
_token: '{!! csrf_token() !!}'
}
});
}
</script>
</body>
</html>
Here is my delete data view page:
<html>
<head>
<title> User Details </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container">
<h3> User Details </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>User Name</td>
<td>User Email</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach($user as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->email}}</td>
<td>
Edit
<div id="deleteTheProduct">
{!! Form::open([
'method' => 'POST',
'action' => ['UserController#delete',$row->id],
'style'=>'display:inline'
]) !!}
{!! Form::hidden('id',$row->id)!!}
{!! Form::submit('Delete',['class'=>'btn btn-danger deleteUser','id' => 'btnDeleteUser', 'data-id' => $row->id]) !!}
{!!Form::close()!!}
</div>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$('.deleteUser').on('click', function (e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url(' / delete') }}'
+ '/' + dataId,
method: 'POST',
data: inputData,
success: function (data) {
console.log(data);
}
});
});
</script>
</body>
</html>
to prevent redirect problem just make .delete button as button not submit, I think this will fix your problem, if not please inform me,
to delete row please make following changes on your script code... first is yours code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
}
});
});
have some changes in above code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
// added code is
$object=$(this);
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
//if success status is successful and below code removes the parent row from the table
$($object).parents('tr').remove();
}
});
});
But as I'm using Ajax, it shouldn't load or previous data should automatically vanish
You will have to control that yourself, ajax is like a request to web server without reloading the page (or navigating) but the browser doesn't know what action to make after the ajax request. as you are using jQuery you can update your UI after Ajax request in success callback.
try for example returning the id of deleted object and in ajax success function.
success: function(data) {
jQuery('#'+data.id).remove();
}

Categories

Resources