Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,153,361 members, 7,819,303 topics. Date: Monday, 06 May 2024 at 02:01 PM

Help! Cannot Get Json Array Into Input Field - Jquery - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Help! Cannot Get Json Array Into Input Field - Jquery (2697 Views)

Programming Challenge: Convert String to Json with a Loop / List Of All States With Local Governments In Nigeria In JSON, PHP And SQL Format / Android Quiz Application With Json Parser, Php And Mysql Database (2) (3) (4)

(1) (Reply) (Go Down)

Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 5:29pm On Jun 05, 2015
Hello guys,

Please am having some difficulty in getting encoded json array into the input field in jquery.

I used
$("input#no"wink.val(data.result['no']);
$("input#no"wink.html(data.result['no']);
$("input#no"wink.text(data.result['no']);


to no avail.

Looking at the pictures below, i used firebug to step in through the code to no avail.

Please kindly look at the picture below and please make suggestions.

thanks

Re: Help! Cannot Get Json Array Into Input Field - Jquery by Adesege(m): 6:17pm On Jun 05, 2015
Please paste the code from
success: function(){ ... }
This will enable me to understand how you came about data.result['no'].
Re: Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 7:23pm On Jun 05, 2015
Adesege:
Please paste the code from

success: function(){
...
}

This will enable me to understand how you came about data.result['no'].


Ok do you mean the php or jquery? well if i understand your statement, here it is again

Re: Help! Cannot Get Json Array Into Input Field - Jquery by Adesege(m): 8:09pm On Jun 05, 2015
Paste and not screenshot.

uvalued:


Ok do you mean the php or jquery? well if i understand your statement, here it is again
Re: Help! Cannot Get Json Array Into Input Field - Jquery by JackOfAllTrades: 8:13pm On Jun 05, 2015
Try parsing the data with JSON.parse();
Re: Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 11:39pm On Jun 05, 2015
Adesege:
Paste and not screenshot.

ok
$(document).ready(function () {
$('#no').keyup(function () { //keyup event responds
var loc = $('#no').val();

$.ajax({
dataType: "json",
url: "/php/barry.php",
data: ({
loc: loc
}),
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {

$.each(data.result, function () {
$("input#no"wink.val(data.result['no']);
$("input#name"wink.val(data.result['name']);
});




//this is end of success
}
});
});
});


PHP

<?php
include_once('/db.php');
if(isset($_GET['loc'])){

$fille = $_GET['loc'];
//echo "this is $fille";
//exit;

//$fille = '0000';
$sql = "SELECT * FROM barry where no='$fille'";
$res = mysql_query($sql);
$result = array();
while( $row = mysql_fetch_array($res) )
array_push($result, array('no' => $row[0],
'name'=> $row[1]
)
);
//print_r($result);
echo json_encode(array("result" => $result));
}


Thanks
Re: Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 11:59pm On Jun 05, 2015
JackOfAllTrades:
Try parsing the data with JSON.parse();
thanks for the suggestion, but i have already set the dataType:"json" which will parse it. Tried it anyway and it gave me null when i alerted it.
Re: Help! Cannot Get Json Array Into Input Field - Jquery by JackOfAllTrades: 12:47am On Jun 06, 2015
uvalued:

thanks for the suggestion, but i have already set the dataType:"json" which will parse it. Tried it anyway and it gave me null when i alerted it.
it gives you null because your php script is not outputting anything, you need to add this in the php after the while loop

print_r( json_encode($result) );

Setting data type to json in JQuery doesn't automatically parse it to json unless you set the MIME response of the server to application/json
Then the JQuery success callback will return a JavaScript object
Add this line in the beginning of your php script to set mime of the php script
header('Content-type: application/json');

I think firebug is printing the json string instead of the object and that's why you should parse it
Re: Help! Cannot Get Json Array Into Input Field - Jquery by Adesege(m): 1:56am On Jun 06, 2015
IMHO, you've taken it too far. In your php, edit the sql statement. Instead of selecting all the columns in the table, be specific. I.e SELECT no, name FROM your_table blah blah.

The while loop will not be neccessary if the column type for no is unique. But in this case, i'll assume it's not unique.

While you are fetching, replace the statement inside the while loop with

$data[]=array_map('utf8_encode', $row);

Close the while loop. Replace your json_encode echo statement with

echo json_encode($data);

Having done this, save the page and visit the page on your browser, start typing something into the input form. Check your console, and you should see something like

{{ ...some data }}

Don't worry if you don't see that. I just realized there are alot of bug in your code. But i'll address that at the end of this.

Assume you saw the {{ ...some data }}, this implies that the json is nested. This is so because of the $data[]=...

In your Jquery, starting from the each control structure, delete everything till the last closing braces.

To access your values, you'll type

$('input#no"wink.val(data[0].no);

$('input#name"wink.val(data[0].name);

So this is everything in one.

$(document).ready(function () {
$('#no').keyup(function () { //keyup event responds
var loc = $('#no').val();
var dat='loc='+loc;
$.ajax({
dataType: "JSON",
url: "/php/barry.php",
data: dat,
async: false,
global:false,
type: "POST",
success: function (data) {
$("input#no"wink.val(data[0].no);
$("input#name"wink.val(data[0].name);
//this is end of success
},
error: function(xhr,ajaxOptions, thrownError){
alert(xhr.status+" "+thrownError);
}
});
});
});

PHP

<?php
include_once('/db.php');
if(isset($_POST['loc'])){
$fille = $_POST['loc'];
//echo "this is $fille";
//exit;
//$fille = '0000';
$sql = "SELECT no,name FROM barry where no='$fille'";
$res = mysql_query($sql);
while( $row = mysql_fetch_array($res) ){
$data[]=array_map('utf8_encode', $row);
}
//print_r($data);
echo json_encode($data);
}
?>

Endeavour to validate user input please.

Let me know if it helps
uvalued:

.
Re: Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 10:20am On Jun 06, 2015
JackOfAllTrades:
it gives you null because your php script is not outputting anything, you need to add this in the php after the while loop

print_r( json_encode($result) );

i did it and this is the result [First Image]

JackOfAllTrades:

Setting data type to json in JQuery doesn't automatically parse it to json unless you set the MIME response of the server to application/json
Then the JQuery success callback will return a JavaScript object
Add this line in the beginning of your php script to set mime of the php script
header('Content-type: application/json');

I think firebug is printing the json string instead of the object and that's why you should parse it

I did add the header and it gave the [first image] below. On the firebug, look at the Second image, it shows the array has been captured after success: (function). However it still did not send it to the input field [no and name].

Re: Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 10:38am On Jun 06, 2015
Adesege:
IMHO, you've taken it too far. In your php, edit the sql statement. Instead of selecting all the columns in the table, be specific. I.e SELECT no, name FROM your_table blah blah.

The while loop will not be neccessary if the column type for no is unique. But in this case, i'll assume it's not unique.

While you are fetching, replace the statement inside the while loop with

$data[]=array_map('utf8_encode', $row);

Close the while loop. Replace your json_encode echo statement with

echo json_encode($data);

Having done this, save the page and visit the page on your browser, start typing something into the input form. Check your console, and you should see something like

{{ ...some data }}

Don't worry if you don't see that. I just realized there are alot of bug in your code. But i'll address that at the end of this.

Assume you saw the {{ ...some data }}, this implies that the json is nested. This is so because of the $data[]=...

In your Jquery, starting from the each control structure, delete everything till the last closing braces.

To access your values, you'll type

$('input#no"wink.val(data[0].no);

$('input#name"wink.val(data[0].name);

So this is everything in one.

$(document).ready(function () {
$('#no').keyup(function () { //keyup event responds
var loc = $('#no').val();
var dat='loc='+loc;
$.ajax({
dataType: "JSON",
url: "/php/barry.php",
data: dat,
async: false,
global:false,
type: "POST",
success: function (data) {
$("input#no"wink.val(data[0].no);
$("input#name"wink.val(data[0].name);
//this is end of success
},
error: function(xhr,ajaxOptions, thrownError){
alert(xhr.status+" "+thrownError);
}
});
});
});

PHP

<?php
include_once('/db.php');
if(isset($_POST['loc'])){
$fille = $_POST['loc'];
//echo "this is $fille";
//exit;
//$fille = '0000';
$sql = "SELECT no,name FROM barry where no='$fille'";
$res = mysql_query($sql);
while( $row = mysql_fetch_array($res) ){
$data[]=array_map('utf8_encode', $row);
}
//print_r($data);
echo json_encode($data);
}
?>

Endeavour to validate user input please.

Let me know if it helps

PHP
Yes it did help as i was able to do some correction. However, on running the php code you posted separately, it gave this result of the encoded array [First Image).

AJAX
After success:function, it did not display any argument as you can see from the second image.

Running previous AJAX after modifying it according to your suggestions, i discovered that the arguments [json array] from PHP was showing the values. Third image . But still it did not transfer the result into the INPUT fields on the main page.

Thanks for your suggestion.

Re: Help! Cannot Get Json Array Into Input Field - Jquery by JackOfAllTrades: 11:06am On Jun 06, 2015
@op i just tested your code it appears if you remove the dataType and ContentType options it runs fine
Re: Help! Cannot Get Json Array Into Input Field - Jquery by Adesege(m): 11:14am On Jun 06, 2015
Datatype is needed.

JackOfAllTrades:
@op i just tested your code it appears if you remove the dataType and ContentType options it runs fine
Re: Help! Cannot Get Json Array Into Input Field - Jquery by Adesege(m): 11:20am On Jun 06, 2015
Gotcha! I'll advice you use the php code i gave you instead of yours cos from the var_dump of your php code, you'll agree with me that your json decoded array is three steps deep. Though, that doesn't pose a problem, but it's advisable.

The problem why it's not showing in your input form is cos of your selector.

Try something like

$('input[id="no"]').val(...);

or

$('#no').val(...);

You can check the jQuery documentation for list of selectors. There are a bunch of them.

Peace!
Re: Help! Cannot Get Json Array Into Input Field - Jquery by JackOfAllTrades: 11:23am On Jun 06, 2015
Adesege:
Datatype is needed.

JQuery always perform intelligent guess in ajax response once the server set it to application/json it will return a JavaScript object other wise it will return a string of the response, so data type can be optional
Re: Help! Cannot Get Json Array Into Input Field - Jquery by Adesege(m): 11:25am On Jun 06, 2015
That's true but from the php code over there, you'll agree me that there is no header to force php to render it in json. That's the php json header.

So it's advisable he leaves it as it is.

JackOfAllTrades:

JQuery always perform intelligent guess in ajax response once the server set it to application/json it will return a JavaScript object other wise it will return a string of the response, so data type can be optional
Re: Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 11:40am On Jun 06, 2015
Thanks guys i did as you recommended and voila its running great.


thank you all for your quick and wise response.

Its most appreciated.

Re: Help! Cannot Get Json Array Into Input Field - Jquery by JackOfAllTrades: 11:52am On Jun 06, 2015
So what did you do differently?
Re: Help! Cannot Get Json Array Into Input Field - Jquery by Adesege(m): 12:00pm On Jun 06, 2015
Please post what worked and went wrong for future reference
uvalued:
Thanks guys i did as you recommended and voila its running great.


thank you all for your quick and wise response.

Its most appreciated.

2 Likes

Re: Help! Cannot Get Json Array Into Input Field - Jquery by uvalued(m): 1:36pm On Jun 06, 2015
Sure guys.

this is what i did different from my earlier mistake



document.getElementById(no).value = data.result[0].no;
document.getElementById(name).value = data.result[0].name;



this worked the magic

1 Like

(1) (Reply)

Help Fix This Android Studio Error Dhtml18 And Otherd / I Need An Angular Js Developer to partner with me on a project / Foodfrik (A professional food listing Platform)

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 46
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.