show value in the texbox using ajax - php - javascript

<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]);
}
});
}

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>

Textarea is not displaying the result

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

Pass values from JQUERY to PHP then output to INPUT in FORM

i need to get a value from the a form then send it to php using jquery then output the result a dropdown select menu
get the value of using jquery
<input id="search" name="search" type="text">
send it to php and perform a query
<select id="farmertype" name="farmertype" >
<option value="" > - PLEASE SELECT FARM -</option>
//// output here as options
</select>
my php file farm.php
<?php
include_once("../init.php");
$q = ($_POST["search"]);
$db->query("SELECT * FROM farmers ");
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
echo "<option value='$idno'>$idno</option>";
}
}
?>
the jquery part is so messy this is where i really need help
$("#search").click(function() {
search = $(this).attr('#search');
$.ajax({
type: 'GET',
url: 'farm.php',
data: "#search=" + search,
});
});
try this, it will help you.
JQuery:
$("#search").click(function() {
search = $(this).val();
$.ajax({
type: 'POST',
url: 'farm.php',
data: {searchValue:search},
success:function(result) {
console.log(result);
}
});
});
PHP:
<?php
include_once("../init.php");
$q = ($_POST["searchValue"]);
$db->query("SELECT * FROM farmers");
$result = [];
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
$result = "<option value='$idno'>$idno</option>";
}
print_r($result);
?>
what is the purpose of your variable $q?
Your jquery can be like :
$("#search").click(function() {
search = $('#search').val();
$.ajax({
type: 'GET',
url: 'farm.php',
data: {search : search},
success: function(html){
alert(html);
}
});
});
$("#search").click(function() { /* I think you should use keyUp or use click on a button, nobody clicks an input box */
var search = $(this).val();
$.ajax({
method: 'POST', //
url: 'farm.php',
data: {'search' : search},
success: function(data){
alert(data);
}
});
});

ajax call not getting executed in php

I m sending some checkbox which are selected,their value to next php page with ajax call.but in the above code i m not able to send it to ajax call
code is as below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
<form name="searchForm">
<input type="checkbox" name="services" value="twic" />TWIC
<br/>
<input type="checkbox" name="services" value="enclosedTrucking" />Enclosed Trucking
<br/>
<input type="checkbox" name="services" value="flatBedTrucking" />Flat Bed Trucking
<br/>
<input type="submit" id="btnSubmit" value="Submit" />
</form>
<div id="results">
</div>
</body>
</html>
In above code.When i select checkboxes from page,and on click of submit.i want to pass them to next php page with ajax call.but its not going to next page and no response is coming back....
Please help guysss
ajaxphp page
<?php
include('connection.php');
$query=$_GET['query'];
echo $query;
$countsql='SELECT * FROM XML';
$countsql1=mysql_query($countsql);
$numrows = mysql_num_rows($countsql1);
$countArray2=array();
print($countsql);
while($row = mysql_fetch_array($countsql1)) {
// Append to the array
$countArray2[] = $row;
//echo $row['PID']."<BR />";
}
?>
<?php
foreach($countArray2 as $array)
{
?>
<div class="search">
hi
</div>
<?php $i++; } ?>
data: "query=" + queryString, is wrong because the "query=" + is a syntax error. It should be:
var queryString = "os="+os+"&ser="+ser;
and then
data : queryString,
Or you can format it like:
data : {
'ser' : ser,
'os' : os
}
Then there is the fact that your Ajax is using POST but you're trying to read the request with $_GET rather than $_POST or $_REQUEST in your PHP.
You can try with these two amends:
var data : "?ser=" + ser; // put '?' instead of '&'
Or more jQuery way:
data : { ser : ser },
And you are missing the dataType in your ajax:
dataType : 'html',
On the php side, as this is a post request, so you have to put this:
$query=$_POST['ser'];
Maybe you're forgetting to prevent the Submit button default behavior:
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (evt) {
evt.preventDefault();
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>

Categories

Resources