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

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.

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>

Buttons received from Ajax are not clickable

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

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"

How to call ajax function on buttonclick in laravel?

View Code:
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Here ,When I click on the button it should be replaced by the other text. But nothings appears on clicking.
Controller code:
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
In pure js that code work fine
function getMessage(){
alert('Its working!');
}
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Looks OK.
Put a breakpoint in your success and see what data is.
Or do a console.log
Mick
in your ajax code you didn't define dataType, add dataType:"json", to retrive the json data, change your ajax code as
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
dataType:'json',
data:{
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
$("#msg").html(data.msg);
}
});
Update your code with below mentioned code, and let's try.. i will working for me..
<script type="text/javascript" charset="utf-8">
$(document).on('click', '#btnSelector', function(event) {
event.preventDefault();
/* Act on the event */
getMessage();
});
var getMessage = function(){
$.ajax({
type:'POST',
url:'/getmsg', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" id='btnSelector'>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
<div id='msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" id="ajax_call" value="Replace Message">
</body>
<script>
$(function () {
$('#ajax_call').on('click', function () {
$.ajax({
type:'POST',
url:'<?php echo url("/getms"); ?>',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
},
complete: function(){
alert('complete');
},
error: function(result) {
alert('error');
}
});
});
});
</script>
Jquery onclick function: jquery onclick function not defined
Also check: Function not calling within an onclick event

Populate data from mysql to ListView (JQuery Mobile) using ajax

<div data-role="main" class="ui-content">
<ul data-role="listview" id="responsecontainer" >
</ul>
This is my html file.
var output = $('#responsecontainer');
$.ajax({
url: 'http://192.168.1.28/mobile/db_select.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<li><a href="#"><h2>'+item.tr_issue+'</h2>'
+ '<p>'+item.tr_assign+'</p></a></li>';
output.html(landmark);
console.log(output);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
This is my JavaScript.
I want to populate my listview from my database(mysql) but the problem is when it generates the theme of jquery mobile di not work.
its like a simple unordered list. thanks in advance
Add $('ul').listview('refresh'); after appending the HTML
Show change your success callback as below
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<li><a href="#"><h2>'+item.tr_issue+'</h2>'
+ '<p>'+item.tr_assign+'</p></a></li>';
output.html(landmark);
console.log(output);
});
$('ul').listview('refresh');
},

Resources