I am trying to create a drop down list using jQuery, PHP and mySQL, here is my code thus far,
HTML:
<select id="box"></select><br />
<input id="button" type="button" value="populate" />
Javascript/jQuery:
$(document).ready(function() {
$("#button").click(function (){
$.getJSON("test_post.php", function(data){
$.each(data, function(user) {
$('#box').append(
$('<option></option>').html(user)
);
});
});
});
});
PHP:
mysql_connect('localhost', 'user', '1234');
mysql_select_db('json');
$test = mysql_query('SELECT user,pass FROM login WHERE user="john"');
while($row = mysql_fetch_array($test, true)) {
$data .= json_encode($row);
};
echo $data;
I have 3 entries in the database, and when I run the 'test_post.php' file, it echoes out the JSON, but when I try and get it to populate the drop down, nothing happens!
Any idea why?
Try taking json_encode out of while loop and encoding it at the end. Like this:
while($row = mysql_fetch_array($test, true))
{
$data[] = $row;
}
$data = json_encode($data);
echo $data;
[EDIT]: After OP comment:
If you just want the name of the user in the drop down, then do it like this:
while($row = mysql_fetch_assoc($test))
{
$data[$row['user']] = $row;
}
$data = json_encode($data);
echo $data;
There are several problems in your code.
First: attempt to use undefined variable $data, you should have initialized it to an empty string before while loop: $data = '';, otherwise this can send PHP notice with the JSON response, depending on values of display_errors and error_reporting settings.
Second: as #shamittomar said, $data must be an array and json_encode() must be called only once for the whole array. For now, you're sending several JSON objects concatenated to a single string, which is wrong.
Third: value of the user function parameter in the JavaScript is actually an index of the data array, not a value, but even if user would be a value, it would be a JavaScript object with user and pass properties, not a string.
Resulting code should be (changed parts only):
PHP
$data = array();
while ($row = mysql_fetch_array($test, true)) {
$data[] = $row;
};
echo json_encode($data);
JavaScript
$.each(data, function(i, user) {
$('#box').append(
$('<option></option>').html(user.user)
);
});
Have you tried validating the JSON?
jQuery is quite picky about it's JSON: it needs to validate correctly, no comments and the right content-type!
Try adding the following in your PHP to see if it helps (I always do this)
header('Content-type: application/json');
First of all check mysql connection code is ok?
mysql_connect('localhost', 'user', '1234');
Updated php code as below,
mysql_connect('localhost', 'user', '1234');
mysql_select_db('json');
$test = mysql_query('SELECT user,pass FROM login WHERE user="john"');
while($row = mysql_fetch_array($test, true)) {
$data['pass '] = $row['pass'];
$data['user'] = $row['user'];
};
echo json_encode($data); die();
Javascript code:
$("#button").click(function (){
$.getJSON('getDropdownData.php', '',function(data){
$("#box").remove();
$('<option />', {value: '', text: 'Select option'}).appendTo("#box");
$.each(data,function(key, value){
$('<option />', {value: key, text: value}).appendTo("#box");
});
});
});
Then you will get a dorpdown with pass as "option value" and user as "option text".
Related
Edit:
I can output the table now but the strange thing is, trying to parse the JSON returned from PHP using JS or jQuery methods results in skipping all remaining lines in the debugger with zero output to the browser. Where as not parsing and using it to construct at table works.
Also, trying to .append() the JSON using the parse methods or not to a ` does not work.
I'm so confused right now.
Anyways, the jQuery that worked looks like this making a .post() request, notice I added the 'json' fourth parameter although it might work without it.
$(document).ready(function(){
$('#disease_btn').click(function(){
showDisease();
});
});
function showDisease(){
//var disease = $("#disease-dropdown:selected").text();
//var disease = $("#disease-dropdown:selected").val();
var disease_dropdown = document.getElementById("disease-dropdown")
var disease = disease_dropdown.options[disease_dropdown.selectedIndex].text;
var controller = 'controller.php';
$.post(controller, //url, data, callback, dataype=Json
{
page: 'SpaPage',
command: 'search-disease',
search_term: disease
},
function(disease_json, status){
//#search-results display table
//var disease_obj = JSON.parse(disease_json); this did not work
//var disease_obj = jQuery.parseJSON(disease_json); //this did not work
var disease_obj = disease_json;
//$('#test-out').append(disease_obj); /this did not work
var table = $.makeTable(disease_obj);
$('#search-results').append(table); //this worked!
}, 'json');
//https://stackoverflow.com/a/27814032/13865853
$.makeTable = function(disease_obj){
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var h in disease_obj[0]) tblHeader += "<th>" + h + "</th>";
$(tblHeader).appendTo(table);
$.each(disease_obj, function(index, value){
var tblRows = "<tr>";
$.each(value, function (key, val){
tblRows += "<td>" + val + "</td>";
});
tblRows += "</tr>";
$(table).append(tblRows);
});
return ($(table));
}
};
That table code I mimicked what I saw here: https://stackoverflow.com/a/27814032/13865853
I sort of get it but still not crystal clear on all of it. I guess it's outputting HTML so I can throw in a class for the table to take advantage of bootstrap.
On the PHP side I do this:
case 'search-disease':
$matches_arr = [];
$disease = $_POST['search_term'];
$matches_arr = search_disease($disease);
//todo: decide to use session or returned arr
if(isset($_SESSION['disease-matches_arr'])){
$matches_arr = $_SESSION['disease-matches_arr'];
}
if(count($matches_arr) > 0) {
//jsonify array here to send back
//https://stackoverflow.com/a/7064478/13865853
//https://stackoverflow.com/a/58133952/13865853
header('Content-Type: application/json');
$disease_json = json_encode($matches_arr);
echo $disease_json;
exit;
}
and then the model.php interaction with database looks like this:
function search_disease($disease_option){
// search DB for substring of question
//add results to an array of strings
//return array of strings or empty array
//
$user_id = -1;
$matches_arr = array();
$sql = "SELECT * FROM diseases
WHERE disease LIKE '%$disease_option%'";
$result = mysqli_query(Db::$conn, $sql);
if (mysqli_num_rows($result) > 0) {
//iterate
while($row = mysqli_fetch_assoc($result)){
//get username
$disease = $row['disease'];
$food = $row['food'];
$en_name = $row['en_name'];
$health_effect = $row['healthEffect'];
$metabollite = $row['metabollite'];
$citation = $row['citation'];
$next_row = array("Disease"=>$disease, "Food"=>$food,
"Name"=>$en_name, "Health Benefits"=>$health_effect, "Metabollite"=>$metabollite,
"Sources"=>$citation);
$matches_arr[] = $next_row;
}
}
$_SESSION['disease-matches_arr'] = $matches_arr;
return $matches_arr;
//https://stackoverflow.com/questions/1548159/php-how-to-sen
So I set a session variable and also return it, still have to decide which way but they are both working.
My questions still remaining are:
Why do the parse methods cause this strange behavior?
How can I just output the JSON to a testing <div>?
If you have to return data from PHP to javascript you must have use json_encode() if data type is array otherwise just return.
To take action with array type data by javascript you have to decode this json data by JSON.parse() function.
Array example
$data = array('carname' => 'TOYOTA','model'=>'ARTYIR500');
echo json_encode($data);
exit;
String example
echo 'lorem ipsum is a simple text';
exit;
I am trying to incorporate some ajax into my code, at the moment it works great, when a user clicks a button it sends some hidden inputs to another php script, performs some actions, then sends the result back and outputs it, all updating with no refresh etc.
However, the last part I am trying to send and receive back is a variable that shows some html code, in other words the other variables that are being sent back and outputed are just numbers and letters, where as this one is actual div's, however it is not outputting it, I have tried it without the ajax, when the page first loads and it works great, but doesn't when i try it with the ajax, hopefully the code below will make more sense. The variable I want to be able to send back is $sl_output.
AJAX code on main page
<script>
$(document).ready(function (){
$(".add_detail_land_down").click(function(){
var hidden_count = $('input[name=addon_detail_hidden_count]').val();
var land_required = $('input[name=addon_hidden_land_required]').val();
var sl_array = $('input[name=addon_hidden_shopping_list_array]').val();
var button_tok = "land_down";
$.ajax({
type: "GET",
url: "addon_detail_calc.php",
data: { hidden_count: hidden_count, button_tok: button_tok, land_required: land_required, sl_array: sl_array },
dataType: "json",
success: function (data) {
$("#res_expected_gain").html(data.total_hidden);
$("#output").html(data.output);
$("#res_expected_profit").html(data.land_required);
$("#res_total_supply_time").html(data.test_time);
$("#land_selected_token").html(data.total_hidden);
$("#sl_output_div").html(data.sl_output);
}
});
return false;
})
});
Code in addon_detail_calc.php
<?php
// header('application/json');
$hidden_count = $_GET["hidden_count"];
$button_tok = $_GET["button_tok"];
$land_required = $_GET["land_required"];
$sl_array = $_GET["sl_array"];
$sl_output = "";
if($button_tok == "land_up"){
//MAIN CODE SHALL BE DONE HERE
$hidden_count = $hidden_count + 1;
$test_time = $hidden_count * 66;
$new_sl_array = array();
$final_sl_array = array();
foreach ($sl_array as $columnName => $columnData) {
if($columnName == "0"){
unset($sl_array[$columnName]);
}else{
$new_columnData = $columnData * 54;
$new_sl_array[$columnName] = $new_columnData;
}
}
foreach ($new_sl_array as $columnName => $columnData) {
$sl_output = "";
$sl_output = '<li class="add_detail_content_ele_wrap_ele"><div class="add_detail_content_ele_wrap_ele_header">'.$columnName.'</div><!--end add_detail_content_ele_wrap_ele_header--><div class="add_detail_content_ele_wrap_ele_pic"></div><!--end add_detail_content_ele_wrap_ele_pic--><div class="add_detail_content_ele_wrap_ele_amount">47 Required</div><!--end add_detail_content_ele_wrap_ele_amount--><div class="add_detail_content_ele_wrap_ele_user_amount">You Have 0</div><!--end add_detail_content_ele_wrap_ele_user_amount--></li>';
$final_sl_array[$columnName] = $sl_output;
}
$array_result = implode("", $final_sl_array);
}else{
$hidden_count = $hidden_count;
}else{
$hidden_count = $hidden_count;
}
$output = "";
$output = '<input type="hidden" name="addon_detail_hidden_count" id="addon_detail_hidden_count" class="addon_detail_hidden_count" value="'.$hidden_count.'" />';
include 'connect_to_mysql.php';
echo json_encode(array("total_hidden" => $hidden_count, "output" => $output, "land_required" => $hidden_count, "test_time" => $test_time, "sl_output" => $final_sl_array ));
?>
I guess the question is, can the html code variable being transported be viewed and re-outputed?
EDIT
I have updated my code above, it seems that the first problem, was the foreach loop wasn't handling the right data, i had to shuffle things around and add another array. Because of this i have to put every value in array final_sl_array into a single variable, i have tried to implode this, it worked when i ran it through normal php when the page opens, however, now when i try it through ajax, it is not working, and not returning any result, any ideas why it works for one and not the other?
I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )
I've read multiple similar posts on this, and my code seems to match the suggestions, but still no data returned.
Here's my JS:
$.post('php/get_last_word.php', { user_id : userID },
function( data ) {
currentLanguage = data.language_id;
currentWord = data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
},'json');
And the relevant php:
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$encoded = json_encode($row);
echo $encoded;
}
And the resulting log:
Connected successfully{"language_id":"1","word_id":"1"}
So the json array is being echoed, but it's not ending up in data, because currentLanguage and currentWord are not being populated. Is this a problem with asynchronicity? Or something else?
Make sure you have a valid json coming back to your variable from your PHP script
IF your json object is like this,
{"language_id":"1","word_id":"1"}
You can access the values like this
currentLanguage = data.language_id;
currentWord = data.word_id;
Example JsFiddle http://jsfiddle.net/NuS7Z/8/
You can use http://jsonlint.com/ to verify your jSon is in correct form or not.
Specifying json as the data type value in your post request will make sure the reponse is coming back as json format to the success callback.
$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
currentLanguage = data.language_id;
currentWord = data.word_id;
});
You can also use getJson to simply get json data. getJson is a shorthand of ajax Call with datatype as json
http://api.jquery.com/jQuery.getJSON/
Try changing your JS to:
$.getJSON('php/get_last_word.php', { user_id : userID },
function( response ) {
if (response.success) {
currentLanguage = response.data.language_id;
currentWord = response.data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
} else {
alert('Fail');
}
});
and your PHP to:
<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$success = true;
$data = $row;
}
// I generally format my JSON output array like so:
// Response
header('Content-Type: application/json');
echo json_encode(array(
'success' => $success,
'data' => $data
));
?>
That way its more organized and don't forget to set the content type.
Hope that helps.
i am a noob to jquery and i want to know how to make use of if else for the following:
on the server side there is a if for number of rows is equal to 0 and else some JSON part.
$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
if ($age_num_rows==0)
{
echo "true";
}
else
{
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$abc_output = array('title' => $row['title'],'age' => $row['age']);
}
echo json_encode($abc_output);
}
Now coming to Jquery part :
If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.
$(document).ready(function(){
$("#button1").click(function(){
$.getJSON('script_1.php',function(data){
if (data=='true') {
alert ('hello')
}
else {
$.post('script_1.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
},
"json");
}
});
});
Edited:
$(document).ready(function(){
$("#button1").click(function(){
$.post(
'script.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
var data = JSON.parse(json);
if (data.length === 0){
alert('no data');
}
else{
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
}},
"json"
);
});
});
PHP side
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row= array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}
You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.
For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
echo json_encode($row);
} else {
echo json_encode(array());
}
Back in the JavaScript, you could then do something like this:
var data = JSON.parse(json);
if (data.length === 0) {
alert('no data');
} else {
$("input[name='title']").val(data.title);
$("input[name='age']").val(data.age);
}
jeroen is right though, you only need to use one AJAX call.
There seem to be a few problems:
You are treating the data returned from getJSON as if it is plain
text
The php that you are calling from javascript does not always
return json
You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition
By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.
Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:
$.getJSON('script_1.php',function(data){
to something like:
$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {
and in your php you need to use something like:
$name = mysql_real_escape_string($_GET['id']);