PDA

View Full Version : Resolved jQuery assign innerHtml to result of ajax



keyboard
04-02-2012, 04:52 AM
Hey everyone,

I've got this code



<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
var field1 = $('#fldrChatWindowInput'),
$('#send').click(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'process.php',
type: 'post',
data: 'field1value=' + field1.html() + '&field2value=' + field2.value,
success: function(results){
alert(results);
}
});
});
});
</script>
<div id="fldrChatWindow"></div>
<div id="fldrChatWindowInput" contenteditable></div>
<input type="button" value="Submit" id="send">


Instead of alerting results, I'd like to assign it to a global variable that I'd use in normal javascript(not jQuery).

Sorry if the question is a little bit easy.
Keyboard1333

jscheuer1
04-02-2012, 11:11 AM
Your question is different than the title suggests. And using global variables when they're not required risks errors and/or conflicts. To answer the title:


jQuery.ajax({
url: 'process.php',
type: 'post',
data: 'field1value=' + field1.html() + '&field2value=' + field2.value,
success: function(results){
$('#target_id').html(results);
}
});

where target_id is the unique id of an element you want to send the results to.

If you want to do that with regular javascript:


jQuery.ajax({
url: 'process.php',
type: 'post',
data: 'field1value=' + field1.html() + '&field2value=' + field2.value,
success: function(results){
document.getElementById('target_id').innerHTML = results;
}
});

Still no global involved though.

To answer your question in the post, hmm. It's sort of a trick question. You can make a variable be a global variable simply by prefacing it with window. Like:


jQuery.ajax({
url: 'process.php',
type: 'post',
data: 'field1value=' + field1.html() + '&field2value=' + field2.value,
success: function(results){
window.myGlobalVar = results;
}
});

where myGlobalVar can be any unique variable name you like.

Alternatively, you could declare a global ahead of time:


<script type="text/javascript">
var myGlobalVar;
jQuery(function($){
var field1 = $('#fldrChatWindowInput'),
$('#send').click(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'process.php',
type: 'post',
data: 'field1value=' + field1.html() + '&field2value=' + field2.value,
success: function(results){
myGlobalVar = results;
}
});
});
});
</script>

What makes it a trick question is, regardless of how you do it, that value will not be available until the jQuery.ajax function has completed successfully. So, you might as well use it right within the success function, and at that point there's no sense in making it global.

keyboard
04-02-2012, 11:35 AM
Thanks for your reply John.