Unable to understand string escaping from onclick method - javascript

I have a method defined as below :
function updateManagerPreferences(companyId, managerId, userId) {
console.log('inside method');
$.ajax({
type: 'GET',
url: admin_url + "/updatemanager/" + companyId + "/"
+ managerId + "/" + userId,
encode: false,
crossDomain: true
}).done(function (tresult) {
var success_result = jQuery.parseJSON(JSON.stringify(tresult));
console.log(success_result);
});
}
It takes 3 parameters from a button onclick and I am trying to call the method as follows :
<input type='button' class='btn btn-sm btn-success' value='Update' onclick='updateManagerPreferences(" + companyId + "," + $('#managerDropDown').val() + "," + result.ResponseMessage.users[i].user_id + ");'/>
I refered all the similar stackoverflow answers but none of them have helped.
Can someone please tell where am I going wrong ?

You can solve by getting directly your value from inside function and element value by jQuery .
<input type='button' class='btn btn-sm btn-success' value='Update' id='updatemanager' />
<script>
$("#updatemanager").on("click",function(){
var managerId = $('#managerDropDown').val();
var userId = result.ResponseMessage.users[i].user_id;
$.ajax({
type: 'GET',
url: admin_url + "/updatemanager/" + companyId + "/"
+ managerId + "/" + userId,
encode: false,
crossDomain: true
}).done(function (tresult) {
var success_result = jQuery.parseJSON(JSON.stringify(tresult));
console.log(success_result);
});
});
</script>

Related

how to sent a text to a specified email address when pressing a button html and javascript

function sendEmailToUser(){
var msgTo = "cigma#gmail.com";
var msgFrom = "drrama#gmail.com";
var messageBody = " Your code is 1234567";
var msgSubject = "CODE";
$.ajax({
type: "POST",
url: "/services/Mail.asmx/SendMail",
cache: false,
contentType: "application/json; charset=utf-8",
data: "{ 'body':'" + messageBody + "'," +
"'to': '" + msgTo + "'," +
"'from': '" + msgFrom + "'," +
"'subject': " + msgSubject + "'" +
"}",
dataType: "json",
complete: function (transport) { if (transport.status == 200) $("#formcontainer").html("Success"); else alert("Please try again later"); }
});
}
This is my function in javascript code that is called when ever a button is clicked, so as to sent text to the specified email address as shown in the code, but the function always returns "Please try again later" as a error message. It does not sent a text to cigma#gmail.com

Address a specific looped input with jQuery ajax

I have HTML code looped with another jQuery. There is an input which looped too. I want to address it in jQuery Ajax... but only the first input works... and the same values are printed for the rest in the console.
success: function (r) {
var posts = JSON.parse(r)
$.each(posts, function (index) {
$('.timelineposts').html(
$('.timelineposts').html() + '<blockquote><p>' + posts[index].PostBody + '</p><footer>Posted by ' + posts[index].PostedBy + ' on ' + posts[index].PostDate + '<button class="btn btn-default" data-id="' + posts[index].PostId + '" type="button" style="color:#eb3b60;background-image:url("none");background-color:transparent;"> <i class="glyphicon glyphicon-heart" data-aos="flip-right"></i><span> ' + posts[index].Likes + ' Likes</span></button><button class="btn btn-default comment" type="button" data-postid="' + posts[index].PostId + '" style="color:#eb3b60;background-image:url("none");background-color:transparent;"><i class="glyphicon glyphicon-flash" style="color:#f9d616;"></i><span style="color:#f9d616;"> Comments</span></button></footer><input type="text" class="c"><button comment-postid="' + posts[index].PostId + '">comment</button></blockquote>'
)
/////////////////////ajax/////////////////////////
$('[comment-postid]').click(function () {
var buttonid = $(this).attr('comment-postid');
var value = $('.c').val();
$.ajax({
type: "POST",
url: "api/comments1?id=" + buttonid,
processData: false,
contentType: "application/json",
data: '{ "commentBody": "' + value + '"}',
success: function (r) {
//var res = JSON.parse(r)
console.log(buttonid);
console.log(value);
value = "";
buttonid = "";
},
error: function (r) {
console.log("ddd")
}
});
})
})
I have figured it out!
I named each class with a different postid value...so when the loop iterates, each post will have anew class, so I address it in the ajax!
<input type="text" class="'+posts[index].PostId+'" >
and in ajax: var buttonid = $(this).attr('comment-postid');
var v=$('.'+buttonid).val();

Send to database using ASP.NET, c# and jQuery

New to AJAX here.
Been trying to send to my database using AJAX but is is not working.
In my aspx.cs:
[WebMethod]
public static void saveMsg(string roomCode, string userName, string msg)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LBConnectionString"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT into chatTable(roomCode, uName, msg) VALUES (" + roomCode + ", '" + userName + "', + '" + msg + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
I am trying to insert data using AJAX and C# ASP.NET.
This is my aspx file
$.ajax({
type:'POST',
contectType: "application/json; charset=utf-8",
dataType: "json",
url:"Room.aspx?Board='" + roomCode + "'",
data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
})
The full url is http://localhost:1759/Room?Board='//roomcode'.
Is there anything that went wrong? Like how I put the url into the AJAX function?
Thanks in advance!
EDIT:
Is it needed to put data type as JSON? New to JSON too...
Try this code :
Javascript :
function Getpath() {
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
var Domainpath = window.location.origin + "/";
if (Domainpath.indexOf("localhost") == -1) {
return Domainpath;
}
else {
return Domainpath;
}
}
Ajax:
You will get the path in Getpath() Method.
var path = Getpath();
$.ajax({
type:'POST',
contectType: "application/json; charset=utf-8",
dataType: "json",
url: path +"Room.aspx?Board='" + roomCode + "'",
data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
})
You Need to Pass correct URL to call method.
$.ajax({
type:'POST',
contectType: "application/json; charset=utf-8",
dataType: "json",
url:"Room.aspx/saveMsg",
data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
})

.empty() function won't work after loading contents with ajax

I did a multilevel ajax call .i.e. make an ajax call and use the id value from the call to make another call... I tried calling a jquery .empty() isn't working for the data generated in the inner ajax call... But when i place the .empty() function on the outer generated element, it worked just fine... How can i fix this issue? This is my code../
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({ //first ajax call///
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output) {
if (output.result === 'success') {
$('.blog').empty();
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var storyTitle = this.story_view;
var frontTitle = '<div class="blog-item"><h3>' + storyTitle + '</h3>' + '<img class="img-responsive img-story" src="images/blog/blog1.jpg" width="100%" alt="" />' + '<div class="blog-content"><div class="entry-meta"><h4>Episodes</h4></div>' + '<div class="well" style="padding-right: 10px; padding-left: 5px; width: 105%;">' + '<ul class="tag-cloud stories">';
var request2 = $.ajax({ ////inner ajax call//////
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function(output2) {
var i = 1;
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
var title = this.title;
var count = this.episode_count;
if (count == 0) {
frontTitle += id2;
} else if (i % 20 == 0) {
frontTitle += '<li data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li></ul><ul class="tag-cloud">';
} else {
frontTitle += '<li style="margin: 1px" data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li>';
}
i += 1;
})
}
$('.blog').append(frontTitle);
frontTitle += '</ul></div></div>';
})
})
} else {
console.log('failed');
}
});
});
I really need help for this, i av been on this for two days now... I would really appreciate the help.. or is there a better way i could do this?

JQUERY fails to set parameter when currentRow.next().next() is not available

I have a jquery save function like this -
$(".SaveBtn").click(function () {
if ($("#Form1").valid()) {
var rowData = $("#TestTable").getRowData($(this).data("rowid"));
var currentRow = $(this).closest("tr");
var postData = {
testID: rowData.testID,
testNotes: currentRow.next().find(".NotesEntry").val(),
isActive: currentRow.next().next().find(".CheckEntry") == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
$.ajax({
type: "POST",
url: "../Services/test.asmx/UpdateTestRowData",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
$("#TestTable").setGridParam({ postData: { myID: $('#hfmyID').val() }, datatype: 'json' }).trigger("reloadGrid");
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
});
The problem is with this line -
isActive: currentRow.next().next() == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
When currentRow.next().next() is not available, the isActive is not set as "false" and is even not in the request body to web service.
Currently the request body is {"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST"}
I expect it to be -
{"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST", "isActive":"false"}
Why the "isActive" parameter is missed and how to make it available when currentRow.next().next() is not available?
Thanks
I fixed the problem by adding the else part in the following statement -
if (data.d.IsActived) {
output += "<td colspan='6' align=\"left\"><input type='checkbox' id='cbActive" + rowId + " checked" + " name='cbManualDeactive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
else {
output += "<td style=\"display:none;\"><input type='checkbox' id='cbActive" + rowId + " name='cbActive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
Thanks

Categories