I would like to delete a comment via Ajax in background, without refreshing a page.
I made a button with onclick function which will pass the id of the comment:
<button type="button" class="btn btn-primary" onClick="return delete_comment(<?=$data['comment_id']; ?>);">Delete comment</button>
and I am not sure how to pass a comment id to PHP function:
<script>
function delete_comment(comment_id)
{
if (confirm("Delete?")) {
$.ajax({
type: 'post',
url: '/comments/delete/' + comment_id,
data: $('form').serialize(),
success: function () {
alert("Deleted.");
}
});
}
return false;
}
</script>
To delete a comment I need to call PHP script like: /comments/delete/comment_id
I'm assuming, the mistake you are making is, the type. If you use GET type. Then we can post the Javscript paramter to the PHP form using the page /comments/delete/123123.
But,since you are using POST. Specificing the comment id in the URL is not going to pass the variable into the PHP form. For which, you will have to use the following ajax.
$.ajax({
type: 'POST',
url: '/comments/delete/',
data: {
id: comment_id
},
success: function () {
alert("Deleted.");
}
});
Method 2
If you are not particular about the POST method. Then, you can change your PHP form to GET and the ajax type to GET
$.ajax({
type: 'GET',
url: '/comments/delete/' + comment_id,
data: $('form').serialize(),
success: function () {
alert("Deleted.");
}
});
Thank all you guys for help.
The problem seems to be a PHP script not the mentioned HTML with Ajax
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 have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});
edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});
I have a PHP program for counting user banner clicks. My banner link is something like this:
<a href="<?=$banner_url;?>" onclick="banner_click_count('<?=$banner_id;?>')"><img src=...>
When user clicks on image, it runs banner_click_count() function with $banner_id as parameter.
function banner_click_count($ban_id)
{
$.ajax({
type: "POST",
url: 'banner_click.php',
data: {banner_id: $ban_id}
});
}
At banner_click.php, I get the banner_id with $banner_id = $_GET['banner_id']);, search the database based on it. Find the record, then add 1 to banner_count column field. After that, redirect to banner_url.
When I run the program, I get Parse error: parse error, expecting T_VARIABLE' or '$'' on line $.ajax({
Addendum: the error is cleared with all your help, but when I click on the link it redirects to banner_url directly and does not run the AJAX function.
Addendum:I put the alert("hello"); at the top of ajax function and i got it. So it goes into function
1.You need to put your javascript function under <script> tag
2.you need to pass json string as post data
3.though you are passing your data as post so you will get this data in php as $_POST not $_GET
So change your function as below
<script>
function banner_click_count(ban_id)
{
$.ajax({
type: "POST",
url: 'banner_click.php',
data: {banner_id: ban_id}
});
}
</script>
// in your php use as below
echo $_POST['banner_id']
Make sure banner_id is in quotes and that you are including JQuery in your page.
And don't forget a success/error return.
$.ajax({
type: "POST",
url: 'banner_click.php',
data: {'banner_id': $ban_id},
success: function(s) {
console.log('success' + s);
},
error: function(e) {
console.log('error' + e);
}
});
Don't we need a return false before the function ends?
I found the solution. Thanks to all.
function banner_click_count(ban_id)
{
$.post(
"banner_click.php",
{
banner_id: ban_id
});
}
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.