Buttons received from Ajax are not clickable - ajax

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='';})});

Related

Laravel Return Response From Ajax

I am trying to learn Laravel9. For this I have Created a Controller, a model and blade view file. Below is my vatprofile.blade.php file code
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "/vatprofile",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>
And this is my Rout,
Route::get('/vatprofile',
[VatProfileController::class,'index']);
And Below is my Controller Function
public function index(){
return response()->json(['success'=>'Record is successfully added']);
}
It is not Giving Error, Not printing out any response. Only the Blank Page is Showing up. Can you Correct me Pls
Please try this:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "{{ url('vatprofile') }}",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>

How to send data from ajax to controller

I want to transfer data to the controller using ajax. Here is the ajax code
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
name2:"admin",
_token: $("input[name='_token']").val()
}
})
});
Here is the code in the controller
public function insert_db(Request $request)
{
dd($request->all());
}
Here is the layout code
<form action="/insert_" method="post">
#csrf
<input type="submit" id="bt1" value="do it">
</form>
Here is code в web.php
Route::post('/insert_',"StudentController#insert_db");
Displays this
Why does display this? Please help
Your jquery ajax request should look like below:
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
"name":"test",
_token: $("input[name='_token']").val()
}
})
});
or
$(document).on("click", '#bt1', function(e)
{
var payload = JSON.stringify({
'name': 'test',
'_token': $("input[name='_token']").val()
});
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:payload
})
});
There is nothing wrong with your code, but i will love to get the string part by coding it like this
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
"name2":"admin",
_token: $("input[name='_token']").val()
}
})
});
noticed that i changed name2:"admin" to "name2":"admin"

MVC Razor Ajax call from button click

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);
}
});
});

jQuery-ui Autocomplete display results wrong

I am using jQuery-ui autocomplete to create a search field with a remote data source. Everything works and I get results, however the results does not display in a list below the textfield like it is supposed to. The results are put in a list and gets displayed at the bottom of the page.
Here is my code:
<script>
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request,response)
{
$.ajax({
url: "<?php echo $this->webroot; ? >portfolios/ajax_clients_dropdown/"+request.term+".json?callback=ajax_clients_dropdown?",
// dataType: "text",
async: false,
//jsonp: "callback",
jsonpCallback: "ajax_clients_dropdown",
success: function(data)
{
var fin = [];
for(a=0;a<10;a++)
{
fin[a]= data[a].value;
}
console.log(fin);
response(fin);
console.log("success");
},
appendTo: "#autocomplete",
position: {'my': 'left top', 'at': 'left top', 'of': '#autocomplete'},
error: function(response){console.log("Fail");}
});
}
});
});
</script>
<div class = "ui-widget" id="container">
<label for ="autocomplete">Clients</label>
<input id = "autocomplete" style ="" autocomplete = "on">
</div>
It doesn't matter weather I do the appendTo with #container or #autocomplete, it does nothing.
Here is the result that's supposed to be displayed:
["3434a62c bf592581", "a3ee7766 7894a7e0", "ea41d8ec 4e7df334", "919f6fac 96d4cdf0", "24ecac17 bfbed443", "f0270fc4 a2659300", "ea803fac 94b43df4", "5337467f 1a41e158", "fc54b844 0a19b69e", "a7393c7b aaea998b"]
Does anyone have an idea why this is happening?
I think that there might be a few issues here. If you just want the default behaviour for displaying, then you shouldn't need to mess with appendTo or position. Try the following:
<script>
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request,response) {
$.ajax({
url: "<?php echo $this->webroot; ?>portfolios/ajax_clients_dropdown/"+request.term+".json?callback=ajax_clients_dropdown?",
// dataType: "text",
async: false,
//jsonp: "callback",
jsonpCallback: "ajax_clients_dropdown",
success: function(data) {
var fin = [];
for(a=0;a<10;a++)
{
fin[a]= data[a].value;
}
console.log(fin);
response(fin);
console.log("success");
},
error: function(response){console.log("Fail");}
});
}
});
});
</script>
<div class="ui-widget" id="container">
<label for="autocomplete">Clients</label>
<input id="autocomplete" style="" autocomplete="on">
</div>
Except for the data source, which you say is working, this should be the same as what I have here.
Edit: This answer doesn't fix the problem, see comments for details.
Your appendTo and position properties have been assigned to the AJAX request, not to the autocomplete call. It's easier to see with the indentation fixed.
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request,response) {
$.ajax({
url: "<?php echo $this->webroot; ?>portfolios/ajax_clients_dropdown/"+request.term+".json?callback=ajax_clients_dropdown?",
// dataType: "text",
async: false,
//jsonp: "callback",
jsonpCallback: "ajax_clients_dropdown",
success: function(data) {
var fin = [];
for(a=0;a<10;a++)
{
fin[a]= data[a].value;
}
console.log(fin);
response(fin);
console.log("success");
},
error: function(response){console.log("Fail");}
});
},
appendTo: "#autocomplete",
position: {'my': 'left top', 'at': 'left top', 'of': '#autocomplete'}
});
});
For those of you who have this issue, first make sure you go here:
https://jqueryui.com/autocomplete/
And you are referencing the correct css and jquery files. Next, this was my issue in ASP.NET MVC 4. I created a bundle, using
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/core.css", .....
but when I referenced it in my layout page, instead of calling #Styles.Render("~/Content/themes/base/css") I was calling #Scripts.Render("~/Content/themes/base/css").
This caused
<script src="/Content/themes/base/jquery-ui.css"></script>
to be inserted rather than
<link href="/Content/themes/base/jquery-ui.css" rel="stylesheet"/>
so for those of you running into this situation using MVC, that could be it, or you may just not be referencing the correct css and js files properly.

Why Ajax Jquery form click not working vs div that works?

Ajax Jquery form not working vs div why its happen and how can i fix my error?
view.html-Code with form
not working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<form id="parse-form" action="#" method="post">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</form>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
view.html -form replaced by div
working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="parse-form">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</div>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
controller.php -simple php file that return json array:
<?php
$arr=array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Thanks
The form has a default action with a type="submit" button, which is submitting, so you'll need to stop that from happening by adding return false or event.preventDefault() , like this:
$(document).ready(function() {
$('#submit-html').click(function(e) {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
return false;
//or e.preventDefault();
});
});
Without this, the form is submitting as it normally would with no JavaScript, leaving the page. So effectively it's doing a refresh, instead of AJAX submitting your form (which doesn't have time to complete...because you left :)
An element of type=submit inside a <form> will perform the form request when clicked on.
You need to abort the default behavior by running event.preventDefault() inside the click callback.
My guess is that the form is submitting and refreshing the page before the ajax has a chance to respond.
Try putting return false; at the end of the click handler.
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Of course you'll have the same issue if the user hits Enter in one of the fields. Unless you're preventing the Enter key from submitting the form, you may want to the handle the event using the submit() handler.
$('#parse-form').submit(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Try using submit() http://api.jquery.com/submit/ , this should work with keyboard events as well as clicks. You can use serialize() to get any form data into the ajax objects data variable.

Resources