Only add data to ajax call if it isnt a null value - javascript

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks

You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

Related

How to stop function if input is invalid?

I'm trying to get a value of several URL input and if value of URL isn't not valid, I just want to animate input element and stop everything.
Is there any way to do it?
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
});
You need to let outside of your each loop know the condition of the contents.
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var blnIsValid = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
// Input isn't valid so stop the code
blnIsValid = false;
return false; // Alternatively don't stop so that any other invalid inputs are marked
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
// Check to make sure input is valid before making ajax call
if (blnIsValid) {
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});
One method is you can use flag to check and execute the Ajax method
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var callAjax = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
callAjax = false;
return false;
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
if(callAjax)
{
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});

unable to post id of selected dropdown to controller through knockout function

This is my Post function something like this:
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.NeighbourhoodId = data.id || "";
This is my simple function in knockout. Here at the last line u can see, data: ko.toJson(post)
self.addPost = function () {
var post = new Post();
post.Message(self.newMessage());
return $.ajax({
url: postApiUrl,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: ko.toJSON(post)
})
.done(function (result) {
self.posts.splice(0, 0, new Post(result));
self.newMessage('');
})
.fail(function () {
error('unable to add post');
});
}
Now, along with this, i want to pass dropdown selected id something like this:
data: { id: $("#Locations").val() }
Right now, i have tried using this:
data:{post: ko.toJSON(post), id: $("#Locations").val() }
but in controller, post: ko.toJSon(post) is sending nothing however i am getting id of selected dropdown but not the message property of post parameter.
If i use this line:
data: ko.toJSON(post)
then i can get every property of post parameter but then id is null so, how to deal with this.Plzz Plzz help me out.Debugger is showing nothing useful information.My Post Controller is:
public JsonResult PostPost(Post post, int? id)
{
post.PostedBy = User.Identity.GetUserId<int>();
post.NeighbourhoodId = id;
db.Posts.Add(post);
db.SaveChanges();
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
NeighbourhoodId = post.NeighbourhoodId
};
return Json( ret,JsonRequestBehavior.AllowGet);
}
on my view page,this is the button on which click event i fired addPost function
<input type="button" data-url="/Wall/SavePost" id="btnShare" value="Share" data-bind="click: addPost">
along with this, dropdown for sending id is something like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
<script type="text/javascript">
$(document).ready(function () {
$("#btnShare").click(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("PostPost", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
Plzz someone help me out.I am not getting what to do from here.

Fetch contenteditable=true data

I want to fetch data from div tag which set contenteditable=true
I have used autosuggestion in that..Data is successfully fetched but when I write item which is written in autosuggestion field then it wont be fetched because it add HTML tag and it wont save into database
My code
if data is changed:
var timeoutID;
$('[contenteditable]').bind('DOMCharacterDataModified', function () {
clearTimeout(timeoutID);
$that = $(this);
timeoutID = setTimeout(function () {
$that.trigger('change')
}, 50)
});
$('[contentEditable]').bind('change', function () {
getTextChangeContent();
});
UPDATE
function getTextChangeContent() {
var ma = document.getElementById('myAudio');
var remove = ma.src.slice(0, -4);
var path = remove.substring(remove.lastIndexOf("/") + 1);
var newPath = path.concat('.wav');
var text_id = document.getElementById('textbox');
var textdata = text_id.innerHTML;
$.ajax(
{
type: "POST",
url: '#Url.Action("getChangeContent")',
dataType: "json",
mtype: "post",
data: { arg: varid, content: textdata, path: newPath },
async: true,
success: function (data) {
alert(data + " DATA");
}
});
}
when I changed data and use autosuggestion then it will show data as
The door is blacl <span class="atwho-inserted">[[Ceilings]]</span>
How to ignore html tag and take only values of that?
Plz suggest me
Retrieve innerText rather than innerHTML in order to ignore the HTML content. If you want only the content inside the html tag with class .atwho-inserted, then retrieve only that content.
var textdata = text_id.innerText;

Reading data from table (HTML, JAVAscript)

I have this table that receive from the server:
(with ajax):
$.each(data, function(i, item) {
$('#MyTable tbody').append("<tr>"d
+"<td>" +data[i].A+ "</td><td>"
+data[i].B
+"</td><td><input type='text' value='"
+data[i].C+"'/></td><td><input type='text' value='"
+ data[i].D+"'/></td>"
+ "</tr>");
});
C and D are edit text, that the user can change. after the changing by the user I want to "take" the all new data from the table and send it by ajax with JSON.
how can I read the data to a JSON?
I start to write one but I am stuck on:
function saveNewData(){
var newData= ...
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
thank you
Try something like this,
function getUserData()
{
var newData = new Array();
$.each($('#MyTable tbody tr'),function(key,val){
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
//if you want to add A and B, then add followings as well
fileldValues['a'] = $($(this).children()[0]).text();
fileldValues['b'] = $($(this).children()[1]).text();
newData.push(fileldValues);
});
return JSON.stringify(newData);
}
function saveNewData(){
var newData = getUserData();
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
http://jsfiddle.net/yGXYh/1/
small demo based on answer from Nishan:
var newData = new Array();
$.each($('#MyTable tbody tr'), function (key, val) {
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
newData.push(fileldValues);
});
alert(JSON.stringify(newData));
use the jquery on event binding
try somthing like this. Fiddler Demo
$('#MyTable').on('keyup', 'tr', function(){
var $this = $(this);
var dataA = $this.find('td:nth-child(1)').text() // to get the value of A
var dataB = $this.find('td:nth-child(2)').text() // to get the value of B
var dataC = $this.find('td:nth-child(3)').find('input').val() // to get the value of C
var dataD = $this.find('td:nth-child(4)').find('input').val() // to get the Valur of D
// $.ajax POST to the server form here
// this way you only posting one row to the server at the time
});
I don't normaly do that I would use a data binding libarray such as Knockoutjs or AngularJS

Data variable in jquery ajax function

I'm trying to use the code below, but it's not working:
UPDATED WORKING:
$(document).ready(function() {
$('.infor').click(function () {
var datasend = $(this).html();
$.ajax({
type: 'POST',
url: 'http://domain.com/page.php',
data: 'im_id='+datasend',
success: function(data){
$('#test_holder').html(data);
}
});
});
});
As you can see I used $datasend as the var to send but it doesn't return the value of it, only its name.
I would change
$datasend = $(this).html;
to
var datasend = $(this).html();
Next I would change
data: 'im_id=$datasend',
to
data: 'im_id='+datasend,

Categories