How to put alert value to element - javascript

in this code i am trying to get the alert value to the element.
brief:
my ajax code checks the database values and gets the new values from database and
displays the fetched values in alert. but i am not able to put that alert values into
element...
How can i do this?
Code:
<script>
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
var rowNum = $(this).parent().parent().index();;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
setTimeout(alert(data), 2000);
var allTds = $("#rtable tr:eq('"+rowNum+"')").find('td');
$(allTds)[4].html(data[0]);
$(allTds)[3].html(data[1]);
document.getElementById("#div1").innerHTML=data;
},
error:function(data)
{
document.getElementById("#div1").innerHTML="It was a failure !!!";
}
});
});
});
</script>
HTML code:
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
In alert(data) i am getting the value.
but when i put same value like this
document.getElementById("#div1").innerHTML=data;
it is not applying the value to element

you don't need # using javascript's getElementById
try this
document.getElementById("div1").innerHTML=data; //notice no `#` in front of div1
or
using jquery that should be
$('#div1').html(data);

try
document.getElementById("div1").innerHTML=data[0];
document.getElementById("div2").innerHTML=data[1];
or
$('#div1').html(data[0]);
$('#div2').html(data[1]);
Pass the actual data inside the object to the HTML element, not the object itself.

Related

Display value from checkbox in console.log

Well this is probably an easy question but I've been figure this one out. I would like to display the value of a checkbox in the console.log so I can use it to fire a AJAX call. But the values of every checkbox is the same (the first one).
I have spent some time on google and I for what I read there, I should put the checkbox in an array. But I can't seem to get it to work. Here is my code at the moment.
<!-- Custom taxonomy checkboxes -->
<?php
$taxonomy = 'locatie';
$queried_term = get_query_var($taxonomy);
$terms = get_terms($taxonomy, 'slug='.$queried_term);
if ($terms) {
foreach($terms as $term) {
$name = $term->name;
echo "<div class='col-xs-12 col-sm-12 col-md-2 col-lg-2'>
<form id='location'>
<input class='checkIt' type='checkbox' value='".$name."' name='location' id='".$name."_id'> ".$name."
</form>
</div>";
}
}
?>
<!-- /Custom taxonomy checkboxes -->
$('.checkIt').change(function(e) {
var value = $(this).val();
$.post('../wp-content/themes/mysite/includes/search-team-wp.php',{value:value}, function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value);
});
});
});
Everything works, even the AJAX call, except the console.log output so I can't sent different values trough the AJAX call. Any help would be really nice!
use
var value = $(this).val();
The issue is because you're selecting all .checkIt elements in the selector within the change event. When you call val() on a collection of elements jQuery will only return the value of the first one.
To fix this you only need to get the value of the element that raised the change event. To do that, use the this keyword within the handler:
var value = $(this).val();
Try ajax call as given below,
var value = $(this).val();
$.ajax({
type: "POST",
url:'../wp-content/themes/mysite/includes/search-team.php',
dataType: "json",
data: {
value:value
},
success:function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value)
}
})
You can use
$('.checkIt').is(':checked')
This will give you the checked box.
Jquery.val() for checkbox always return ... the value you defined, despite of the checked state.
If you want something like when check return value, else return undefined you should do: value = $('.checkIt:checked').val();

How can I change an element's text without changing its current element?

$.ajax({
type: "GET",
url: "my url" + x,
datatype: "html",
success: function(data){
//alert(x);
//var Content = data;
var sendId ;
var data = $.parseJSON(data);
var jsonArray = data.result;
// var data2 = $.parseJSON(jsonArray);
var jsonArray3 = jsonArray.oilFilter;
$.each(jsonArray3,function(i1,js2){
var proname = js2.productName;
var mrp = js2.mrp;
var deliveryStatus = js2.deliveryStatus;
var oilid = js2.productId;
$(".oilid").val(oilid);
$(".deliveryStatusOil").html(deliveryStatus);
$(".mrpoil").html(mrp);
$(".oilprodetail").html(proname);
});
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<a onClick="ajax_cross(this);" id="oilid" class="oilid" >View</a>
If you go through the code I am assigning values to label tag with id oilprodetail and mrpoil and i am doing the same thing to oilid as well,
My requirement is to send oilid value to a tag and retain view there,
Please help? I am new to ajax..
In the above picture i need to do the right part of the pic that is view,,
but when i send the data it changes to left part of the pic like it changes from view to the value that is sent
You can use data attribute to keep innerHTML of "a" tag. Like :
$(".oilid").attr('data-oilid',oilid);
There are several issues with your code:
You misspelled datatype, which should be dataType;
Even if correctly spelled, you then wrongly identify the data type as HTML: you really expect JSON, which is something different;
Without the dataType property (which is your case), jQuery will guess the data type, and probably will guess it to be JSON. In that case, $.parseJSON will fail, because jQuery will already have decoded the JSON string and present the result as the data argument;
You use the .html(...) method to set the content of some elements to some text. html() should only be used when the content really is HTML, but otherwise (which I think is your case), you should .text(...);
An a element does not have a value property, so calling .val() on it does not have the desired effect;
You want to pass the oilid value to the ajax_cross function, but provide it this, which is an HTML element (the a), not the value.
As you iterate the array, you are setting the content of the exact same elements in each iteration over and over again, which means only the last iteration determines what the content will be. You should put each text in the proper element, avoiding to overwrite the previous written value.
The HTML you have shared, only has space for writing the result of the first array element to -- there should be similar elements for the second row, third row, etc.
To solve all this, you could get inspiration from this code:
$.ajax({
type: "GET",
url: "my url" + x,
dataType: "json", // corrected spelling and type
success: function(data){
// Don't parse as JSON string any more, data alread is object;
// Don't name your variable jsonArray, it is neither of those
var result = data.result;
var jsonArray3 = result.oilFilter;
$.each(jsonArray3, function (i1, js2) {
var proname = js2.productName;
var mrp = js2.mrp;
var deliveryStatus = js2.deliveryStatus;
var oilid = js2.productId;
// bind onclick handler with oilid argument bound to it:
// use `get()` to select the next element of the same class:
$(".oilid").get(i1).off('click').on('click', ajax_cross.bind(null, oilid));
// use text(), not html()
$(".deliveryStatusOil").get(i1).text(deliveryStatus);
$(".mrpoil").get(i1).text(mrp);
$(".oilprodetail").get(i1).text(proname);
});
}
});
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<!-- remove onclick attribute, we bind the handler dynamically -->
<a id="oilid" class="oilid" >View</a>
<hr><!-- repeat elements for second row -->
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<!-- remove onclick attribute, we bind the handler dynamically -->
<a id="oilid" class="oilid" >View</a>
<hr><!-- repeat elements for third row -->
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<!-- remove onclick attribute, we bind the handler dynamically -->
<a id="oilid" class="oilid" >View</a>
The above is still not ideal, as you would better create the elements dynamically as you iterate through the Ajax results, so you would have just as many as you would need.

How to print multiple html tags in jquery

How to print the multiple input boxes using jquery
I am using the following code
<script type="text/javascript">
$(document).ready(function(){
$("#taxId").change(function(){
var tax_id=$("#taxId").val();
$.ajax({
type:"post",
url:"<?php echo base_url();?>index.php/pranasInventory/get_tax_detail",
data:{tax_id:tax_id},
success:function(data)
{
var json_obj = $.parseJSON(data);//parse JSON
var len=json_obj.length;
for (var i=0;i<len;i++)
{
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
}
});
});
});
</script>
It print only one input tag.
my console message like this
Service tax # 14%<input id='taxcal' name='taxcal' placeholder='0.00'>
swachh bharat cess # 0.5%<input id='taxcal' name='taxcal'placeholder='0.00'>
I want print two input box.
please help me
The html function replaces the whole content.
You might replace
var len=json_obj.length;
for (var i=0;i<len;i++) {
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
with
$('#taxDetail').append(json_obj.map(function(obj){
return $("<input placeholder='0.00'>");
});
but you need to decide how to handle the ids of the added inputs as you can't obviously use the same for all.
.html replaces the whole content of the div. You must use JQuery append or prepend methods.

Select element from Jquery post return

I am trying to select an element from jquery post returning data. String is returning but when I try to select an element from returning html string, selection is always null. This is a userscript which is being loaded with greasemonkey.
refresh();
function refresh(___id,___action,___page){
$.post("http://www.example.com", {auction_id:___id,action:___action,page:___page}, function(bidpage){
var auction_id = $("#auction_id", bidpage).val();
console.log(auction_id);
});
This post returns this data
<html><head></head><body><input type="hidden" name="auction_id" id="auction_id" value="8583949"></body></html>
But auction_id is always null. Cant find any solution to that. Thank you for your helps.
This is because you get bidpage as string. You need to convert it to HTML first:
var auction_id = $("#auction_id", $( bidpage ) ).val();
As by jQuery API [context] should be DOM Element, Document, or jQuery.
COMMENT:
Seems like jQuery strips <html> and <body> elements so you need to use:
var auction_id = $( bidpage ).val();
you could try adding your post data to a div:
<div id="appendpostdatahere"></div>
function refresh(___id,___action,___page){
$.post("http://www.example.com", {auction_id:___id,action:___action,page:___page},
function(bidpage){
$('#appendpostdatahere').html(bidpage);
var auction_id = $('#auction_id).val();
console.log(auction_id);
});
}

How to call ajax and output its result inside div and textarea?

I am trying to make load more button. My goal is to call ajax and put the response inside div and textarea.how to place the response inside div and textarea? Currently the response only shows in messagebox but i want to append the result into div.
*Note:*Response is html hyperlinks produced by process.php and i want those hyperlinks placed inside the div
<html>
<head>
<script>
//initialize page number to 1 default
var pagenumber=1;
//pass pagenumber to function to fetch correct page records
function getResult(pagenumber){
alert('me here'+pagenumber);
$.ajax(
{
type: 'GET',
url: './process.php?ID=1234&type=1&moviePath=1234/1212/Love&title=Love&page='+pagenumber,
data: $("#myform").serialize(),
data: {
},
success: function (good)
{
//handle success
alert(good)
},
failure: function (bad)
{
//handle any errors
alert(bad)
}
});
//after every call increment page number value
pagenumber++;
}// end of getResult Function
function addMoreItems()
{
pagenumber++;
getResult(pagenumber);
}
</script>
</head>
<body>
<div id="myDiv"></div>
<div class="MoreButtonSection">
<div class="RedButton">
<span class="LeftEnd"></span>
<span class="Centre">see more</span>
<span class="RightEnd"></span>
</div>
</div>
<br>
<br>
<form id="myform" name="myform" action="./2.php?Id=&title=" method="post">
<td>
<textarea rows="7" cols="15" name="outputtext" style="width: 99%;"></textarea>
</td>
</form>
</html>
You say your result is only showing in the message box, instead of alerting it, simply append. Assuming the below div is what you want to append to:
<div id="myDiv"></div>
You can modify your success function:
success: function (good)
{
//handle success
$("#myDiv").append(good);
},
Also, get rid of that second data: {}, -- it's doing nothing.
There are a number of issues.
There is no indication that you've included jQuery.
You've declared data: twice.
As Dmitry pointed out, you should probably be posting this.
And finally, where are you actually calling getResult()? It doesn't look like it's being called.
In addition, it is worth noting that from jQuery 1.8 and higher, .success() and .failure() are now deprecated and have been replaced with .done() and .fail().
http://api.jquery.com/jQuery.ajax/
I tend to use jQuery in these situations to make life a little easier, and work with the $('#yourDiv').append() function. For instance you can create variables i.e. var mug; and once it is filled with your data append mug to the document through $('#yourDiv').append("<p>"+mug+"</p>);
An example - Ajax Twitter API call that returns tweets to specific lists within a div (page source)
Hope that helps!
I think I get what you are trying to do but that code is a mess. As #David L has stated, you need jQuery. But then you do not need all the code you have written. It can be done in a few simple lines. Please replace the actual element selectors with your correct ones.
function addMoreItems() {
pagenumber++;
// get form values
var params = $('#myform').serializeArray();
// add predefined values
params.push({name: 'ID', value: '1234'});
params.push({name: 'type', value: '1'});
params.push({name: 'moviePath', value: '1234/1212/Love'});
params.push({name: 'title', value: 'Love'});
params.push({name: 'page', value: pagenumber});
// do request and insert response from server in div with id='divresults'
$.get('process.php', params, function(data) {
$('#divResults').append(data);
});
}

Categories

Resources