I have a javascript function and when it is called I want to insert a partial into a div. All is working fine, but, when I want to pass some javascript into Html.Partial ViewDataDictionary, it isn't passing the rendered javascript.
<script>
function addExperience() {
#{var uid = #MvcHtmlString.Create("new Date().getTime()");}
console.info(#uid); //output ok !
var partialView = #(Html.Raw(JsonConvert.SerializeObject(Html.Partial("~/Views/Dashboard/_editUserExperience.cshtml", Model, new ViewDataDictionary { { "id", uid } }).ToString().Trim('"'))))
$("#newExperienceSection").append(partialView); //it renders "new Date().getTime(), not the number
}
</script>
Thank you !
If you call Jsonconvert.SerializeObject with a string (Html.Partial returns a string), it returns a string.
So you statement
var partialView = ... will be rendered as
var partialView = "the contents of the partial view";
That's why, when you do this:
$("#newExperienceSection").append(partialView);
it actually displays the javascript as text.
If you want to get a partial view to execute javascript, you can return javascript inside script tags, and as soon as you add that to the DOM it gets executed, for example if you set your _editUserExperience.cshtml as this:
<script>
alert('this gets executed as soon as you do add this to the DOM with the jQuery append command');
</script>
When you execute $("#newExperienceSection").append(partialView); you'll see the alert.
An easier way to insert a partial view is to take advantage of $.ajax, for example, in addExperience:
$.get('#Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) {
$("#newExperienceSection").html(theHtmlReturned);
});
($.get is just shorthand for $.ajax using a get request)
Source: http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.get/
http://api.jquery.com/category/deferred-object/
Related
I am using WordPress and I am trying to get and assign the value of a data attribute to a variable using JavaScript inside functions.php in my custom child theme.
The page renders the following body:
<body class="(...)" data-elementor-device-mode="desktop">
I have the following function:
var body = document.body;
console.log(body);
var bodyDevice = body.dataset.elementorDeviceMode;
console.log(bodyDevice);
The first console.log returns the body as expected, but the second console.log still returns "undefined".
It must be a syntax issue, since the following
var bodyDevice = body.clientWidth;
console.log(bodyDevice);
will return the current width of the body element (which solves my issue); anyway, why is
var bodyDevice = body.dataset.elementorDeviceMode;
console.log(bodyDevice);
not returning "desktop" value?
Elementor inserts the data set by JavaScript on its initialization, see line 271 : https://github.com/elementor/elementor/blob/master/assets/dev/js/frontend/frontend.js
Basically your code is returning nothing because it is executed before the Elementor has inserted the data set... So, there is no data-elementor-device-mode at the moment your code is executed.
Try to execute your code after the page loads using like:
window.onload = function() {
var bodyDevice = document.body.dataset.elementorDeviceMode;
console.log(bodyDevice);
};
I'm fetching value from mysql query result page.php into display.html. I'm able to show "VALUE368" value in display.html in div ID.
but I also want to log "VALUE386" in firebase realtime database, for that I'm trying with below code.
$(document).ready(function (){
function testing(){
return $('#VALUE368').load('data.php #VALUE368');
//return 100 + 300 ;
}
var tag1 = testing();
document.write(JSON.stringify(tag1));
console.log(tag1);
});
I also tried with
var tag1 = document.getElementById("VALUE386");
but it returns null value.
Please help me in that.
The issue is because load() returns a jQuery object which contains the #VALUE368 element. This is why you see [object Object] when you call stringify().
Aside from that, your logic is very odd. You're calling document.write (which itself is bad practice) in an attempt to write content to the DOM which load() will already have done for you.
You can simply change your code to this:
$(document).ready(function() {
$('#VALUE368').load('data.php #VALUE368');
});
I am new to AJAX and currently learning to use it with Spring MVC. I am facing issues on the same.
Before proceeding to the actual real time requirement that I am working on, I am testing out the whole AJAX+Spring MVC+jquery combination with something really basic to get my understanding right.
I am having a search box+'submit' button on a page. I am sending a hard coded text to the Spring controller on submit using $.get. Then I am sending another text from that controller back to the callback function and trying to display the returned text in the callback function using an 'alert' box. This doesn't seem to work.
I see that the call back function is being called(since the 'alert' inside the callback function is being fired) so I am kind of assuming that control is being transferred to the controller and back to the callback method but I am not able to figure out why the text that is returned from the controller is not showing up on the alert box in the call back method. Not sure what I am missing here to capture the return value in the call back method.
Your response and help on this is really appreciated.
Thanks.
HTML for text box and submit button:
<div class = "searchcontactform">
<form id = "searchcontactform" name="searchcontactform" method="GET">
<input type = 'text' size='25' name = "searchlastname" id = "searchlastname" value='Enter Last Name to Search'/>
<input type = "submit" value="Find">
</form>
</div>
JavaScript that triggers on submit of the above form:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/scripts/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function( ) {
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search", {textsent : 'Hello Controller'},callback);
function callback(textreceived){
alert('In Callback. Text Received is: '+textreceived);
};
});
});
Controller:
#RequestMapping(value = "/search", method = RequestMethod.GET)
public #ResponseBody String searchcontact(#RequestParam(value="textsent") String textsent){
return textsent;
}
Jackson Dependency in POM.xml:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
Annotation driven in servlet-context.xml and root-context.xml:
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
first of all, put return false at the end of submit event handler
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search",
{
textsent : 'Hello Controller'
},
function(textreceived){
alert('In Callback. Text Received is: '+textreceived);
});
return false;
});
if this does not work try using Google Chrome you could debug your javascript application, put a breakpoint inside the callback and at the $.get line
I believe the issue is that you are returning type String and for some reason Spring/Jackson doesn't like when converting to a response. To fix the issue what you should do is the following:
#RequestMapping(value = "/search", method = RequestMethod.GET)
public #ResponseBody List<String> searchcontact(#RequestParam(value="textsent") String textsent){
return Arrays.asList( new String[] { textsent } );
}
It's not ideal and is quite annoying. I haven't really looked into why this happens though as the workaround was fine for me at the time.
UPDATE: Apologies I'm wrong here, you are not assuming the return is going to be JSON at all so making the controller change will have no impact.
Try passing the data returned to the callback as a parameter:
$(document).ready(function( ) {
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search", {textsent : 'Hello Controller'},
function(data){
callback(data);
});
function callback(textreceived){
alert('In Callback. Text Received is: '+textreceived);
};
});
});
You could also setup your callback function as an anonymous function to tidy things up.
$(document).ready(function( ) {
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search", {textsent : 'Hello Controller'},
function(data){
alert('In Callback. Text Received is: '+data);
});
});
});
Pretty noobish question, and I'm probably thinking about this wrong, but...
Is there a way to pass a javascript object (or a reference to it) to a javascript function within the HTML markup?
For example:
<script type="text/javascript">
var myObject = new Object();
$('body').append('<div onclick=testThis(' + myObject + ')></div>');
function testThis(object)
{
console.log(object);
}
</script>
The markup ends up looking something like this when I inspect it:
<div onclick="testThis([object Object])">
Additional context:
The real use case is a search page in which I am querying SOLR via AJAX and get a result back as JS objects. When the user clicks on the HTML markup representing one of these search results, I want to be able to pass the object(or a reference to it) to a separate JS function for processing.
Am I thinking about this the wrong way?
No, you can't embed a reference to an object into markup.
Instead you probably would like to setup your click event listening in Javascript/jQuery:
var object = new Object();
$('<div/>').appendTo('body').click(function() {
testThis(object);
});
function testThis(value) {
console.log(value);
}
I am making an AJAX calling using JQuery. I get back a JSON object containing HTML and Javascript. Within the javascript, there is a function Initialize(). This returned javascript from the AJAX call should replace the initial definition of Initialize() which was there before the AJAX call was made. So basically, I'm trying to dynamically change the code of the javascript function to code I get back from an AJAX call. Help? Thanks in advance.
I think you might be looking for something like this:
init = function() { alert("init"); };
hash = { "newInit" : function() { alert("newInit"); }};
init(); // alerts "init"
init = hash.newInit;
init(); // alerts "newInit"