Finding a circular object in the code - javascript

I am writing a script using jQuery for loading some content into my page.
At runtime nothing happens. I get this error when inspecting Firebug console:
TypeError: cyclic object value
data: JSON.stringify({ columnName: _columnName })
Here is the code (placed inside <Head>):
<Script>
function changeContent(_columnName) {
$.ajax({
type: 'POST',
url: '#Url.Action("GetContent")',
data: JSON.stringify({ columnName: _columnName }),
dataType: 'json',
contentType: "application/json; charset=utf-8"
}).done(function (resp) {
CKEDITOR.instances.text.setData(resp.Text);
}).fail(function () {
alert("Error");
});
}
$(function () {
$("#side-content").bind('click', { a: "side" }, changeContent);
});
</Script>
I used the tip here: Detecting and fixing circular references in JavaScript but could not find any circular relations!!!
Any point on saving my life would be so greatly appreciated.
- Kamran

Problem solved and well understood
The main part of the problem was I did not know that the argument of the handler is DOM event. I thought that _columnName will receive event data which was wrong. It is DOM event in fact.
The working code follows:
<script>
function changeContent(event) {
$.ajax({
type: 'POST',
url: '#Url.Action("GetHomeColumnContent")',
data: JSON.stringify({ columnName: event.data.a }),
dataType: 'json',
contentType: "application/json; charset=utf-8"
}).done(function (resp) {
CKEDITOR.instances.text.setData(resp.Text);
}).fail(function () {
alert("Error");
});
}
$(function () {
$("#side-content").bind('click', { a: 'side' }, changeContent);
});
</script>
And about the cyclic value: DOM elements are cyclic in nature because every DOM element has a reference to its parent, and in turn every parent has references to its children, so a cyclic structure.
Thanks to all friends for their times: #Dogbert, #nnnnnn, #AD7six, #Xotic750 ;-)

Related

Firebase Creating Dynamic Links with the REST API call using Javascript giving 400

I am trying to create Firebase Dynamic Links with REST API using simple Javascript ajax code, but every time I am getting 400 bad request, though I have tried and implemented the documentation described at https://firebase.google.com/docs/dynamic-links/create-links. I couldn't find any solution for this.
Whats wrong I am doing here please help.
Here is my code
<!DOCTYPE html>
Change Content
<script>
function loadDoc() {
var params = {
longDynamicLink:
"https://thepary.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
dynamicLinkInfo: {
domainUriPrefix: "https://thepary.page.link",
link: `https://threads-1511.web.app/threads/`,
iosInfo: {
iosBundleId: "com.bundleId",
iosAppStoreId: "1512677811",
iosIpadBundleId: "com.bundleId",
},
androidInfo: {
androidPackageName: "com.bundleId",
},
socialMetaTagInfo: {
socialTitle: `A thread by s`,
socialDescription: `s`,
socialImageLink:
"https://firebasestorage.googleapis.com/v0/b/threads-1511.appspot.com/o/playstore.png?alt=media&token=896f4fe6-2882-442e-b15c-3767d61b8a70",
},
},
suffix: {
option: "SHORT",
},
};
$.ajax({
url:
"https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[APIKEY]",
type: "POST",
data: params,
dataType: "json",
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
},
});
}
</script>
Since API expects contentType: "application/json",
You need to data: JSON.stringify(params)

AJAX function inside $.extend not working in jQuery 3

I need to extends jQuery (as a plugin). Problem is, $.ajax is not working inside the $.extend scope but outside the scope it is working fine. I am using jQuery 3.4.1 in my project.
My code:
(function($) {
jQuery.extend({
mmw: function(options) {
var settings = $.extend({
mtarget: "#cnapp-mmw",
imgSize: "square",
imgRestricted: true,
imgtype: ["gif", "png", "jpg", "jpeg", "pdf"]
}, options);
$.ajax({
type: "GET",
url: "http://example.com/public/get-media",
dataType: "html",
success: function(data) {
alert(data);
},
error: function(e) {
alert(e); // Showing this as outout [object Object]
}
});
}
})
})
But this is showing the proper output:
(function($) {
$.ajax({
type: "GET",
url: "http://example.com/public/get-media",
dataType: "html",
success: function(data) {
alert(data); // This is showing the proper output
},
error: function(e) {
alert(e);
}
});
jQuery.extend({
mmw: function(options) {
var settings = $.extend({
mtarget: "#cnapp-mmw",
imgSize: "square",
imgRestricted: true,
imgtype: ["gif", "png", "jpg", "jpeg", "pdf"]
}, options);
}
})
})
What is wrong in my first code? Is there anything different in jQuery 3?
Please note, I need to call this plugin without selector like
$(".trigger").on('click', function(){
$.mmw();
});
Is the $.extend is a must required function to do so? Any advice on the best practice for this would be gratefully received.
UPDATE
After debugging many times I have found that, the AJAX request is not working inside any block or event. I am using this with Codeigniter 4 (beta 4).
This is showing error
$(".trigger").on('click', function(){
$.ajax({
type: "GET",
url: "http://example.com/public/get-media",
dataType: "html",
success: function(data){ alert("Ok"); },
error: function(e){ alert(JSON.stringify(e)); } // Showing error message {"readyState":0,"status":0,"statusText":"TypeError: Cannot read property 'open' of undefined"}
});
});
But this showing the correct data
$.ajax({
type: "GET",
url: "<?=base_url('test/'.session_id())?>",
dataType: "html",
success: function(data){ alert(data); }, // Showing the Data
error: function(e){ alert(JSON.stringify(e)); }
});
$(".trigger").on('click', function(){
});
Means Ajax function is only working outside the scope. Really confused about it.
As I am working with CI 4 (beta 4), there was a conflict between above code and the Javascript that has been used by CI 4 for debugging tools. The error is only generated in "development" environment. In "production" environment, everything on working fine.

Dynamically loaded partial view dynamically load another partial [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
Just wondering if this is even possible.
I am making a store web application in asp.net MVC 4 i guess.
And my articles have a category and a sub category.
So I got this code which I can't make to work.
Script:
$("#ManageCategories").click(function (e) {
$.ajax({
type: "GET",
url: "Acp/LoadManageCategories",
success: function (response) {
$("#main-acp-display").html(response);
},
error: function () {
alert("Error!");
}
});
});
$(".get-subcategories").click(function () {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: $(this).attr("id") },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
});
(the first part works like a charm)
Controler:
[CustomAuthorize(Roles.Admin)]
public ActionResult LoadManageCategories()
{
IEnumerable<CategoryModel> model = _categoryManager.GetAll().Select(x => (CategoryModel)x);
return PartialView("Partial/_LoadManageCategories", model);
}
[CustomAuthorize(Roles.Admin)]
public ActionResult LoadManageSubCategories(string subCategoryId)
{
int id = Convert.ToInt32(subCategoryId);
IEnumerable<SubCategoryModel> model = _categoryManager.GetAllSubCategoriesByCategoryId(id).Select(x => (SubCategoryModel)x);
return PartialView("Partial/_LoadManageSubCategories", model);
}
Now you see the first level code works. When I click a div on index it loads all categories. But the other function wont load unless I place the clickable div on index page too and I wanted it to be a part of first partial view.
So it should be Button(click) > Shows all categories(click any) > Loads subcategories.
Is this even possible?
Offtopic: Does MVC work only on one level? Cause I remember trying to have a Model with List of other models inside of it and inside this list there was another model and it wasn't so good xD (Managed to find simpler solution, but this is where I got the mvc one level only thought)
Update:
So #bigless had an idea to make this a function so here it is so far:
function createSubcategories(id) {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: id },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
};
And calling it by:
<button onclick="createSubcategories(1)"><i class="fas fa-angle-double-right main-cat-icon"></i></button>
Current error:
Uncaught ReferenceError: createSubcategories is not defined
at HTMLButtonElement.onclick (Acp:89)
You can not attach event listener to DOM element(.get-subcategories) that does not exist yet. Try something like $(document).on('click', '.get-subcategories', function() { .. or:
$("#ManageCategories").click(function (e) {
$.ajax({
type: "GET",
url: "Acp/LoadManageCategories",
success: function (response) {
$("#main-acp-display").html(response).ready(function() {
$(".get-subcategories").click(createSubcategories);
});
},
error: function () {
alert("Error!");
}
});
});
function createSubcategories() {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: $(this).attr("id") },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
};

IE 9, 10, 11 - Ajax calls not returning

I am having an issue with IE related to jQuery and ajax. Chrome and Firefox work just fine, but my ajax calls are disappearing in IE.
After making the ajax call, neither the success nor the fail functions are being called. I can see the response in the IE console, and I know my controller action is being hit.
$.ajax({
url: controllerUrl
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});
Has anyone else seen this issue?
fail: function () {
alert('failed!');
}
fail is not a valid jQuery ajax setting. I believe you are looking for error.
Also, cache: false, does nothing with POST requests.
Note, jQuery does not append the time stamp with POST requests.
The source code clearly demonstrates this. (summarized from https://github.com/jquery/jquery/blob/master/src/ajax.js)
var rnoContent = /^(?:GET|HEAD)$/;
s.hasContent = !rnoContent.test( s.type );
if ( !s.hasContent ) {
/* code to append time stamp */
}
You are missing a comma , after your URL parameter:
$.ajax({
url: controllerUrl, // <--- you were missing this comma!
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});

Event Handlers in a JavaScript "class"

I am working at fully understanding class definitions in JavaScript. Currently, I have a class defined like the following:
function Item() { this.init(); }
Item.prototype = {
init: function () {
this.data = {
id: 0,
name: "",
description: ""
}
},
save: function() {
$.ajax({
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json",
success: save_Succeeded,
error: save_Failed
});
}
}
My problem is, I'm not sure how, or where, to define my save_Succeeded and save_Failed event handlers. Can someone please help me out? Thank you!
Add a context: to your $.ajax call pointing to this so that the correct object is passed as this when the handlers are called.
Something like:
save: function() {
$.ajax({
context: this,
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json",
success: this.save_Succeeded,
error: this.save_Failed
});
(assuming that you also put save_Succeeded and save_Failed into the prototype)
}

Categories