JQuery Illegal invocation when using variable to select - javascript

My javascript dont seem to like the var divTag = '#' + ratinglistid + " > select[name=SelectedValue] > option:selected";
I couldn't find the answer searching.. Sorry for the messed up formatting, couldn't get it to go away.
Script:
<script>
function doSubmit(form, myRating, ratinglistid){
var divTag = '#' + ratinglistid + " > select[name=SelectedValue] > option:selected";
var ratingValue = $(divTag);
$.ajax({
type: "GET",
url: "/RatingLists/Done",
data: ({
myrating: ratingValue,
myRatingListId: ratinglistid
}),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
</script>
Html I want to get value from:
<div id='2'>
<input type="hidden" name="RatingListId" value="2"/>
<select id="SelectedValue" name="SelectedValue" onchange="doSubmit($(this).parents('form'),2);"><option value="1">Inget intresse, tas bort</option>
<option value="2">Svagt intresse, sparas</option>
<option selected="selected" value="3">Intresserad-ingen kontakt än</option>
<option value="4">4-Intreserad-vill ha kontakt</option>
<option value="5">5-Vill byta!</option>
<option value="100">6-Avvaktar värdar</option>
</select>
</div

You are trying to pass a jQuery object to be serialized in the ajax function which causes the Illegal invocation error, use the .val() to get the value of the form element.
data: ({
myrating: ratingValue.val(),
myRatingListId: ratinglistid
}),

It could not evaluate inside get call so I had to do it like this:
var divTag = '#' + ratinglistid + " > select[name=SelectedValue] > option:selected";
var ratingValue = $(divTag).val();
$.ajax({
type: "GET",
url: "/RatingLists/Done",
data: ({
myrating: ratingValue,
RatingListId: ratinglistid
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(ratinglistid),
error: function () {
var id = ratinglistid;
$('#' + id + "tbody td").hover(function () {
$(this).parents('tr').addClass('highlight');
}, function () {
$(this).parents('tr').removeClass('highlight');
});
}
});

Related

ASP.NET MVC - After HTML append with Jquery the DropDownList value comes as undefined

I have two dropdownlist and when I change the value of the first one with refreshes the value of the second one with the following code:
function FillBooks(val) {
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$("#DDL_TIPO").empty();
$.ajax({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: "POST",
dataType: "JSON",
data: { value: CategoryId },
success: function (data) {
var markup = "<option value='0'>Selecione um Tipo</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].value + ">" + data[x].Text + "</option>";
}
$("#DDL_TIPO").html(markup).show();
}
});
}
P.S - The data comes from the controller which is not relevant for the exemple that I am showing.
After this when I try to get the value of the Second dropdownlist it comes as undefined.
I tested before this jquery code and it gives me the value of the dropdownlist, it just doesn't give when I get this function to work on it.
Try this:
<script>
function FillBooks(val)
{
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$.ajax
({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: { value: CategoryId },
success: function(result)
{
$("#DDL_TIPO").html("");
$.each($.parseJSON(result), function(i, tipo)
{
$("#DDL_TIPO").append($('<option</option>').val(tipo.Value).html(tipo.Text))
})
},
error: function()
{
alert("Whooaaa! Something went wrong..")
},
});
}
</script>

Javascript SyntaxError: missing

I'm trying to put 2 scripts in 1 js file and i'm getting:
SyntaxError: missing } after property list
note: { opened at line 9, column 19
But as far as I check all the curly brackets are closed, not sure what the real issue is.
Code
// country
jQuery( document ).ready( function( $ ) {
$('select[name="country"]').on('change', function() {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var CountryId = $(this).val();
if(CountryId) {
$.ajax({
url: '{{ url('getprovinces') }}/'+encodeURI(CountryId),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="province"]').empty();
var options = data.map(function(state) {
return $("<option class='form-control'>").val(state.id)
.text(state.name);
});
$('select[name="province"]').empty().append(options);
}
});
}else{
$('select[name="province"]').empty().append("<option class='form-control' value='' selected>Select</option>");
}
});
});
error comes from this line:
url: '{{ url('getprovinces') }}/'+encodeURI(CountryId),
Any idea?
You need to escape the quotes or use a double-quoted string. Otherwise JS thinks the string ends on the quote after url(' then gets confused when a variable name pops up.
Try like that:
// country
jQuery( document ).ready( function( $ ) {
$('select[name="country"]').on('change', function() {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var CountryId = $(this).val();
if(CountryId) {
$.ajax({
url: '{{' + url('getprovinces') + '}}/' + encodeURI(CountryId),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="province"]').empty();
var options = data.map(function(state) {
return $("<option class='form-control'>").val(state.id)
.text(state.name);
});
$('select[name="province"]').empty().append(options);
}
});
}else{
$('select[name="province"]').empty().append("<option class='form-control' value='' selected>Select</option>");
}
});
});
Try
url: url('getprovinces') + '/' + encodeURI(CountryId),

Javascript: How to get id of div from dynamically added tab and call a function with that?

I've got a webpage on which I can dynamically create new tabs in which a chat with a selected user is/should be initiated. I wrote and tested the chat-script on itself, which works perfectly well and I now need to integrate it with the tabs.
So I've got this function which adds a new tab. In this function I set the tab-pane id to the user_id:
function addTab(user_id, name) {
$('#pageTab').append(
$('<li><a href="#' + user_id + '">' + name +
'<button class="close" type="button">×</button></a></li>'));
$('#pageTabContent').append($('<div class="tab-pane" id="' + user_id
+'"><form id="send_message_form"><textarea id="messageText" rows="1" cols="25"></textarea></br>'
+ '<input type="button" id="sendButton" value="Send Message"></form>'
+ '<div class="conversation"></div></div>'));
$('#page' + user_id).tab('show');
}
I then also have a function which updates the chat within this tab. In here I need the user_id (from the tab-pane):
// Poll for new messages
function updateConversation(){
$.ajax({
type:"POST",
contentType: "application/json",
accepts: "application/json; charset=utf-8",
url: "/api/support/{{ supporter_id }}",
data: JSON.stringify({
'action': 'GET_MESSAGES',
'user_id': user_id,
'last_message_id':last_message_id
}),
dataType: "json",
success: function(data) {
if (data.messages.length > 0){
for (var i=0; i<data.messages.length; i++){
$(".conversation").prepend("<P>"+ data.messages[i].text + "</p>");
last_message_id = data.messages[i].id;
}
}
}
});
setTimeout(updateConversation, 1000);
}
So my question is: how would I be able to get the id from the tab-pane that is selected, and then pass it to the updateConversation() function?
I'm kinda lost here, so all tips are welcome!
This should do what you need...
// Poll for new messages
function updateConversation(){
$.ajax({
type:"POST",
contentType: "application/json",
accepts: "application/json; charset=utf-8",
url: "/api/support/{{ supporter_id }}",
data: JSON.stringify({
'action': 'GET_MESSAGES',
'user_id': $(".tab-pane:visible")[0].id,
'last_message_id':last_message_id
}),
dataType: "json",
success: function(data) {
if (data.messages.length > 0){
for (var i=0; i<data.messages.length; i++){
$(".conversation")
.prepend("<p>"+ data.messages[i].text + "</p>")
.data("last-message-id", data.messages[i].id);
}
}
}
});
setTimeout(updateConversation, 1000);
}
I've changed the variable user_id to this...
$("div.tab-pane:visible")[0].id
That gets the id of the visible div with class tab-pane and uses it as the user_id variable in the data object you send via your ajax call.
I've also modified it to save the message ID as a data attribute on the conversation list, so to get the ID of the last message for the visible tab, you could use...
var lastMessageID = $(".tab-pane:visible .conversation").data("last-message-id");

Facing error while populating dynamic dropdown

m trying to add some <option> in existing <select> dynamically, but facing error "An attempt was made to reference a Node in a context where it does not exist." i have tried to resolve it failed...
HTML code:
<label class="control-label" for="selectError">Ayat/Hadith no.:</label>
<div class="controls">
<select id="ayat_selector" disabled >
<option id="all_ayat" selected>All </option>
</select>
</div>
javascript :
var selectHTML = "<option id='200'>Select Surah</option>";
alert("ajax going ");
$.ajax({
url: "../Surah_CRUD/Load_Surahs",
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: '',
success: function (result) {
var mera_obj = result.key;
for (var i = 0; i < 5; i++) {
selectHTML += "<option id='" + i + "'>" + mera_obj[i].Surah_Description + "</option>";
}
var qa = document.getElementById('ayat_selector');
qa.appendChild(selectHTML);
alert("done"+qa.className);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("3> " + thrownError);
},
});
The problem is that you trying to select an element by id that isn't exist.
try to change this:
var qa = document.getElementById('surah_selector');
to this:
var qa = document.getElementById('ayat_selector');
UPDATE
try to change this
var qa = document.getElementById('ayat_selector');
qa.appendChild(selectHTML);
alert("done"+qa.className);
With this code in jQuery:
$('#ayat_selector').append(selectHTML);
alert('done');

Can I use a concatenated string for the url in my .ajax() request

I'm doing cross-domain requests and once the first request is made I need to retrieve the ID (and do some other stuff) and then use the ID for the next request.
So far the hang-up is that the next request doesn't like the concatenation. Here's my code, and yes I know document.write should be changed to console.log() however console.log doesn't work and I was probably going to ask that question after get help with my current problem. the problem starts at the second .ajax() request.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// First link out of three
var url = 'https://www.sciencebase.gov/catalo
/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
for (var i = 36; i < 37; i++) {
document.write(json.items[i].id);
var urlId = json.items[i].id;
}
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/" + urlId
+"?format=json&max=10';
$.ajax({
type: 'GET',
url: deferUrl,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
// Get the next id to use for the next url
document.write(deferUrl);
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog
/item/4f4e4b19e4b07f02db6a7f04?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
document.write(json.title);
},
error: function(e) {
console.log(e.message);
}
});
},
error: function(e) {
console.log(e.message);
}
});
},
error: function(e) {
console.log(e.message);
}
});
});
</script>
</head>
<body>
</body>
</html>
Thanks for the help
'https://www.sciencebase.gov/catalog/itemLink/" + urlId
+"?format=json&max=10';
should be
'https://www.sciencebase.gov/catalog/itemLink/' + urlId
+'?format=json&max=10';
You mix simples and doubles quotes. use 'srting' + var + 'string' or "string" + var + "string" but don't mix them
To address your concatenation issue only.. you have a mix of single and double quotes there. They should all be consistent.
ex:
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/' + urlId + '?format=json&max=10';
I made a slight change from
for (var i = 36; i < 37; i++) {
var urlId = json.items[i].id;
}
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/' +
urlId + '?format=jsonp&max=10';
$.ajax({
type: 'GET',
url: deferUrl,
jsonpCallback: 'getSBJSON',
contentType: 'application/json',
dataType: 'jsonp',
to
for (var i = 36; i < 37; i++) {
var urlId = json.items[i].id;
}
var deferUrl = urlId;
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' +
deferUrl + '?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: 'application/json',
dataType: 'jsonp',
and that seemed to do the trick. It didn't like having the concatenation done completely before assigning it to the url.

Categories

Resources