Is it possible to pass data in aray using AJAX/JSON? Like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."?
This is the sample code.
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
echo "<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
I understand that this can work using AJAX, but I don't know how to set it up for array that is only separated with ":"
<script>
$(document).ready(function() {
$("#accounttype").change(function() {
var accounttype = $(this).val();
if(accounttype != "") {
$.ajax({
url:"earnings_amendment-employee_select_title.php",
data:{accounttitleselector:accounttype},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#accounttitleselector").html(resp);
}
});
}
else {
$("#accounttitleselector").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Thank you.
Add the row data in new array results and return the results in json format using json_encode
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
$array[] ="<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
echo json_encode($array);
In jquery after ajax success parse the response with JSON.parse(), and the data becomes a JavaScript object.
//use each loop to get the option data from response
success:function(response) {
var data = JSON.parse(response);
$("#accounttitleselector").html($.each(data, function(index, value) {
value
}))
}
});
Related
I'm trying to fill a select box in a HTML page using json and PHP, but when I click over the select box it just return a blank option. Whats is wrong?
HTML code:
Choose a problem:
<select name="notification" id="notification" class="form-control">
<option value="00">Select...</option>
</select>
PHP code:
header('Access-Control-Allow-Origin: *');
include 'dbconfig.php';
try{
$results = $DB_con->prepare("SELECT idproblema, tipoproblema FROM problema ORDER BY idproblema");
$results->execute();
$res = $results->fetchAll(PDO::FETCH_ASSOC);
$hold = array();
foreach($res as $reg){
$hold[] = array('idproblema' => $reg['idproblema'], 'tipoproblema' =>$reg['tipoproblema']);
}
}
catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}
echo json_encode($hold);
Jquery code:
$(document).ready(function(){
jQuery.support.cors = true;
$('#notification').click(function(){
$.ajax({
url : 'url.php',
type : 'GET',
data : "json",
crossDomain: true,
success: function (data) {
if (data.length > 0) {
$.each(data, function (index, value) {
$('#notification').append('<option value="' + value.idproblema+ '">' + value.tipoproblema + '</option>');
});
}
else {
var newOption= $('<option value=""></option>');
$('#notification').append(newOption);
}
}
});
});
})
...............................................
You need to add before echo in php
....
header('Content-type: application/json');
....
As jQuery $.ajax set to accepting json data -- you return just text at the moment
I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);
i am trying to get the data which is in array, from an SQL query to the ajax success data. Here is the code i tried,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
now in the php method which is requested from the above ajax call, i have to get the data return by this function which is returning an array
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
here $row is returning an array as data to the ajax function, where i need to get all the items seperately. Some one help me out to get the values into the ajax call. Thanks in advance..
In your PHP file, you can return your array as a json object in the following way (notice how the PHP file echos the result to pass it back to javascript)
...
$json = json_encode($row);
echo $json
Now add the following to your javascrip ajax
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
You can handle the java script variable 'data' as an associative array like it was in PHP
also, look how you populate the php variable $row and adjust the following way:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
in javascript you can access your rows the following way in teh data variable:
var value = data[0]['field_name'];
in the above statement, 0 will correspond to the value of $cnt (i.e. mysql returned row number)
return $row;
replace like this
echo json_encode($row);
and add dataType='json' in ajax like this
dataType: 'json',
If you want get the value in ajax call i think it shoul be :
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;
I am trying to populate a selected menu when the page is created but there are no options that show.
$(document).ready(function() {
$.ajax('patientlist.php', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + data[i].patient_lastname + '</option>';}
$('#patientselect').append(html);
});
});
my patientlist.php
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname` FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo json_encode( $data );
}
My result from the php page
[{"patient_id":"9","patient_firstname":"Adam","patient_lastname":"Steve"}] etc...
Really appreciate any help, been stuck on this for a week!
So, posting again.
First of all, you should put the echo json_encode( $data ); out of your while loop
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode( $data );
Second, your $ajax syntax isn't correct, change this to $.post and tell the $.post request you are expecting a 'json' response from patientlist.php
$(document).ready(function() {
$.post('patientlist.php', {}, function(data){
/* code */
}, 'json'); // <= set data type json here
});
When retrieving a valid json string, you can iterate over data by using the $.each method
$.each(data, function(index, patient) {
console.log(patient.patient_id); // or use patient['patient_id']
});
At least you will now receive a valid request.
Noticing your HTML, do not use .append if it is not a DOM element, you are just building html elements as a string, so use instead
$('#patientselect').html(html);
below is my $.ajax call to php
$(document).ready(function() {
$('ul.sub_menu a').click(function(e) {
e.preventDefault();
var txt = $(this).attr('href');
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#container').fadeOut('8000', function (){
$('#container').html(data);
$('#container').fadeIn('8000');
});
}
});
});
});
my php code
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
echo $row['img'];
}
}
I m getting this output
images/man/caps/army-black.pngimages/man/caps/army-brown.pngimages/man/caps/army-grey.pngimages/man/caps/army-lthr.pngimages
these are basically image paths now how to loop over them in jquery and fit each image in image tag
any code will be useful
Plz Note I DONT NEED JSON
regards sajid
JSON is probably your best bet here. In PHP do something like this:
$ret = array();
while( $row = mysql_fetch_assoc( $result ) )
{
$ret[] = $row['img'];
}
echo json_encode( $ret );
This will output something like the following
["image1","image2","image3"]
jQuery has a function which can convert this information into a javascript array. So put this code in your success callback.
var result = jQuery.parseJSON( data );
alert( result[1] );
EDIT: A method which does not use JSON
In PHP place each image url on a separate line
echo $row['img'], "\n";
Then in javascript, split the response by the new line character
var result = data.split( "\n" );
simply change your php code:
`if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
echo ""<img src='".$row['img']."' /><br />";
} }