I am making a book library site using laravel. I am trying to add bookmark functionality. I have tried doing something like that on click of bookmark button, page no is being send to database and it is working. Issue is that on return from controller page is getting reload causing book to back on page no 1. Is there is any way that data sends to database without page reload??
I know a bit that ajax do this, but I am using JavaScript in my application and I tried to deploy ajax with it but no luck.
I am showing up my code. Any good suggestions would be highly appreciated.
My javascript function:
function bookmark()
{
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
count is defined up in script.
My route:
Route::post("save_bookmark/{b_id}/{p_no}",'BookmarkController#create')->name('save_bookmark');
My controller:
public function create($b_id, $p_no)
{
$b=new bookmark;
$b->u_id=Auth::user()->id;
$b->book_id=$b_id;
$b->p_no=$p_no;
$b->save();
return response()->json([
'status' => 'success']);
}
My html:
<li><a id="bookmark" onclick="bookmark()" >Bookmark</a></li>
Note: There is a navbar of which bookmark is a part. There is no form submission.
try this: use javascript to get the book id
$("#btnClick").change(function(e){
//console.log(e);
var book_id= e.target.value;
//$token = $("input[name='_token']").val();
//ajax
$.get('save_bookmark?book_id='+book_id, function(data){
//console.log(data);
})
});
//route
Route::get("/save_bookmark",'BookmarkController#create');
you need add event to function and add preventDefault
<button class="..." onclick="bookmark(event)">action</button>
in js:
function bookmark(e)
{
e.preventDefault();
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
in controller you ned use it:
use Illuminate\Http\Request;
...
...
public function create(Request $request)
{
$b=new bookmark();
$b->u_id=Auth::user()->id;
$b->book_id=$request->get('b_id');
$b->p_no=$request->get('p_no');
$b->save();
return response()->json([
'status' => 'success']);
}
in route use it:
Route::post("save_bookmark/",'BookmarkController#create')->name('save_bookmark');
Well, assuming your bookmark() JavaScript function is being called on a form submit, I guess you only have to prevent the form to be submitted. So your HTML code would looks like this:
<form onsubmit="event.preventDefault(); bookmark();">
Obviously, if you're handling events in your script.js it would rather looks like this:
HTML
<form id="bookmark" method="POST">
<input type="number" hidden="hidden" name="bookmark-input" id="bookmark-input" value="{{ $book->id }}"/>
<input type="submit" value="Bookmark this page" />
</form>
JavaScript
function bookmark(book_id, count) {
$.ajax({
type: "post",
url: "save_bookmark",
data: {
b_id: book_id,
p_no: count
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
let form = document.getElementById('bookmark');
let count = 1;
console.log(form); //I check I got the right element
form.addEventListener('submit', function(event) {
console.log('Form is being submitted');
let book_id = document.getElementById("bookmark-input").value;
bookmark(book_id, count);
event.preventDefault();
});
Also I would recommend you to avoid as much as possible to insert PHP code inside your JavaScript code. It makes it hard to maintain, it does not make it clear to read neither... It can seems to be a good idea at first but it is not. You should always find a better alternative :)
For example you also have the data-* to pass data to an HTML tag via PHP (more about data-* attributes).
Related
I don't have the knowledge about Ajax in combination with Laravel. I'm trying to build a like system, its already set up. The problem is; when you click on the like button, the whole page refreshes. But I want it to be dynamic. To do this, I need to use Ajax and jQuery
I have tried building a jQuery function, but I don't know how to parse the {id}
Could you show me where I can learn more about this subject? Maybe a tutorial or could you please explain to me the part I'm missing.
$('.like').on('click', function(event) {
console.log("clicked the button");
$.ajax({
method: 'POST',
url: /{id}/addlike
})
});
This is the like button:
<form action="/{{$new->id}}/addlike" method="post">
#csrf
<button value="{{$new->likes}}" class='like' type="submit"><i class="fas fa-fire"></i></button>
</form>
This is the like route:
Route::post('/{id}/addlike', 'ImageController#like');```
This is the "like" controller
public function like($id)
{
$picture = ImageModel::find($id)->increment('likes');
return back();
}
Remove type='submit' It will redirect your page, just add type="button" and in .like function() ajax should be like this, always apply if and else condition in case you getting some error so it will reflect on your browser console.
$.ajax({
type: "POST",
url: Apiurl,
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
success: function (data)
{
if(data.status == 'success' )
{
//apply your condition
}
else
{
console.log('error');
}
}
});
You can pass data in your ajax functions like data: {id: yourid, name: somename}, and also you can assign laravel variable values to js like this:
var testId = '{{$yourid}}'
So in your case you can make url like testId + '/addlike', also always make id or other dynamic thing go at the end like 'addlike/' + testId.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
})
});
Hope it helps
Don't add
return back();
in your controller instead you can use
return response()->json(['success' => 'Liked']);
or anything you want to input there to pass the data in ajax. Don't put action in your post instead you can use hidden input to put your id there and call it (if you're using jquery)
$('input [name=nameofhidden]').val();
then in your ajax add success and what you want to do after updating the data.
var id = $('input[name=nameofhidden]').val();
$.ajax({
method: 'POST',
url: '/'+id+'/addlike',
success: function(ifyouhavedata){
//what you want to do
}
})
JavaScript logic you need to return false, so it'll stop redirecting. see below code.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
});
return false;
});
Controller should be return like below
return response()->json(['success' => 'Liked'],200);
I am trying to post the data from this form into the database. I have tried some tutorials with no success. Here is my code. Any ideas?
View:
<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>
AJAX (in the view, right below the form)
<script type='text/javascript' language='javascript'>
$("#submitbutton").click(function(){
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
},
error: function(){
alert("Fail")
}
});
e.preventDefault();
});
</script>
Controller
function insert_into_db(){
$this->load->model('insert_db');
$this->insert_db->insertQ();
}
Model
class Insert_db extends CI_Model{
function insertQ(){
$email = $_POST['email'];
$qText = $_POST['qText'];
$this->db->query("INSERT INTO questions VALUES('','$email','$qText','','')");
}
}
As #David Knipe already said, you should wait for the DOM to be ready before trying to access one of its elements. Moreover, you likely have an e is undefined error, since you're not passing the event reference to the click handler:
<script> //no need to specify the language
$(function(){
$("#submitbutton").click(function(e){ // passing down the event
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
$('#email').val('');
$('#qText').val('');
},
error: function(){
alert("Fail")
}
});
e.preventDefault(); // could also use: return false;
});
});
</script>
To be more complete, your query is vulnerable, and you might be getting an error there. Make use of the advantage of having a framework beneath you:
function insertQ(){
$email = $this->input->post('email');
$qText = $this->input->post('qText');
$this->db->insert('questions', array('email' =>$email, 'text' => $text));
}
^_ I'm guessing the column names since you didn't specify them
Looks like you've forgotten to use $.ready. As it is, the javascript runs before the page has loaded, which means it can't find the page element from $("#submitbutton"). Try this:
$(document).ready(function() {
$("#submitbutton").click(function(){
....
....
});
I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as FabrÃcio Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>
Just started using AJAX today via JQuery and I am getting nowhere. As an example I have set up a job for it to do. Submit a form and then display the results. Obviously I haven't got it right.
The HTML.
<form id="PST_DT" name="PST_DT" method="post">
<input name="product_title_1682" id="product_title_1682" type="hidden" value="PADI Open Water">
<input name="product_title_1683" id="product_title_1683" type="hidden" value="PADI Advanced Open Water">
<input type="submit" name="submit" id="submit" value="Continue" onclick="product_analysis_global(); test();"/>
</form>
<span id="results"></span>
There are actually many more fields all loaded in dynamically. I plan to use ajax to submit to PHP for some simple maths and then return the results but we can worry about that later.
The JQuery
function test() {
//Get the data from all the fields
var alpha = $('#product_title_1682').val();
JQuery.ajax({
type: 'POST',
url: 'http://www.divethegap.com/update/functions/totals.php',
data: 'text=' + alpha,
beforeSend: function () {
$('#results').html('processing');
},
error: function () {
$('#results').html('failure');
},
timeout: 3000,
});
};
and the PHP
<?php
$alpha = $_POST['alpha'];
echo 'Marvellous',$alpha;
?>
That's my attempt and nothing happens. Any ideas?
Marvellous.
First of all, you're passing the $_POST variable as 'text' while your script is looking for $_POST['alpha']. If you update your PHP to $_POST['text'], you should see the proper text.
Also, if your form is going to have lots of inputs and you want to be sure to pass all of them to your AJAX Request, I'd recommend using jQuery's serialize() method.
data: $('#PST_DT').serialize(), // this will build query string based off the <form>
// eg: product_title_1682=PADI+Open+Water&product_title_1683=PADI+Advanced+Open+Water
In your PHP script you'd then need to use $_POST['product_title_1682'] and $_POST['product_title_1683'].
UPDATE Add a success callback to your $.ajax call.
function test() {
// serialize form data
var data= $('#PST_DT').serialize();
// ajax request
$.ajax({
type : 'POST',
url : 'http://www.divethegap.com/update/functions/totals.php',
data : data,
beforeSend : function() {
$('#results').html('processing');
},
error : function() {
$('#results').html('failure');
},
// success callback
success : function (response) {
$('#results').html(response);
},
timeout : 3000,
});
};
In your PHP script you can debug the information sent using:
var_dump($_POST);
In your AJAX request, you are sending the parameter foo.php?text=..., but in the PHP file, you're calling $_POST['alpha'], which looks for foo.php?alpha=....
Change $_POST['alpha'] to $_POST['text'] and see if that works.
There is a simpler method:
$("#PST_DT").submit(function(e){
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'http://www.divethegap.com/update/functions/totals.php',
success: function(){
....do stuff.
}
});
return false;
});
This will allow you to process the variables like normal.
I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});
If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {
try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...