Textarea is not displaying the result - javascript

I have a textarea which will be in hidden state when the request comes to the page and once i select the value in the page i call a controller method which does manipilation and returns the response to the same page and in the ajax success method i try to print the response in the textarea
This is my gsp page
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<title>Json Compare</title>
<g:javascript plugin="jquery" library="jquery"
src="jquery/jquery-1.11.1.js" />
<script>
$(document).ready(function(){
$('.testMe').click(function(){
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
var retrievedValue = JSON.parse(data);
alert("Parsed Values are: "+retrievedValue)
alert("Values are: "+retrievedValue.status)
//alert("success: "+retrievedValue.result)
if (retrievedValue.status===true) {
alert("inside the success: "+retrievedValue.result)
alert("the parsed values 1st data"+data.firstText)
$("#result").css("display","block")
$("#result").val(data.firstText)
//notice .html since it is content of textArea
//$('.textarea').html(retrievedValue.result)
//document.getElementById("textarea").style.display = "block"
//document.getElementById("textarea").innerHTML = data.result
//$('#textarea').val(retrievedValue.result).show()
// $('.textarea').css("display","");
//$('#result').attr('style', 'display:block'); 
//$('#testdiv').show()
//$('.textarea').toggle();
// $('#testdiv').attr('style', 'display:block'); 
//$('#testdiv').removeAttr("style");
//document.getElementById("result").style.display = "none";
} else { /// if (data===false ) {
alert("Failure: "+retrievedValue.value1+" "+retrievedValue.value2)
//$('#result1').html(entry.value1).show()
// $('#result2').html(entry.value2).show()
}
}
});
});
});
//event.preventDefault();
</script>
</head>
<body>
<g:form>
<div>
<label>From Time</label>
<g:select name="firstText" from="${eventsList}" noSelection="['':'-Choose the From Date-']" />
<label>To Time</label>
<g:select name="secondText" from="${eventsList}" noSelection="['':'-Choose the To Date-']" />
<button class="testMe">Compare</button>
</div>
<br>
<textarea id="result" style="display: none"></textarea>
<%--<div id="textarea">
<label>Output</label><br>
<textArea id="result" name="myField" />
<textarea></textarea>
</div>
--%></g:form>
</body>
</html>
once the result is displayed immediately it disappears how to stop it. And also how to display the result different textarea based on the response from the controller. Initially the textarea should not be visible

Treat a textArea like a div
$('#textArea').html('content');
Unless you declare:
<g:textArea value="something" />
Which then behaves differently to a standard textArea if I recall correctly

Update:
$(document).ready(function(e){
$('.testMe').click(function(e){
e.preventDefault();
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
//alert("success"+data.value)
console.log(data);
$("#result").val(data).show()
}
});
});
});

try this.. hopefully it'll work.
$(document).ready(function() {
$('.testMe').click(function() {
var URL = "${createLink(controller:'jsonComparison',action:'compare')}";
var firstText = $('#firstText');
var secondText = $('#secondText');
alert(URL);
alert(firstText.val());
alert(secondText.val());
$.ajax({
url: URL,
data: {
firstText: firstText.val(),
secondText: secondText.val()
},
success: function(data) {
//alert("success"+data.value)
console.log(data);
$("#result").val(data);
$("#result").show();
}
});
});
});

And if you try to append the textarea element dynamically? For example:
$(document).ready(function(){
$('.testMe').click(function(){
// ... your code ...
// ajax part
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
var textarea_el = $('<textarea />', {
id: 'result',
text: data.value // or just data?
});
// change form_selector with the real selector!
$(<form_selector>).append(textarea_el);
}
});
});
});

<script>
$(document).ready(function(){
$('.testMe').click(function(){
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
//alert("success"+data.value)
console.log(data);
$("#result").css("display","block")
$("#result").val(data.firstText)
}
});
});
});
</script>
try above code
if it not ,try to alert(data.firstText) check the return value in alert .whether it is object or value

Related

The response received in AJAX call is shown in another HTML page

I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.
Form HTML
<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
<div class="form-group">
<input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
<button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
</div>
</form>
AJAX
<script>
$("#AssociateForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var local_id = $('input[name=J_ID]').attr('id');
var formData = {
'J_ID' : $('input[name=J_ID]').val()
};
console.log(formData)
$.ajax({
url: url,
data: formData,
dataType: 'json',
success: function (datas) {
var data = JSON.parse(datas);
if(datas.status){
alert(datas);
//$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
}
},
error: function(jqXHR, textStatus){
alert("In error")
}
})
.done(function(data){
alert(data)
});
});
</script>
for some reason, the above code is not printing the console log as well.
But,
When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.
JSON Response
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
below is from View-Page-source
<html>
<head></head>
<body data-gr-c-s-loaded="true">
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
</pre>
</body>
</html>
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:
<form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
$('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>
success: function (datas) {
if (datas.status) {
alert(datas);
$('pre#<ID>').html(datas.category + ' issue: ' + datas.j_id + ' (' + datas.j_status + ')');
}
}
This worked for me, I removed the form completely.
Code in-place of Form
<div class="form-group AssociateForm" style="float:right">
<input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
<button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>
AJAX
<script>
$('.Associater').on('click', function () {
var local_id = $(this).attr('id');
var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();
if (j_id === "") {
alert("JID cannot be empty")
return false
}
var url = "{% url 'Project:View' 0 %}".replace('0', local_id);
var formData = {
'J_ID' : j_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
console.log(local_id);
console.log(j_id);
console.log(url);
console.log(formData);
$.ajax({
type: 'POST',
url: url,
data: formData,
dataType: 'json',
success: function (data) {
if (data.status) {
ele = 'Failure_'+local_id;
document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
}
},
error: function (jqXHR, textStatus ) {
alert("For some reason im here");
}
});
});
</script>

How to pass onclick function values to ajax post method without refresh page?

This is my onclick function. When I click it the php values should save in database.
<div class="startup-like">
<label class="toggler toggler-danger">
<input type="checkbox" onclick="return favadd(<?php echo $favblogid;?>,<?php echo $b;?>,<?php echo $type_id;?>,<?php echo $lang_id;?>);">
<i class="fa fa-bookmark" title="Save" id="toptip"></i>
</label>
</div>
and this is my script for the onclick function.
<script>
function favadd(val,val2,val3,val4)
{
var blog_id=val;
var userid=val2;
var catid=val3;
var lang=val4;
$.ajax({
type: "POST",
url: "startuparticle_save.php",
data: {
fav_blogid: blog_id,
fav_user_id: userid,
cat_id:catid,
langid:lang
},
success: function (value) {
}
});
}
</script>
I want to pass the values without refresh the page.
<script>
function favadd(val,val2,val3,val4)
{
var blog_id=val;
var userid=val2;
var catid=val3;
var lang=val4;
$.ajax({
type: "POST",
url: "startuparticle_save.php",
data: {
fav_blogid: blog_id,
fav_user_id: userid,
cat_id:catid,
langid:lang
},
success: function (value) {
"$("#your div id").load(" #your div id> ");"
}
});
}
</script>
<script type="text/javascript">
$("#MyButton").click(function() {
alert('clicked')
$("#refresh_div").load(" #refresh_div> *`enter code here`");
});
</script>

Add one or two more PHP variables to the javascript code

I am a decent PHP programer and recently I got stuck in a javascript code.
I have the code below:
$(function () {
$('.more').live("click", function () {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("div#updates").append(html);
$("#more" + ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
This code submit without problems one PHP variable to the process page loadmore.php using this input
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
<a href="#" class="more" id="<?php echo $load_id; ?>">
load more
</a>
</div>
How can put more variables in the input and the javascript code to work with them on the process page?
I want to set one or two more variables.
UPDATE:
I updated the code like this:
HTML input:
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
load more</div>
JAVASCRIPT CODE:
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: {"lastmsg="+ ID, "act="+ ACT},
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
I am not sure if the data lines was writed properly because the script looks like it's frozen now
SOLVED:
I just used a datastring like this
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
var dataString = 'lastmsg='+ ID + '&act=' + ACT;
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: dataString,
//data: {"lastmsg="+ ID, "act="+ ACT },
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
Just send data as an object:
data: {
"lastmsg": "lastmsg="+ ID,
"anotherData": "someData"
}
You'll retrieve them in your PHP script as follows:
$_POST["lastmsg"];
$_POST["anotherData"];

show value in the texbox using ajax - php

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getvalues() {
var selname = $("input[name='names']:text").val();
$.ajax({
url: "process.php",
data: {
"selname": selname
},
type: 'post',
dataType: "json",
success: function (output) {
console.log(output);
$("#aic").val(output[0]);
$("#batchcode").val(output[1]);
}
});
}
</script>
</script>
</head>
<body>
<form method="post">
<input type="text" name="names" id="query" onblur="getvalues()" />
<input type="text" name="aic" id="aic" />
<textarea name="batchcode" id="batchcode" rows="4" cols="50"></textarea>
</form>
</body>
</html>
process.php
<?php
if(isset($_POST['selname']))
{
$response = array('0001', 'short info : john 29 years old - technician '); // add return data to an array
echo json_encode($response); // json encode that array
exit;
}
?>
when I type something on input type="text" name="names"
I get on input text "aic" >>> 1; but in the textarea I didn't get "short info : john 29 years old - technician ", please tell me where is the mistake!!
Convert json to array
var array = JSON.parse(output)
$("#aic").val(array[0]);
$("#batchcode").val(array[1]);
try this
function getvalues() {
var selname = $("input[name='names']:text").val();
$.ajax({
url: "process.php",
data: {
"selname": selname
},
type: 'post',
dataType: "json",
success: function (output) {
var output = jQuery.parseJSON( output );
console.log(output);//use output.property
$("#aic").val(output[0]);
$("#batchcode").val(output[1]);
}
});
}

event.preventDefault() with .on('click') doesn't prevent default behavior

I have the following HTML and javascript. When I click .todo and .completedmsg which have links, I am expecting event.preventDefault(). But it jumps to the link.
$("#form").on('click',".todo", function(event){...}
$("#form").on('click','.completedmsg', function(event){...}
What am I doing wrong here?
HTML all
<div id="homeright" class="adminhome">
<form method="post" id="form" action="admin/insertShoutBox">
<input type="hidden" name="user_id" id="user_id" value="1">
<input type="hidden" name="user" id="nick" value="admin">
<p class="messagelabel"><label class="messagelabel">Message</label>
<textarea id="message" name="message" rows="2" cols="80"></textarea>
</p>
<div class="buttons">
<button type="submit" class="positive" name="submit" value="submit">
<img src="http://localhost/website2014/assets/icons/disk.png" alt="disk"> Save </button>
</div>
</form>
<div id="loading" style="display: none;"><img src="../../assets/images/general/ajax-loader2.gif" alt="Loading now. Smile"></div>
<div class="clearboth"></div>
<div id="container">
<span class="clear"></span>
<div class="content">
<h1>Latest Messages or Task To Do</h1>
<ul id="message_ul" style="display: block;">
<li class="1">
<div class="listbox"><span class="user"><strong>admin</strong></span>
<span class="date">2014-03-28 17:25:50</span>
to do<span class="msg">test</span></div></li></ul>
</div>
</div>
<div id="completed">
<h1>Completed Lists</h1>
<ul id="completed_ul" style="display: block;">
<li class="2">
<span class="user"><strong>admin</strong></span>
<span class="date">2014-03-28 18:11:29</span>
completed
x<span class="msg">another test
</span>
</li></ul>
</div>
</div>
jQuery all
$(document).ready(function(){
//global vars
var inputUser = $("#nick");
var inputMessage = $("#message");
var loading = $("#loading");
var messageList = $("#message_ul");
var completedmsg = $("#completed");
var completedList = $("#completed_ul");
//Load for the first time the shoutbox data
updateShoutbox();
updateCompletedbox();
function updateShoutbox()
{
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/AjaxgetShoutBox'); ?>",
complete: function(data)
{
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(500);
//completedList.fadeIn(500);
}
});
}
function updateCompletedbox()
{
//just for the fade effect
completedList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/AjaxgetCompletedBox'); ?>",
complete: function(data)
{
loading.fadeOut();
completedList.html(data.responseText);
// messageList.fadeIn(500);
completedList.fadeIn(500);
}
});
}
//check if all fields are filled
function checkForm()
{
if(inputUser.val() && inputMessage.val())
{
return true;
}
else
{
return false;
}
}
//on submit event
$("#form").submit(function(event){
event.preventDefault();
if(checkForm())
{
var nick = inputUser.attr("value");
var message = inputMessage.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/insertShoutBox'); ?>",
data: $('#form').serialize(),
complete: function(data)
{
messageList.html(data.responseText);
updateShoutbox();
$('#message').val('');
//reactivate the send button
$("#send").attr({ disabled:false, value:"SUBMIT !" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
//on todo event. this changes the status to compeleted
$("#form").on('click',".todo", function(event){
event.preventDefault();
loading.fadeIn();
var href = $(this).attr("href");
var msgContainer = $(this).closest('li');
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function()
{
msgContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
// on complete event. this changes the status to todo
$("#form").on('click','.completedmsg', function(event){
event.preventDefault();
loading.fadeIn();
var href = $(this).attr("href");
var CompMsgContainer = $(this).closest('li');
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function(){
CompMsgContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
$("#form").on('click','.delete',function(event){
event.preventDefault();
// alert ('clicked');
loading.fadeIn();
var href = $(this).attr("href");
var commentContainer = $(this).parent();
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function()
{
commentContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
});
There are no links inside #form with a class of todo - so the events are not attached to your links:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
The links are outside of the form, so those particular events can't be firing. If the event isn't firing then it makes sense that the links are being 'jumped to' as there's nothing to trap it. If you place a link with the class of .todo inside the form, you will get the desired effect.
As a first test, you could just bind to $(document) instead of #form and check the preventDefault before re-working the HTML so that you can bind to a lower-level element in the DOM (if required...)
Cut-down example of issue: http://jsfiddle.net/YWV9A/1/
Solution: http://jsfiddle.net/YWV9A/3/

Categories

Resources