I'm having some issues displaying an array which I created in a PHP file. The response data in question is data["vessel"]
I have some jQuery:
j$('select[name=vessel]').change(function(e) {
var tour_ID = j$('select[name=tour]').val();
var trip_Date = j$('input[name=trip_Date]').val();
var data = {
"action": "Count_Vessels",
"trip_Date": trip_Date,
"tour_ID":tour_ID
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
//console.log("vessel stack: " + data["vessel"][0]);
var arr=JSON.parse(data["vessel"]);
console.log("vessel stack: " + arr[0]);
console.log("Form submitted successfully.\nReturned json: " + data["json"]);
},
error: function (request) {
console.log(request.responseText);
}
});
});
The PHP:
function count_Vessels(mysqli $conn, $trip_Date, $tour_ID){
$return = $_POST;
$vessel_Stack = array();
$vessel_Query = "SELECT * FROM Vessel";
if(!$vessel_Results = $conn->query($vessel_Query)){
die('There was an error running the query [' . $conn->error . ']');
}
while( $vessel_Row = $vessel_Results->fetch_assoc() ){
$vessel_Stack[$vessel_Row['ve_ID']] = $vessel_Row['vessel_Name'];
}
$return['vessel'] = $vessel_Stack;
$return["json"] = json_encode($return);
echo json_encode($return);
}
when I display data["json"] in console, I get Returned json: {"vessel":{"1":"Thriller","2":"Jammin","3":"Thunderstruck","4":"Wildthing","6":"Joyride"}
Which is awesome, but I don't know how to do that using the data["vessel"] Any help would be greatly appreciated.
I solved my own riddle. Because data["vessel"] is an array, I had to loop through it. Doing so like this worked:
j$.each(data["vessel"], function(key, val) {
console.log('index ' + key + ' value ' + val);
});
Related
So far I do not see how to use solutions posted from my search of "ajax php create associative array then return sql results" - need help: my submit button calls jQuery.ajax that posts select data to a PHP url; then my retriever.php file [msSQL] queries a table and returns multiple records. I want to then return the array back to my jQuery.ajax success function, and parse the returned data - and populate rows of a DataTables HTML table. here is the jQuery.ajax from caller.php:
jQuery('#submit').click(function() {
jQuery.ajax({
url: "https://domain/projects/current/retrieve.php",
//contentType: "application/json",
data: {fy: jQuery('#fy_select').val(), lpid: jQuery('#lp_select').val(), next_year: jQuery('#fy_select').val()+1 },
//dataType: "json",
type: 'post',
success: function(data, XMLHttpRequest){
//alert(data.length);
//alert(JSON.parse(data));
//alert(data[0]);
//jQuery('#activity').text("[" + JSON.parse(data)[0] + "] " + JSON.parse(data)[1]);
jQuery.each(data, function () {
jQuery('#activity').text("[" + JSON.parse(data)[0] + "] " + JSON.parse(data)[1]);
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
pardon comments i left in my code, for if you see something i've tried that can be salvaged let me know; otherwise i hope they are not distracting. i simply need to query the db and get results, stuff them into an array and return it to ajax, then parse the activity, name from the sql result. now the retrieve.php code. thx in advance as always!:
<?php
include(MSS_DB);
//get vars from jQuery .ajax post - lpid and fy:
if ($_POST['lpid'] != null && $_POST['fy'] != null ){
$lpid = $_POST['lpid'];
$fy = $_POST['fy'];
$next_year = $_POST['next_year'];
$fund_info_get = "select activityid, name from activity_table where office= " . $office . " and approveddate > '" . $fy . "-06-30' order by activityid desc";
$get_fund_result = mssql_query($fund_info_get);
$data_array = array();
//$data_array = mssql_fetch_array($get_fund_result);
while($row = mysql_fetch_assoc($get_fund_result)){
$data_array = array('activity_id' => '$row['activityid']', 'activity_name' => '$row['name']');
//$data_array [] = $row; //tried this from another post.
}
$rowcount=mssql_num_rows($get_fund_result); //for alexander this returns 11, correct.
/*while($row = mysql_fetch_array($get_fund_result)){
$table_data[]= arrsay("id=>" = '"$row['activityid']"', "name=>" = '"$row['name']"');
}*/
//$result = "lpid/fy/next_year/get_fund_result: " . $lpid . "/" . $fy . "/" . $next_year . "/" . $fund_info_get . "";
}else{
// either of the values doesn't exist
$result = "No Data Was Sent !";
}
//echo $rowcount;
//echo json_encode($table_data);
//echo $data_array;
echo json_encode($data_array);
//echo $result;
thx, All for Your input! it helped me go forward. a brief description of my solution might help you see how each of you helped:
goal: jQuery.ajax calls someurl.php, gets mssql query data into an array, returns the json_encode array. back in jQuery.ajax success, parse through the json data. here are the operative features of each file to show the solution:
callerfile.php:
jQuery('#submit').click(function() {
jQuery.ajax({
url: "https://fabrik.smartstartinc.net/ncpcphp/activity-mgmt2.0/porc_get_activities.php",
data: {fy: jQuery('#fy_select').val(), lpid: jQuery('#lp_select').val(), next_year: jQuery('#fy_select').val()+1 },
dataType: "json",
type: 'post',
success: function(data, XMLHttpRequest){
console.log(data); //shows json: [{"activity_id":11111,"activity_name":"Community Cleanup"}, etc
jQuery.each(data, function(index, value){
console.log(data[index].activity_id);
console.log(data[index].activity_name);
//these show the id, the name.
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
the PHP file that returns the json array, retrieve.php:
$fund_info_get = "select activityid, name from cpy_activity where lpid= " . $lpid . " and approveddate > '" . $fy . "-06-30' order by activityid desc";
$get_fund_result = mssql_query($fund_info_get);
$data_array = array();
while($row = mssql_fetch_assoc($get_fund_result)){
$data_array[] = array('activity_id' => $row['activityid'], 'activity_name' => $row['name']);
}
}else{
// either of the values doesn't exist
$result = "No Data Was Sent !";
}
echo json_encode($data_array);
once i used JSON.stringify and saw format of the data, i was able to start drilling into how to display it. thx again!
I try to get some data from my MySql db. I have 2 files:
// client/book.js
$(document).ready(function () {
$("#btnJSonDB").bind("click", function () {
var request = $.ajax({
url: "book.php",
type: "GET",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
console.log(result);
}
}); //end ajax
request.fail(function( jqXHR, textStatus ) {
console.log("Request failed: " + textStatus);
});
}); //end click
}); //end ready
and server side:
// server/book.php
$db = new mysqli(DATA_HOST,DATA_UTENTE,DATA_PASS,DATA_DB );
$select = "SELECT * FROM bk_book";
$strJSon = "{\"book\":{}}";
$query = #mysqli_query($db,$select);
if( $query ) {
$result = [];
while($result[] = mysqli_fetch_array($query, MYSQLI_ASSOC));
#mysqli_close($db);
$strJSon = "{\"book\":" . json_encode($result) . "}";
}
echo $strJSon;
I try in my localhost space (windows-xampp) and all it's ok, In meteor I recive an error message:
Parse error
I try to comment datatype (json problem?) and I see the html page without my data.
The result is a correct json format:
{
"book":[
{
"nrent":"xxxxxx",
"start_date":"2017-01-05",
"end_date":"2017-01-12",
"user_ID":"15",
"booking_status":"estimate",
"note":"",
"adults_numb":"0",
"children_numb":"0",
"booking_bill":"630.00",
"name":"Camera Bi",
"first_name":"dddd",
"last_name":"ddd",
"mail":"dddd#dddd.it",
"telephone":"ddddddd"
},
{
"nrent":"fffff",
"start_date":"2017-01-08",
"end_date":"2017-01-27",
"user_ID":"25",
"booking_status":"active",
"note":"",
"adults_numb":"2",
"children_numb":"0",
"booking_bill":"1710.00",
"name":"Camera Ba",
"first_name":"pippo",
"last_name":"puppo",
"mail":"fff#pippfffo.it",
"telephone":"ffffff"
},
{
"nrent":"aaaaa",
"start_date":"2017-01-28",
"end_date":"2017-02-01",
"user_ID":"24",
"booking_status":"estimate",
"note":"",
"adults_numb":"0",
"children_numb":"0",
"booking_bill":"380.00",
"name":"Camera Ba",
"first_name":"ffff",
"last_name":"wwww",
"mail":"no#email.it",
"telephone":""
},
null
]
}
I try the https://jsonformatter.curiousconcept.com/ and is correct
$db = new mysqli(DATA_HOST,DATA_UTENTE,DATA_PASS,DATA_DB );
$select = "SELECT * FROM bk_book";
$jsonObject = new stdclass();
$query = #mysqli_query($db,$select);
if( $query ) {
$result = [];
while($result[] = mysqli_fetch_array($query, MYSQLI_ASSOC));
#mysqli_close($db);
$jsonObject->book = $result;
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($jsonObject);
I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.
I need to extract the URL's from the php datas, how can i achieve this?
PHP
$query = 'SELECT * FROM picture LIMIT 3';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url.=$rec['pic_location'].";";
}
echo json_encode($url);
Ajax
<script type="text/javascript">
$(document).ready(function() {
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first: " + arr[0] + ", second: " + arr[1]);
alert(arr[0]);
$(".theImage").attr("src", +arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
the alert message isn't working its just printing H T ( i think these are http://... )
You're returning a string which is not parsed as JSON.
Just add dataType: "json" to the ajax settings.
And since you're reading it as an array in your javascript you should return it like so:
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
You are sending a string in your PHP and expecting an array as response in javascript. Change you PHP to
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
And javascript to
$.ajax({
url: "viewnew.php",
dataType: "JSON",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret[0]);
var arr = ret;
alert(arr);
alert("first: " + arr[0] + ", second: " + arr[1]); // THIS IS NOT WORKING!!!!
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
A friend of mine had given me this snippet for a js file that can be useful for me:
$.ajax({
type: "POST",
url: "../CheckPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var res = response.d;
if (res == true) {
jAlert('Patient Name already exists!', 'Error');
return;
}
else {
$.ajax({
type: "POST",
url: "../NewPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "','gender':'" + _gender + "','birthDate':'" + _bday + "','ssn':'" + _ssn + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var _id = response.d;
if (_id.length != 0) {
$('#patientName').removeAttr('disabled');
$('#patientName').val(_lname + ", " + _fname + " " + _mname);
$('#patientId').val(_id[0].patientID);
$('#dateOfBirth').val(_bday);
$('#referringDoctor').removeAttr('disabled');
$('#referringDoctor').focus();
$('#patientAge').val(_id[1]);
$('#ptLastName').val('');
$('#ptFirstName').val('');
$('#ptMiddleName').val('');
$('#ptGender').val('');
// $('input[name="birthdate"]').val(); // $('#ptBirthDate').val();
$('#ptSSN').val('');
}
// if (_id == true) {
// }
insertCallback(_id);
// $('#diagnosis tbody>tr:last').attr('dinfo', '_IEDiagnosis|' + _id);
},
failure: function (msg) {
alert(msg);
}
});
}
}
});
I'm using PHP but I'm new to using JSON. Is there a way to return a true value for "response.d" in my PHP file:
success: function (response) {
var _id = response.d;
}
Here's my logic but don't know the code to use:
$lastname = isset($_REQUEST['lastName'])?$_REQUEST['lastName']:'';
$firstname = isset($_REQUEST['firstName'])?$_REQUEST['firstName']:'';
$middlename = isset($_REQUEST['middleName'])?$_REQUEST['middleName']:'';
$response = array();
mysql_connect ("localhost", "root") or die ('Error: ' . mysql_error());
mysql_select_db ("healthpal");
$query = "SELECT Lastname, Firstname, MiddleName FROM db_patients WHERE Lastname = '$lastname' || Firstname = '$firstname' || MiddleName = '$middlename'";
$qrytest = mysql_query($query);
if (isset($qrytest)) {
//"response.d" will be true if the query return not NULL
}
Try something like this:
header('Content-type: application/x-json');
echo json_encode( array( 'd' => true ) );
What you need is the php json_encode function:
json_encode(array('response'=>'true')));
You have to construct JSON string in your PHP file, some thing like this
{"result":"true"}
this constructed JSON string should return as PHP response. In Javascript parse the JSON as,
var obj = eval(response)
if(obj.result == 'true'){
//Do your code here
}