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 tried debugging my code but couldn't reason out the contents of my console.
You are referencing input in your client side code, but I don't see it anywhere in the code. Can you check?
Update:
the textarea.value I'm sending as data to this ajax call is not the
same as the updated text of the text area.
I assume that you have an error in the code related to input. If you can add it to your answer, it will be easier to help you.
Related
I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}
I am using data tables to show data and a button is present opposite to each entry of my data table.
That button has onclick which captures the parameter present in a row and save in array.
I want to change color when certain entry is selected and reset on deselect.
Here is what I am doing,
function select(name){
var property = document.getElementById('checkRule');
if( rArray.includes(name) ){
property.style.backgroundColor = "#FFFFFF"
const index = rArray.indexOf(name);
if (index > -1) {
rArray.splice(index, 1);
}
}else{
rArray.push(name);
property.style.backgroundColor = "#28a0ff"
}
console.log('ARRAY >> ', rArray);
}
This code is only changing color of very first element of of data table.
How shall I make it work?
Assuming that you want to send the ajax request after you select a radio button and you click on go.
You do not need to change the html, but you will have to change the javascript file.
$("#go").click(() => {
var result = $("input:radio[name='doamin']:checked").val();
console.log("result > ", result);
var Data = {
result1: result,
};
console.log("postData > ", Data);
$.ajax({
url: "import",
headers: {
Accept: "text/plain",
"Content-Type": "application/json",
},
type: "POST",
dataType: "html",
data: JSON.stringify(Data),
success: function (data) {
console.log(data);
},
error: function (err) {
console.log(err);
},
});
});
Ideally, you want to send a POST request, as there is a body attached.
I have tried to ajax using post to jsp script my html table rows for weeks now with no success.Can anyone please guide me on this?Below is what I have done so far.
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
$('#notSoCoolGrid > tr').each(function(event) {
event.preventDefault();
var postData = {
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
};
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData.$('input, select').serialize() ,
success: function(msg){
alert("submitted");
}
});
});
});
If I correctly understand your need, you want to transmit the content of your rows, each in the form showed in your current postData.
So this can be made at once for all rows (instead of ajaxing successively each of them).
It might be something like this:
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
event.preventDefault();
var postData = [];
$('#notSoCoolGrid > tr').each(function(event) {
postData.push(
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
);
});
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData,
success: function(msg){
alert("submitted");
}
});
});
});
Note that I choosed (the simplest way, IMO) to make a simple array of rows, where each one is an object like you already structured them.
Last point: I notice you specified async: false.
I don't know why you did that, and so I kept it unchanged.
But note that it's not recommended, and is being on the road to become deprecated.
I finally was able to solve this issue,for that I want to post my answer it might be helpful for someone out there.My previous code was submitting a form before even ajax call being triggered and I have to use Classes instead of IDs to identify my rows.I had to change the code completely to be able to submit the form
$('#btn').click(function(e) {
e.preventDefault();
$('#notSoCoolGrid tr').each(function(i, tr) {
var postData = {
paymentId : $('.paymentId', tr).val(),
id : $('.deald', tr).val(),
pType:$('.pType', tr).val(),
pAmt:$('.pAmt',tr).val(),
currency:$('.currency',tr).val(),
pInvDate:$('.pInvDate',tr).val(),
pRecDate:$('.pRecDate',tr).val(),
comments:$('.comments',tr).val()
}
$.ajax({
async: false,
type: "post",
url: "/update_deal_pmt_script.jsp",
data: postData
})
.done(function(response) {
console.log(response);
})
.fail(function(x, status, error) {
alert("Error: " + error);
});
});
});
I am trying to call MVC Controller from jquery but not able to place the call. Is there any problem in below code
Please figure out that if any problem and also I am not getting any error.
url="http://localhost:49917/Account/SaveAddress"
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
return 0;
};
public async Task<ActionResult> SaveAddress(AddressListViewModel addressListVM)
{
bool response;
string message;
if (addressListVM.ID <= 0)
{
response = await Task.Run(() => AccountManager.Instance().AddAddress(addressListVM));
message = response ? "New address added successfully." : "Failed to add new address.";
}
else
{
response = await Task.Run(() => AccountManager.Instance().UpdateAddress(addressListVM));
message = response ? "Selected address updated successfully." : "Failed to update selected address.";
}
ModelState.Clear();
return Json(new { responsestatus = response, message = message }, JsonRequestBehavior.AllowGet);
//return PartialView("_AddressDetail", BuildAddressListEntity(
// UserManager.FindById(User.Identity.GetUserId()), response, message, addressListVM.ID, true));
}
Yes, you are missing a closing bracket at the end of the this.saveaddress function
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
after all of that .. you need one more closing bracket:
}
;)
What does the console display? If you are using Chrome then right-click, choose Inspect, and find the Console tab. If you are calling the AJAX function correctly then something must be displayed in this Console tab which will probably lead you in the right direction better than I could with the information I have.
Put a breakpoint in your success and error functions. If it hits the error function then the issue is either that the controller action was not found or that the data is not valid json (either the post data or return data). You should add the errorThrown parameter to the error function so you can easily see what the issue is. You also do not need to stringify the data if it is already valid json, but if it is a string representing json data, you will need to use json.parse (sorry for the incorrect case).
In my project, I am trying to create a autocomplete effect using the following plugin:
Devbridge jQuery Autocomplete
This plugin is working fine until I don't add space into my textbox (after adding a word). and when I just delete the entered word using backspace then the autocomplete is showing the previous list which should have shown before.
PS: Every time I am passing the full text of the text field to server through ajax call which is necessary in my application.
Here is my code:
JS Fiddle (not working because of ajax url)
JS
$(function () {
var result = $('#result');
var contents = {
value: "",
data: ""
};
/* Ajax call */
result.keydown(function (event) {
if (!event.shiftKey) {
var sugData;
var text = result.val(); //.split(" ").pop();
//console.log(text);
/* Send the data using post and put the results in a div */
$.ajax({
url: "http://localhost:9999/projects/1/autocomplete/suggestions",
type: "POST",
data: "drqlFragment=" + text, // + " ",
//data: "drqlFragment=when node_database_property ",
async: false,
cache: false,
headers: {
accept: "application/json",
contentType: "application/x-www-form-urlencoded"
},
contentType: "application/x-www-form-urlencoded",
processData: true,
success: function (data, textStatus, jqXHR) {
var resData = data.suggestions;
//console.dir(resData);
for (var i = 0; i < resData.length; i++) {
resData[i].value = resData[i].keyword;
}
sugData = resData;
//console.dir(sugData);
},
error: function (response) {
//console.dir(response);
$("#result").val('there is error while submit');
}
});
console.dir(sugData);
$('#result').autocomplete({
lookup: sugData
});
}
});
});
HTML
<form id="foo">
<textarea id="result" rows="4" cols="50"></textarea>
<input type="submit" value="Send" />
</form>
Sorry, I can't provide you the json data because it is being modified by the server whenever I press a key. (So, actually it is an object variable returning by the server on ajax call).