Ajax post in Laravel blade form not submitting - javascript

I'm trying to add some additional data to a form in my laravel blade using js and ajax post, but I can't get the form to submit. I've stripped everything else out to try to find what's wrong, but I'm mystified. Can anyone help?
My blade looks like this;
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-md-6 mt-5 mb-2">
<div class="card">
<div class="card-body">
<form id="payment-form">
<button id="card-button" class="btn btn-lg btn-block btn-success">
<span id="button-text"><i class="fas fa-credit-card mr-1"></i>{{ __('Add Payment Method') }}</span>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('javascript')
<script>
const cardButton = document.getElementById('card-button');
var form = document.getElementById('payment-form');
cardButton.addEventListener('click', function(event) {
// event.preventDefault();
console.log('On click check');
var payment = '1234';
$.ajax({
type: "POST",
url: "/payment-post",
data: {
payment: payment,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
});
});
</script>
#endsection

You have to use like this
var payment = '1234';
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
url: "{{url('')}}/payment-post",
dataType: "text",
data: {
payment: payment,
_token: CSRF_TOKEN
},
success: function (response) {
//Do something
}
});

In the end I tracked this down to 'defer' being present in the script tag in the header, which was stopping all the event listeners from working. Once I changed it to this
<script src="{{ asset('js/app.js') }}"></script>
everything working fine.

Related

Ajax status update in one page with one button

I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code

Hiding html element clicked after ajax success

I'm new to Web Development and making a mock twitter application. I want the tweet box to be removed after I click on the delete button (only if it is actually deleted in the backend)
I'm using django templating to loop through each tweet:
{% for tweet in data%}
<div class="container border border-primary rounded">
<p> tweet: {{tweet.content}}</p>
<div class="row">
{{tweet.id}}
<p class = "likes" style="margin: 0px 10px;"> likes: {{tweet.likes}} </p>
<button class="btn btn-dark like" style="margin: 0px 10px;">like</button>
<p class = "retweets" style="margin: 0px 10px;" > retweets: {{tweet.retweets}}</p>
<button class = "btn btn-dark retweet" style="margin: 0px 10px;">retweet</button>
<button class="btn btn-dark float-right delete_tweet" onclick="delete_tweet('{{tweet.id}}')">delete</button>
</div>
</div>
{% endfor %}
Here's the delete_tweet function:
function delete_tweet(id){
$(document).ready(function(){
$.ajax({
url: "{% url 'deleteTweet'%}",
data: {'id':id},
dataType: 'json',
success: function(data){
console.log(data);
$(this).parent().parent().remove();
}
});
});
}
This deletes the tweet in the backend fine, but the remove method doesn't work -
I'm pretty sure that I'm this is not referring to the right scope, what should I be doing instead?
Use .closest(".your-element-name").remove();
Your Button
function delete_tweet(id, that){
$(document).ready(function(){
$.ajax({
url: "{% url 'deleteTweet'%}",
data: {'id':id},
dataType: 'json',
success: function(data){
console.log(data);
$(that).closest(".rounded").remove();
}
});
});
}

Bootstrap Pop-Up modal-backdrop Doesn't Disappear

I have a slight problem when pop-up is closing; modal-backdrop is not closing.
This code blog for opening pop-up:
<script>
$('div.ProjePartialGovde').click(function (el) {
var projeid = $(this).data('id');
$('.popupListe').html('içerik hazırlanıyor...');
$.ajax({
method: "get",
url: '#Url.Action("ProjeOzetPartial", "Home")',
data: { projeID: projeid,ilID:#ViewBag.ilID }
})
.done(function (msg) {
$('.popupListe').html(msg);
$("#detayModal").modal();
});
});
And this is my pop-up page:
I'm having trouble with my back button. When I clicked back button it goes backwards but there is something gray on the screen wich is: "modal-backdrop in"
<div class="modal" id="detayModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form>
<div class="form-group">
<label class="form-control">Başlangıç / Bitiş Tarihleri: #Model.SozBasTarihi / #Model.SozBitisTarihi</label>
</div>
<div class="form-group">
<label class="form-control">Nakdi ve Fiziki Tamamlanma Oranları: %#Model.NakdiTamOrani / %#Model.FizikiTamOrani</label>
</div>
</form>
</div>
<div class="modal-footer">
<!-- I HAVE PROBLEM HERE -->
<button class="ProjeListesiGeri" data-dissmiss="modal" data-backdrop="false">BACK</button>
</div>
</div>
</div>
</div>
<!-- GO BACK CODE -->
<script>
$('.ProjeListesiGeri').click(function (el) {
$('.popupListe').html('içerik hazırlanıyor...');
$.ajax({
method: "get",
url: '#Url.Action("ProjelerListesiPartial", "Home")',
data: { ilID: #ViewBag.ilID }
})
.done(function (msg) {
$('.popupListe').html(msg);
});
});
</script>
How can I solve this problem?
I solve the problem. I added in my back code this line: $("#detayModal").modal('hide'); and it is working.
So full code:
<script>
$('.ProjeListesiGeri').click(function (el) {
$("#detayModal").modal('hide'); <!-- I added this line. -->
$('.popupListe').html('içerik hazırlanıyor...');
$.ajax({
method: "get",
url: '#Url.Action("ProjelerListesiPartial", "Home")',
data: { ilID: #ViewBag.ilID }
})
.done(function (msg) {
$('.popupListe').html(msg);
});
});
</script>

How to load a page through ajax and jquery in cold fusion?

When I run this script I am getting AjaxFunction is undefined. I have searched and know that it is not defined in proper scope but can anyone let me know what is the correct way to define it and what is the reason for the error.
<script type=”text/javascript”>
function(AjaxFunction) {
alert(“test”);
$.ajax({
type: “GET”,
url: “cfquery.cfm”,
success: function (res) {
alert(res);
document.getElementById("loadingdiv").style.display = ”block”;
document.getElementById("loadingdiv").innerHTML = res;
}
});
};
</script>
<cfform id="PageloadAjax" name="PageloadAjax">
<div id="Displayingdiv" name="displayingdiv">
<cfinput id="CFQUERYbutton" name="CFQUERYbutton" type="button" value="Displaypage" onclick="AjaxFunction">
</div>
<div id="loadingdiv" name="loadingdiv"></div>
</cfform>
Right now you are defining an anonymous function with AjaxFunction as a parameter. Step one in getting this to works is to change
function(AjaxFunction) {...}
into
function AjaxFunction() {...}
Also, in the onClick attribute, you must call the function, not just name it. So change
onclick="AjaxFunction"
into
onclick="AjaxFunction()"
I recommend looking at some basic JavaScript material to more easily understand and solve these minor issues. You could start with W3 Schools for easily understandable tutorials, or You don't know JS if you want more in-depth JavaScript knowledge.
Try this
<script type=”text/javascript”>
function AjaxFunction() {
alert(“test”);
$.ajax({
type: “GET”,
url: “cfquery.cfm”,
success: function (res) {
alert(res);
document.getElementById("loadingdiv").style.display=”block”;
document.getElementById("loadingdiv").innerHTML=res;
}
});
};
</script>
And call function in onclick = "AjaxFunction()".
the answer that perfectly worked for me is:
<script type="text/javascript">
function AjaxFunction(mode) {
var url="";
if ( mode =="contacts") url = "cfquery.cfm";
if ( mode =="tagsvsscripts") url = "cfqueryprogram.cfm";
if ( mode =="siteinfo") url = "CFtagsvsscripts.cfm";
if ( mode =="Jqueryhide") url = "dynamic.cfm";
$.ajax({
type: "GET",
url: url,
success: function (res) {
$("#results").addClass("loading");
document.getElementById("loadingdiv").style.display="block";
$("#results").html(res);
$("#results").removeClass("loading");
}
});
}
</script>
<div class="card mb-4">
<div class="card-header bg-secondary">
Ajax Page Load Example Using Bootstrap
</div>
<div class="card-block">
<div class="row">
<div class="col-lg-3 col-xl-2 col-form-label">
<input class="btn btn-primary" name="CFQUERYbutton"
type="button" value="Displaypage" onclick="AjaxFunction('Jqueryhide')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('contacts')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('tagsvsscripts')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('siteinfo')">
</div>
<div id="loadingdiv" name="loadingdiv">
</div>
<div id="results"></div>
</div>
</div>
</div>

How to use javascript to trigger a modal one after another

I want to use the code below to accomplish the following flow:
validate user's input (form in a modal pop up)
if no error, trigger another modal to show something. The content of the result modal comes from an ajax call.
The problem is the result modal never shows.
Edited: The problem seems in relation to e.preventDefault() as I tested with another version which makes the ajax call in $("#frmSchPkg").submit(function(e).
It works with preventDefefalut and doesn't work if preventDefault() is missing.
Perhaps the question is how to add preventDefault() to this posted javascript.
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
alert(data); // able to see data being expected. so the ajax call is successful
$('#text-modal').modal('hide'); // tried to comment this out for testing, 1st modal vanishes anyway at this point
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
}
});
<div class="modal fade text-modal" id="text-modal" tabindex="-1" role="dialog" aria-labelledby="smallModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm2">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search</b></h2>
</div>
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSchPkg">
<div class="modal-body">
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" name="pkgnum12" id="pkgnum12" type="text" placeholder="enter tracking number" data-validation="number length" data-validation-length="12-12" />
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<button name="btnfind" id="btnfind" type="submit" class="clsfind btn btn-store btn-block">
<i class="fa fa-search"></i> Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="LookupResultModal" tabindex="-1" role="dialog" aria-labelledby="LookupResultModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search Result</b></h2>
</div>
<div class="ct_schpkgresult"></div>
</div>
</div>
</div>
The JS script should be like
Ajax method should be inside validation onSuccess: function($form) { }
First modal hide and 2nd modal show should be in side Ajax method success: function(data) { }
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
alert(dataString);
$.ajax({
type: "POST",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide'); //If all good hide first modal
$('#LookupResultModal').modal('show'); //show 2nd modal
$('#LookupResultModal').find('.ct_schpkgresult').html(data); //show response in 2nd modal
},
error: function(err) {
console.log(err);
}
});
}
});
I found the following solution:
$.validate({
form: '#frmSchPkg',
onSuccess: function(form) {
return $.sendFormDataViaAJAX(form);
}
});
$.sendFormDataViaAJAX = function(form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide');
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
return false;
};

Categories