I have two select elements both using selec2.js, the first select element has drop down options populated from the database, now what I want to do is to choose an option from select element 1, get the value and send that value via ajax to query the database and return matching results and populate the results in the 2nd select element. unfortunately, I haven't succeeded with returning data back from the server, below is my code and oh I am using laravel.
$('#province').on('change', function (e) {
var data = $("#province option:selected").val();
$.ajax({
url: "{{route('list-townships')}}",
type: 'get',
data: {
province_id: data
},
success: function (response) {
console.log(response);
response.filter(function (response) {
if (response) {
//Append data to the 2nd select element
}
})
},
error: function (err) {}
})
});
Okay, I find the issue here, due to laravel CSRF request protection I had forgotten to define the CSRF Token in the ajax header. the complete code is below.
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#province').on('change', function(e) {
var data = $("#province option:selected").val();
console.log(data);
$.ajax({
url: "{{route('list-townships')}}",
type: 'get',
data: {
province_id: data
},
success: function(response) {
console.log(response);
response.filter(function(response) {
if (response) {
var townships = new Option(response.name, response.id, false, false);
$('#township').append(townships).trigger('open');
}
})
},
error: function(err) {}
})
});
});
Related
I have a text area with id "text" and I am toggling the text area to appear on the screen with a click event on some div and I have 30 such divs.
Initially , I'm assigning the textarea.value with result of ajax call to my fetch api which fetches the data from the mongo on the server side based on an unique id.
Sometimes , when I'm making the ajax call to my update api in my backend , the textarea.value I'm sending as data to this ajax call is not the same as the updated text of the text area.
//client side
// called when any of the divs is clicked
$(".radius").on("click", function(event) {
//extracting the id from the class and using this id as the id of my data for my mongo
var st=event.target.classList[1].substring(0,7);
var num=parseInt(event.target.classList[1].substring(7));
var toadd="close-button"+num;
//console.log(num+"modal")
closeButton.classList.add(toadd);
$.ajax({type: "POST",
url: "/fetch",
async: true,
data: JSON.stringify({
id: num,
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
input.value=result.text;
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
});
// called when textarea is closed
function toggleModal1(event) {
var s1=closeButton.classList[closeButton.classList.length-1];
var st=s1.substring(12);
closeButton.classList.remove(s1);
var num=parseInt(st);
// event.preventDefault();
console.log(input.value)
$.ajax({type: "POST",
url: "/update",
data: JSON.stringify({
id:num,
text:input.value,
//input is my textarea
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
}
//server side
app.post("/fetch",function(req,res)
{
//console.log(req.body);
// var id1=req.body.id;
const findInDB= Fruit.findOne({id:req.body.id},function (err, docs) {
console.log(docs);
res.send({text:docs.text});
});
});
app.post("/update",function(req,res)
{
Fruit.updateOne({id:req.body.id},
{text:req.body.text}, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Updated Docs : ", docs);
}
});
I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.
This is how the code works:
(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.
(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated
(3) The form is then submitted via Ajax as well.
(4) If successfully submitted it perform another Ajax call to get the table updated.
First problem: when the table is loaded via Ajax the "edit" button is not working anymore.
Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?
Here it is the javascript code, server side all works just fine:
$(".edit-transaction").click(function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('updated successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Create a new transaction via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('created successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
Thanks for any help
Since some of the elements are added asynchronously, this means that the event listeners which were added at runtime will not affect those elements. You should instead listen to events on them via "events delegation".
You can also create a custom event for loading the table content. So to update the table, you just .trigger() your custom event. This is useful when you want to implement other functionalities which will need a table update like, delete, etc.
// custom event for loading the table content
$(document).on('load.table', '#display-transaction-list', function () {
const $table = $(this);
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: (data) => $table.html(data.html)
});
});
// edit transaction event
$(document).on('click', '.edit-transaction', function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
// save transaction event
$(document).on('submit', '#transaction-form', function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
// you can add some data to the response
// to differentiate between created and updated. Eg response.actionType
console.log('created or updated successfully')
// load the table with the new content updated
$("#display-transaction-list").trigger('load.table');
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
Right now i have the following code below, this code posts some data to my page and waits for a response of status = SUCCESS or Failure. I am trying to understand if this is async or sync. How can I make this JavaScript query wait for the response and then run what is inside success? It doesn't seem to wait for the response of what it is posting to.
Thanks!
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.post('', form.serialize(), function(json) {
console.log(json)
if(json.status === 'SUCCESS') {
console.log('success');
window.open(json.imgid, '_self');
} else {
console.log('failure');
}
}, 'json');
$('#progress_bar').show();
}
I then tried to work on making it work the way i wanted by editing the code below but now its just returning the HTML contents of the entire page rather than the JSON response. Any idea why its not getting the JSON response?
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.ajax({
url: '',
type: 'POST',
data: data,
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}
Add dataType: 'json', below data: data,
my.submit = function() {
var form = $('#lines');
//console.log(form)
var data = form.serialize();
//console.log(data)
$.ajax({
async: false,
url: '',
type: 'POST',
data: data,
dataType: 'json',
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
window.open(json.imgid, '_self');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}
I am trying to make a comment form which adds a comment in array of blog schema
but when I am using ajax it is giving undefined below the places where I have console log and when I am using simple post request it is working fine.
I am using mongoose, nodejs , express, jquery ajax
my script is as follows
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
function addNewComment(data){
console.log(data);
}
my routes is as follows
//add comments
router.post('/addComment',function(req,res,next){
console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
var newComment = {
'text': req.body.comment,
'author': req.body.userId
}
Post.addComment(req.body.postId, newComment, function(err,comment){
if(err) throw err;
console.log(comment);
res.send(comment);
});
});
and my mongoose schema is
//add comments
module.exports.addComment = function( postId, newComment, callback){
var query = { '_id': postId};
console.log('postid: '+postId+" newcomment: "+newComment.text+ " "+newComment.author);
Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}
That's because data is not defined in ajax call ,
use following provide the frm is the actallu form or use
use data : form name.serialize()
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
data : $(this).serialize(),
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
I have three functions that called as shown below (Functions not included):
Code:
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSourcepData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSpouseData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSpousData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllDividentData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveDividentData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".
This forces user to have to close three popup boxes.
Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?
You could also simplified your code by using Promise.all:
$("#btnSubmit").click(function() {
var allSourcepData = JSON.stringify(getAllSourcepData());
var allSpouseData = JSON.stringify(getAllSpouseData());
var allDividentData = JSON.stringify(getAllDividentData());
Promise.all([
getData('closures.aspx/SaveSourceData', allSourcepData),
getData('closures.aspx/SaveSpousData', allSpouseData),
getData('closures.aspx/SaveDividentData', allDividentData)
])
.then( alert )
.catch( alert )
});
function getData(url, data)
{
return new Promise((resolve, reject){
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: () => { resolve("Data Added Successfully") },
error: () => { reject("Error while inserting data"); }
});
})
}
You need to wait until all ajax requests are complete, like in this answer
So in your case you need to create functions for all $.ajax calls like this:
function ajax1() {
var data = JSON.stringify(getAllSourcepData());
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
}
// add ajax2() and ajax3() ...
And then use only one click handler like this:
$("#btnSubmit").click(function() {
$.when(ajax1(), ajax2(), ajax3()).then(function(a1, a2, a3){
// success, display message
}, function(){
// exception
});
});
You can reorder a little your code to use the deferred method to jQuery 1.5+ otherwise you can implement as this answer:
jQuery callback for multiple ajax calls
Why you want to call 3 times for button click?
Why not put them all together?
Any how you can use variable as isAlertToBeShown= false and after pushing data make it has true. finally check the variable is true or false.