I’m working on a project where I need to dynamically change the content of a div element using jQuery after an AJAX request completes. Here’s what I have so far:
HTML Structure:
<div id="header">
<h1>
Office
<small>Climate System</small>
</h1>
</div>
JavaScript Code:
$(document).ready(function(){
$('.btnSubmit').click(function(e){
e.preventDefault();
$('#mainform').hide();
$('#resultform').show();
var postData = {};
postData.location = $(this).data('location');
postData.tempid = $(this).data('tempid');
postData.tempkey = $(this).data('tempkey');
postData.humidid = $(this).data('humidid');
postData.humidkey = $(this).data('humidkey');
var locationText = $(this).data('location');
$.ajax({
url: 'fetchData.php',
type: 'post',
dataType: 'text',
data: postData
}).done(function(response){
$('#header').html("<div id='header'><h1>" + locationText + "</div></h1>");
});
});
});
The problem is that when the AJAX call finishes, the div content doesn’t get updated with the new information from my locationText variable. The replacement isn’t working as expected.
Also, my locationText variable contains something like “Building A - Floor 2”. How can I split this into two separate parts so I can display them as <h1>Building A</h1> and <small>Floor 2</small>?
Any help would be appreciated!
Looks like a variable scope problem. Your locationText variable probably isn’t accessible inside the AJAX callback - I’ve hit this same issue with dynamic content before.
Move the variable declaration inside the callback or just grab it fresh right where you need it:
$.ajax({
url: 'fetchData.php',
type: 'post',
dataType: 'text',
data: postData
}).done(function(response){
var locationText = $('.btnSubmit').data('location'); // Get it fresh
var locationParts = locationText.split(' - ');
$('#header').html('<h1>' + locationParts[0] + '<small>' + locationParts[1] + '</small></h1>');
});
This fixes scope issues and makes sure you’re working with current data. Also check your browser console for any JS errors that might be blocking the update.
The issue’s probably simpler than you think - your locationText variable is likely undefined when the AJAX call runs. Try using $(this).data(‘location’) directly inside the done callback instead of storing it first. Also, your HTML structure has closing tags in the wrong order.
Your HTML has a structural problem - you’re creating nested divs with the same ID, which breaks markup rules. When you use $('#header').html(), you’re already inside the header div, so don’t recreate it.
Here’s the fix:
$.ajax({
url: 'fetchData.php',
type: 'post',
dataType: 'text',
data: postData
}).done(function(response){
var parts = locationText.split(' - ');
var building = parts[0] || '';
var floor = parts[1] || '';
$('#header').html('<h1>' + building + '<small>' + floor + '</small></h1>');
});
The split method handles your “Building A - Floor 2” string perfectly. Add console.log(locationText) before the AJAX call to make sure it’s not undefined or empty.