How to display ajax success response inside div with javascript - ajax

I am writing one ajax call and collect the response from controller. I want to show that response(jsp) to one particular div. Please help me, how to put response div to current page div.Below is the code:
function openSocietyTab(divName, parentTabName, subTabName)
{
debugger;
var i;
var x = document.getElementById(divName);
var parentTempId = parentTabName;
var tempId = subTabName;
$.ajax({
type : "GET",
url : "/ApartmentAdda/"+parentTempId+"/"+tempId,
data : {x:tempId},
timeout : 100000,
success : function(x) {
debugger;
console.log("SUCCESS: ", x);
// here i want to display x into divName div.(x is the jsp view which i am getting from controller)
},
error : function(e) {
console.log("ERROR: ", e);
}
});
}
I am calling this javascript function on button click:
<button class="w3-bar-item w3-button dropbtnInr" onclick="openSocietyTab('tabToOpen','societyService','houseTab')">Houses</button><br>
and tabToOpen is the div on which I want to open ajax response jsp.

There are many ways, but since you only want to display a certain div then I'd suggest you to use the hidden class to hide and show the div.
For example if the div has id="tabToOpen" and you are using jQuery then it would be:
$(#tabToOpen).addClass('hidden');
$(#tabToOpen).removeClass('hidden');
If you are not using jQuery then try:
var theInfoDiv = document.getElementsById('tabToOpen');
theInfoDiv.classList.add('hidden');
theInfoDiv.classList.remove('hidden');

Related

Play framework render HTML & values on same page via ajax

I'm using ajax within the play (scala) framework to run some code after a click event occurs on a page. I want to return the results of that code execution on the same page.
EDIT: the goal of this is to display some rows from the database, along with form elements to fill out to update cells of the databse, all without reloading/or going to a new page
Is there a way to pass html + (scala) values into
Ok(...).as(HTML)
to display without directing to new a page?
I know Ok can take things like:
Ok(<h1>it works</h1>).as(HTML)
but I can't figure out how to combine that with scala values as well. Is there a smarter way to do this?
EDIT: the ajax looks like this:
var ajaxCall = function() {
var ajaxCallBack = {
success : onSuccess,
error : onError
}
jsRoutes.controllers.Application.scrape().ajax(ajaxCallBack);
};
var onSuccess = function(data) {
$("#results").append(data);
}
var onError = function(error) {
alert(error);
}
For sure you can. You can use TWIRL templates:
Create a template "views/Application/contacts.scala.html
#(users: List[User])
<h1>Users</h1>
<ul>
#for(user <- users) {
<li>#user.name</li>
}
</ul>
in the controller:
Ok(views.html.Application.contacts(users))

Spring MVC Ajax updating DIV

Okay...I am coming from C# MVC using partial views/ajax, etc...
Here's what I have: 1 main page with a target ID that renders the default information using a page include.
What I want to do is onclick of a button target the original ID and render a different page as the include. Kind of like RenderPartials in C# MVC.
Can Spring (using Maven) MVC do this or is there a way to go about this that is strait forward?
Thanks,
You don't need to implement partial views just have an empty div and on click of a button make an ajax request get the content and update the div. something like below.
function button_onclick() {
var params = {}; //put parameter if any
$.ajax({
headers: {
Accept : "text/plain; charset=utf-8","Content-Type": "text/plain; charset=utf-8"},
url: "/controller",
method:"GET",
data:params,
success:function(data, textStatus,response) {
var text = response.responseText;
if (text == "") {
return;
}
$( "#DIV_ID" ).text(text);
},
error: function(response) {
alert(response);
// terminate the script
}
});
}

ajax call not responding with $.post

What i am trying to do is to get the value of the selected elements by jquery selection. After that, those value are post to php script via ajax and then retrieve the data from the database and display it on the same page (something called autocompete).
var marvalue=$("input[name=m_status]:checked").val();
var fromhvalue=$("#fromheight").val();
var tohvalue=$("#toheight").val();
var value = $("#edu_det1").val();
alert (value);
var regvalue = $("#religion").val();
alert (regvalue);
var occvalue = $("#occupation").val();
alert (occvalue);
var convalue = $("#country").val();
alert (convalue);
Alert is there to check the correct values. As you see the code above this will get the values from the different input elements.
Below is the code i used to post to php
/*
$.post("regsearch.php", {queryString: ""+value+"",queryString1: ""+marvalue+"",queryStringfage: ""+fage+"",queryStringtage: ""+tage+""+queryStringfromh: ""+fromhvalue+""+queryStringtoh: ""+tohvalue+""+}, function(data) { // Do an AJAX call
$('#suggestions').fadeIn(); // Show the suggestions box
$('#suggestions').html(data); // Fill the suggestions box
});
*/
The problem :
when the comment is removed nor the alert popup and neither the result displayed. Ok about the result as no query is posted.
Major part is that when i use the below code which hold only m_status and edu_det1 it works.
marvalue=$("input[name=m_status]:checked").val();
alert (marvalue);
var value = $("#edu_det1").val();
alert (value);
The post code for above is
$.post("regsearch.php", {
queryString: ""+value+"",
queryString1: ""+marvalue+"",
queryStringfage: ""+fage+"",queryStringtage: ""+tage+""
}, function(data) {
// Do an AJAX call
$('#suggestions').fadeIn(); // Show the suggestions box
$('#suggestions').html(data); // Fill the suggestions box
});
The code for age and it verification is not added here. What is the problem and how to sort this out?
It will be better if you use jquery serialize() function. This will make your life easier to work with forms.
var querstring = $(form).serialize();
above will help
I guess using ajax post jQuery.ajax() will do the same thing and you can even serialize the fields in your page.
http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
I have done similar type of code
UserName is the field Which I am passing
var data = $('#Username').serialize();
$('#usernameCheck').empty();
if (!$("form").validate().element("#Username"))
return;
$.ajax({
url: '/SignUp/CheckUsername',
type: 'POST',
data: data,
async: true,
success: function (result) {
if (result == 1) {
$('#usernameCheck').html('<font color=green>Username available</font>');
usernameOK = true;
}
else if (result == 2) {
$('#usernameCheck').html('<font color=red>Username not available</font>');
usernameOK = false;
}
else {
$('#usernameCheck').empty();
usernameOK = false;
}
}
});
First of all you should use your console to see Javascript errors, as I'm sure this will generate some. For example that querystring is undefined.
I'd also console.log instead of alert, it is less annoying and more informative.
Then: you dont need to use f.e. ""+marvalue+"" - just use marvalue. On the other hand f.e. queryString should be quoted...
$.post("regsearch.php", {'queryString':value,'queryString1': marvalue,'queryStringfage':fage,'queryStringtage':tage,'queryStringfromh': fromhvalue,'queryStringtoh':tohvalue}, function(data) {
$('#suggestions').fadeIn();
$('#suggestions').html(data);
});

JQuery mobile collapsible with Ajax

trying to display the JQMobile collapsible containing an unsorted list. The collapsible is not shown when the list is appended using an ajax call. The collapsible is correctly shown when the list is added statically. Any advice?
thanks
<script>
$(document).ready(function() {
var updateSectionsPage = function() {
// 1. Get the page and list we need to work with
var $page = $('#homeList');
// 2. Build the URL we need using the data stored on the main view page
var strUrl = 'http://xyz';
// 3. Get the sections and append them to the list
$.ajax({
url: strUrl,
dataType: 'json',
cache: false,
success: function(data) {
$sections = $page.find('#sections');
// 3.1 Delete the existing content, if any
$sections.empty();
// 3.2 Create a new collapsible
$sections.html('<div id="collapsible" data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a"></div>');
// 3.3 Create the title of collapsible
$sections.html('<h3>ColdPlay</h3>');
// 3.4 Create the list and store it into a JQuery object
$sections.html('<ul id="list" data-role="listview" data-inset="false"></ul>');
$list = $page.find('#list');
// 3.5 Build HTML that contains the desired information
for (var j in data.list[0].list){
var strHtml = '<li><img src="' + data.list[0].list[j].img + '" /><h4>' + data.list[0].list[j].title + '</h4></li>';
// Make it into a jQuery object...
var item = $(strHtml);
// ...so we can append it to our list.
$list.append(item);
}
// Call the listview widget.
$list.listview();
},
error: function() {
alert("An error occurred. please, try it again!");
}
});
}(); // 4. Call the updateSectionsPage() function
})
</script>
I think you just need to turn your $list.listview(); call into $list.listview('refresh');.
Also, you may benefit from changing up the way you append you new list items. Check this post out. You do not want to nest an append call within a loop if you can avoid it. You will also benefit from not wrapping your strHtml with the jQuery $ selector as it may not be necessary.
That optimization link is courtesy of another SO post here.
Once you create the list,use the following code snippet-
$list.listview('refresh');
$page.trigger('create');
in place of $list.listview();
Also it is not considered a best practice to use $(document).ready() in jquery mobile.See the note below
Important: Use pageInit(), not $(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.
From http://jquerymobile.com/demos/1.0/docs/api/events.html
thanks guys, the issue in my code was on the missing collapsible() widget call. Once the html page is dynamically created, we need to render it with jqmobile widget calls: listview() and collapsible(). Here the working code.
function fillSectionsPage() {
// 1. Get the page we need to work with
var $page = $('#sectionList');
// 2. Build the URL we need using the data stored on the main view page
var strUrl = 'http://xyz';
// 3. Get the sections and append them to the list
$.ajax({
url: strUrl,
dataType: 'json',
cache: false,
success: function(data) {
$sections = $page.find('#sections');
// 3.1 Delete the existing content, if any
$sections.empty();
// 3.2 Append a new collapsible and store it into a JQuery object
$sections.append('<div id="collapsible" data-role="collapsible" data-collapsed="true" data-theme="c" data-content-theme="c"></div>');
$collapsible = $page.find('#collapsible');
// 3.3 Append the title of collapsible
$collapsible.append('<h3>' + data.list[0].title + '</h3>');
// 3.4 Append the list header and store it into a JQuery object
$collapsible.append('<ul id="list" data-role="listview" data-inset="false"></ul>');
$list = $page.find('#list');
// 3.5 Build the list items
var htlmList = [];
for (var j in data.list[0].list){
htlmList[j] = '<li><img src="' + data.list[0].list[j].img + '" /><h4>' + data.list[0].list[j].title + '</h4></li>';
}
// 3.6 Append the list items to the list header
$list.append(htlmList.join(''));
// 3.7 Render the listview and the collapsible
$list.listview();
$collapsible.collapsible();
},
error: function() {
alert("An error occurred, please, try it again!");
}
});
}
Hope to check that tutorial, Collapsible content and Ajax loading with jQuery Mobile and this for How do I toggle the jQuery Mobile Accordion with a button click?

jQuery monitoring form field created by AJAX query

Preface: I am sure this is incredibly simple, but I have searched this site & the jQuery site and can't figure out the right search term to get an answer - please excuse my ignorance!
I am adding additional form fields using jQuery's ajax function and need to then apply additional ajax functions to those fields but can't seem to get jQuery to monitor these on the fly form fields.
How can I get jQuery to use these new fields?
$(document).ready(function() {
$('#formField').hide();
$('.lnk').click(function() {
var t = this.id;
$('#formField').show(400);
$('#form').load('loader.php?val=' + t);
});
//This works fine if the field is already present
var name = $('#name');
var email = $('#email');
$('#uid').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(function () {
$.ajax({
url: 'loader.php',
data: 'action=getUser&uid=' + t.value,
type: 'get',
success: function (j) {
va = j.split("|");
displayname = va[1];
mail = va[2];
name.val(displayname);
email.val(mail);
}
});
}, 200);
this.lastValue = this.value;
}
});
});
So if the is present in the basic html page the function works, but if it arrives by the $.load function it doesn't - presumably because $(document).ready has already started.
I did try:
$(document).ready(function() {
$('#formField').hide();
$('.lnk').click(function() {
var t = this.id;
$('#formField').show(400);
$('#form').load('loader.php?val=' + t);
prepUid();
});
});
function prepUid(){
var name = $('#name');
var email = $('#email');
$('#uid').keyup(function () {
snip...........
But it didn't seem to work...
I think you are close. You need to add your keyup handler once the .load call is complete. Try changing this...
$('#form').load('loader.php?val=' + t);
prepUid();
To this...
$('#form').load('loader.php?val=' + t, null, prepUid);
What you are looking for is the jquery live function.
Attach a handler to the event for all elements which match the current selector, now or in the future
You can do something like this:
$('.clickme').live('click', function() {// Live handler called.});
and then add something using the DOM
$('body').append('<div class="clickme">Another target</div>');
When you click the div added above it will trigger the click handler as you expect with statically loaded dom nodes.
You can read more here: http://api.jquery.com/live/

Resources