I have a page on which i have placed several jquery sliders, some checkboxes and radio buttons.
I post is created on slidestop, change of checkboxes, change or radio buttons. This works great.
On this same page there is a table displayed with this information and in the buttons which are outbound links, i have placed id's which are posted to another controller to track the outbound clicks with their id's.
When the button is clicked a post with the id is done using jquery to this clicks controller.
This works great when the sliders, checkboxes, radio buttons aren't used. As soon as one of those elements are touched the post to this clicks controller on the buttons click doesnt work anymore.
This is what the javascript looks like:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$(".btn").bind("click", function (event) {
$.ajax({
async: true,
data: "id=" + $(this).attr("id"),
dataType: "html",
type: "POST",
url: "\/clicks"
});
return false;
});
$("#saveForm").bind("slideStop", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
$(".checkbox").bind("change", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
$(".radio").bind("change", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
});
//]]>
</script>
I think it's caused by the multiple posts on the same page but i'm not sure. I have been trying to fix this the whole day but couldn't find a solution.
Update:
I found what is causing the other function to fail.
$this->Js->get('#saveForm')->event(
'slideStop',
$this->Js->request(
array('action' => 'index', 'controller' => 'abonnements'),
array(
'update' => '#resultaat',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST',
'before' => '$("#loading").attr("style", " ")',
'complete' => '$("#loading").attr("style", "display:none")'
))
);
The action for the .btn which is displayed in the #resultaat table is broken when the update is done by the slideStop action.
This is how the button looks like:
<td>
<?php echo $this->Html->link('Meer Info',
$link,
array('class' => 'btn btn-primary btn-block',
'target' => '_blank',
'id' => $abonnement['Abonnement']['id']
)
);
?>
</td>
The id is needed.
I have solved the issue by placing the jquery code for the button click on the element which is updated by the other jquery function. Somehow it lost the bind when the slider updated the element in which another bind is placed.
Related
I'm using the following code to receive some content from a page called filter.PHP. But the issue is the buttons become not clickable once fetched.
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "POST",
url: "filter.php",
dataType: "html",
success: function(response) {
$("#responsecontainer").html(response);
}
});
});
});
</script>
I have buttons like these on the filter.php file.
<button onclick="location.href='details.php?id=<?php echo htmlspecialchars($result->nid); ?>'" class="buttonnew">Details </button>
Any help would be much appreciated.
You have to add the event listener from JavaScript, when you fetch the html from an ajax response.
document.querySelector('.buttonnew').addEventListener('click', () => { location.href=''});
Or
document.querySelectorAll('.buttonnew').forEach(btn => { btn.addEventListener('click', () => { location.href='';})});
i am triyng to save data but my page is reloading with json message on next page, how can i stop reloading page.
Ajax Code:
jQuery(document).ready(function($) {
$("#add-data").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Submit Button:
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
Store Controller:
after saving which is working fine:
return response()->json([
'status' => 'success',
'msg' => 'New esecond has been saved'
]);
It is because of you are trying to post the data to form .
If you use button type = "submit" it will redirect you to somewhere .
You should avoid using type = "submit" .
Instead use the type = "button"
<button type = "button" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
And achieve it by using click event of the button .
then get it in jquery .
$("#add-data").click(function (event) {
//Your code here
}
You can try this instead of prevent default. The reload happen, because you use form submit event.
$('#add-data').submit(false);
If you want to use prevent default, then use click event of the submit button to perform the action.
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
}
Remove dataType: 'json' as you're already returning JSON otherwise your button seems perfect.
Try this
jQuery(document).ready(function($) {
$("#add-data").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Add "return false;" in the end of your submit callback..
As "add-data" is ID of your button, for your example it couldn't retrieve a submit event. That's because it submitted and didn't prevented.
So you can write something like this:
$("form").submit(function (event) {
event.preventDefault();
$.ajax({ ... });
return false; // <<< THE THING
});
Or just do that with binding an click event on button (not for submit event on button)
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({ ... });
});
With this you can leave button type, and don't need to change that to type="button".
I just migrated to a different bootstrap template now my ajax functions is not working and my php file which handles the functions is not appearing in the XHR inspect tool of chrome.
I only have this jquery script ? is this enough for running an ajax function? I
<!-- Jquery Core Js -->
<script src="../dashboard-assets/plugins/jquery/jquery.min.js"></script>
HTML CODE
<form id="upload_book_form" method="POST">
<p>Upload Books</p>
<input type="file" id="uploadbookinfo" name="uploadbookinfo" value="Import" />
</form>
SCRIPT FUNCTION
<script type="text/javascript">
$(document).ready(function() {
//upload book
$('#uploadbookinfo').change(function() {
$('#upload_book_form').submit();
});
$('#upload_book_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Book Added , Try refreshing the page',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else if (getdata == "ERRORFILETYPE") {
swal({
title: 'Oops...',
text: 'File type is not supported',
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-info",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>
I'm struggling to get a button click to invoke an Ajax function which then posts to a controller action. Cannot even get a simple message to work (nothing happens when button is clicked). Clearly, I'm missing something fundamental. What is it?
The Ajax script in my Razor form:
<script type="text/javascript">
$('#UseShipAddr').click(function () {
$.ajax({
url: "#(Url.Action("UseShippingAddress", "Checkout"))",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
</script>
The button that I want to use to invoke the Ajax function:
<input type="button" value="Use Shipping Address" id="UseShipAddr" />
The action in CheckoutController:
// Ajax POST: /Checkout/UseShippingAddress/5
[HttpPost]
public ActionResult UseShippingAddress(int id)
{
return Content("It worked!");
}
Please try this code.
$(document).ready(function(){
$('#UseShipAddr').click(function () {
$.ajax({
url: "Checkout/UseShippingAddress",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
I trying to upload image using ajax in Laravel 5. I am using following code but nothing happends:
image.blade.php
{{Form::open(array('action' => 'ImageController#store','files'=>true,'id'=>'upload_form'))}}
Title: {{Form::text('title')}}
Image: {{Form::file('image')}}
{{Form::submit('submit',['id' => 'btnAddProduct'])}}
{{Form::close()}}
#include('flash::message')
ImageController.php
public function store(Request $request)
{
$destinationpath = public_path() . '/img/';
$image=$request->input('image');
$filename=$request->file('image')->getClientOriginalName();
$request->file('image')->move( $destinationpath,$filename );
return Response::json(['success' => true, 'file' => asset($destinationpath.$filename)]);
}
Ajax code:
<script>
$(document).ready(function() {
$('#submitButtonId').on('click', function() {
$.ajsubmitButtonIdax({
url:'/imgC/store',
data:new FormData($("#upload_form")[0]),
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
});
</script>
Route.php:
Route::resource('imgC', 'ImageController');
What I am doing wrong?