AJAX reloads the page without inserting into database - javascript

I am new to Ajax and confused. The problem is the ajax reloads the page. The function mentioned in the url inserts the data into database. but the page reloads. I guess the URL is not working but i am not sure on this.
Here is my Controller Function
public function insert_student_fee_payment()
{
$std_code=$this->input->post('std_code');
$total_fee=$this->input->post('total_fee');
$payable_fee=$this->input->post('payable_fee');
$date=date('Y m d');
$class_detail=$this->db->select('class.class_year,class.class_semester')
->join('class','class_student.class_id=class.class_id','LEFT')
->where('class_student.student_id',$std_code)
->where('class_student.class_student_status',2)
->limit(1)
->get('class_student')
->result();
if(count($class_detail)>0)
{
foreach($class_detail as $cd)
{
$year=$cd->class_year;
$semester=$cd->class_semester;
}
}
$data=array(
'std_code'=>$std_code,
'year'=>$year,
'semester'=>$semester,
'total_fee'=>$total_fee,
'payable_fee'=>$payable_fee,
'date'=>$date,
'status'=>2
);
if($this->db->insert('student_fees',$data))
{
echo '1';
}
}
and here is my Ajax code in form
<script type="text/javascript">
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '<?php echo base_url()."index.php/finance/insert_student_fee_payment;?>',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
});
});
any help guys

We don't see the HTML so it's hard to say what's wrong but my guess is that $('#insert_fee_payment') is a submit button so you have to cancel the action by default which is submitting the form.
$('#insert_fee_payment').click(function(e){
e.preventDefault();
};
or
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
return false;
});

Add return false after the error function.
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
return false;
});
});
});

Related

Laravel 8 and ajax

Never used ajax before and I'm quite new to Laravel as well.
I'm running a function where it gets the information from the form and i have no idea how to do the request with the information that I need.
function myFunction() {
var x = document.getElementById("frm1");
//console.log(x.elements.personSearch.value);
var details = x.elements.personSearch.value;
document.getElementById("personValidation").innerHTML = "";
if (
!details.match(
/\b[a-zA-Z ]*\\[a-zA-Z ]*\\[0-3][0-9][0-1][0-9][0-9]{4}\b/g
)
) {
document.getElementById("personValidation").innerHTML =
"Your search does not match the required format";
return;
}
$.ajax({
url: "/api/pnc/person",
type: "POST",
dataType: "json",
success:function(amount) {
console.log(amount);
}
});
``` Javascript
public function person(Request $request)
{
$request->validate([
'search' => 'required'
]);
return "test";
}
You need to Follow 3 steps for Ajax Request-
1. Setup Ajax Header bottom of your code. I mean before </html> add below code.
<script>
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
2. If you don't use Header Then you can use.
<script>
$(document).ready(function () {
$("#your_form_id").submit(function(e) {
var details = $('#details_input_id').val();
if(your_condition){
$.ajax({
url: "api/url",
type: "post",
data: {"_token": "{{csrf_token()}}", 'details':details},
success:function(data){
//Your response
if(data){
consol.log("Print what you want to print");
}
}
});
}else{
alert("Your search does not match the required format")
}
});
});
</script>
3. Your Route will be like ajax url
Route::post('api/url', [YourController::class, 'functionName'])->name('functionName');

JavaScript libraries are not working inside Ajax

#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
function notyfy() {
$.notify({
message: "Hello"
}, {
type: 'danger'
});
}
notyfy();//THis works
$("#btnSave").click(function (e) {
savedata();
});
function savedata() {
var items = new Array();
$("#tblGRN TBODY TR").each(function () {
var row = $(this);
var item = {
'PoNo': $("#PoNo").val(),
'FundSource': $("#FundSource").val(),
'Vote': $("#Vote").val(),
'Total': row.find("TD").eq(5).html(),
'InvoiceNo': $("#InvoiceNo").val(),
'ReceivedDate': $("#ReceivedDate").val(),
'Note': $("#Note").val()
}
items.push(item);
});
$.ajax({
type: "POST",
url: "/GRN/Create",
data: JSON.stringify(items),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
notyfy(); //This do not work
alert(r.responseText);
console.log(r);
$("#tbody").empty();
window.location = "/GRN/Create";
}
});
}
</script>
$.notify is not a function
$.notify works outside without any issue. anything I put inside the success function giving me not a function. all libraries are working fine outside the ajax.
The whole script part is above. please help me to solve the issue in this.

stopping a function after first click, to prevent more executions

I have this function
function display() {
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
and it serves its purpose, the only problem is, a user can click on for as many times as possible, and it will send just as many requests to new.php.
What I want is to restrict this to just 1 click and maybe till the next page refresh or cache clear.
Simple example would be :
<script>
var exec=true;
function display() {
if(exec){
alert("test");
exec=false;
}
}
</script>
<button onclick="javascript:display();">Click</button>
In your case it would be :
var exec=true;
function display() {
if(exec){
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
exec=false;
}
});
}
}
This should do what you want:
Set a global var, that stores if the function already was called/executed.
onceClicked=false;
function display() {
if(!onceClicked) {
onceClicked=true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
}
During onclick, set a boolean flag to true to indicate that user clicked the link before invoking the display() function. Inside the display() function, check the boolean flag and continue only if it is true. Reset the flag to false after the AJAX completed processing (successful or failed).
You can use Lock variable like below.
var lock = false;
function display() {
if (lock == true) {
return;
}
lock = true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function (data) {
$('.daily').html(data);
lock = false;
}
});
}
you can implement this with that way too
$(function() {
$('#link').one('click', function() {
alert('your execution one occured');
$(this).removeAttr('onclick');
$(this).removeAttr('href');
});
});
function display(){
alert('your execution two occured');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="display();" id='link'>Have you only one chance</a>

Updating quantity of multiple field from selections using jQuery

I'm updating quantities in an order form with predefined "packs" from the database. Updating the from fields from the "packs" dropdown in the first function works, but the second function that uses those values and multiplies them by the value in a text input does not update the fields.
Also, when looking at the console output, it looks like the ajax request from the first and second function both run when the quantity input is changed.
jQuery(document).ready(function($) {
$("[id^=packs]").on('change', function() {
var packname = this.value;
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1);
$('#'+lineno+'-size1').attr("value", obj.packdetail[0].size1);
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
//multiply packs
$("[id^=packs_qty]").on('change', function() {
var pack_qty = this.value;
var packname = $(this).attr("data-name");
console.log("qty:"+pack_qty);
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1*pack_qty);
$('#'+lineno+'-size1').attr("value", (obj.packdetail[0].size1*pack_qty));
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15*pack_qty);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2*pack_qty);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25*pack_qty);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3*pack_qty);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35*pack_qty);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4*pack_qty);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45*pack_qty);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5*pack_qty);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55*pack_qty);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6*pack_qty);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65*pack_qty);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7*pack_qty);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75*pack_qty);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8*pack_qty);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85*pack_qty);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9*pack_qty);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95*pack_qty);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10*pack_qty);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105*pack_qty);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11*pack_qty);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115*pack_qty);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12*pack_qty);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125*pack_qty);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
});
can you please convert obj.packdetail[0].size1 and pack_qty in to Number and try,
for this you can use
parseInt(obj.packdetail[0].size1) * parseInt(pack_qty);
Please have a try..

How to Hide multiple div on Ajax Success

I am trying to hide 2 div on Ajax Success by following code
$(".editButton").click(function () {
var self = this;
var membershipid = $(this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembershipDetail","User")',
data: { "MembershipID": membershipid },
success: function (data) {
$('#ddlStoreUpdate').val(data["fk_Store_ID"]);
$('#TxtTitleUpdate').val(data["MembershipTitle"]);
$('#TxtDescriptionUpdate').val(data["MembershipDescription"]);
$('#TxtTimeFrameUpdate').val(data["MembershipTimeFrame"]);
$('#TxtMembershipMinUpdate').val(data["MembershipMinVisit"]);
$('#chkUpdate').prop('checked', data["MembershipGroundLevel"]);
$('#HiddenMembershipID').val(membershipid);
if (data["MembershipGroundLevel"] == true)
{
alert("True");
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
}
else
{
alert("false");
$("#RowTimeFrame").show("slow");
$("#RowMinFrame").show("slow");
var storeid = $("#ddlStore").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetTimeFrame","User")',
data: { 'StoreID': storeid },
success: function (data) {
$("#TxtTimeFrame").val(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
},
error: function (data) {
alert(JSON.stringify(data));
}
})
$("#myModalUpdate").modal('show');
});
If condition is working well, but Div(s) doesn't hide
If I remove $(self).closest() from second div, first div hides all well, Issue is with multiple div
You can use class to hide it, like this:
$(".resetValueTo0").val(0);
$(".divToHide").hide();
Therefor, you don't need to do this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
You might want to try this:
Replace this code:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
To this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").each(function(){
$(this).hide();
});
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").each(function(){
$(this).hide();
});

Categories

Resources