I'm trying to make a PHP echo messages show up whenever users inputs either nothing at all or no numbers. Ive been able to make error messages show up when someone doesnt input numbers onto the text field.
However I cant make the error message I've created in PHP to show up whenever someone clicks the send button without inputing anything at all in the text field.
My PHP code:
$resurs = array();
$fyll = $_GET['inputfield'];
$dg = 2;
$nummer1 = $nummer1 * $dg;
$fel = "Fill in a number";
$nummer2 = $nummer1 * $fill;
$no = "Field is empty";
if (is_numeric($fyll)){
$resurs = array(
"nummer1" => $nummer1. "<br>",
"nummer2" => $nummer2. "<br>"
);
echo json_encode($resurs);
}
else {
$resurs = array (
"fel" => $fel. "<br>"
);
echo json_encode ($resurs);
}
if (empty($fyll)){
$resurs = array (
"no" => $no. "<br>"
);
echo json_encode ($resurs);
}
My Jquery:
$(document).ready(function(){
$("#submit1").click(function(){
var siffra = document.getElementById("inputfield");
$.getJSON("form.php?inputfield="+siffra.value, function(result){
var t1;
var t2;
var t3;
var error;
$.each(result, function(i, field){
if (i =="nummer1"){
t1 = field
}
if (i == "nummer2"){
t2 = field
}
if (i == "no"){
t3 = field
}
if (i == "fel"){
error = field
}
$(".d1").html(t1);
$(".d2").html(t2);
$(".d3").html(t3);
$(".d3").html(error);
});
});
});
});
field will be an object. You need to retrieve the properties of that object. So either, field.nummer1, field.nummer2, field.fel or field.no depending on the response from the request. Try this:
$.each(result, function (i, field) {
if (i == "nummer1")
t1 = field.nummer1;
if (i == "nummer2")
t2 = field.nummer2;
if (i == "no")
t3 = field.no;
if (i == "fel")
error = field.fel;
$(".d1").html(t1);
$(".d2").html(t2);
$(".d3").html(t3);
$(".d3").html(error);
});
Note that you're setting the value of each .dX element in each iteration of the loop, even when there is no value for the variable provided. I would suggest you check the logic of this function against your requirements.
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;
Im retrieving an array from php file called check_num.php :-
check_num.php
<?php
include 'config.php';
session_start();
$VALUE = $_SESSION["some_session_variable"];
if(isset($_POST['default'])){
$ert = "SELECT * FROM table_name WHERE something = '$VALUE' ORDER BY p_id ASC ";
$qty = mysql_query($ert);
$fgh = mysql_num_rows($qty);
$ertz = "SELECT something, COUNT(something) FROM table_name WHERE something = '$VALUE'
AND something >= 1 GROUP BY p_id ORDER BY p_id ASC";
$qtyz = mysql_query($ertz);
$tyui = mysql_num_rows($qtyz);
$data = array(
"post" => $fgh,
"likes" => $tyui
);
echo json_encode($data);
} else {
echo "0";
}
?>
Now comes the jquery part :-
<script>
$(document).ready(function(){
setInterval(function(){
var def = "one";
$.post("check_num.php", {'default': def }, function(response){
if(response != 0){
document.getElementById("total_array_count").innerHTML = response;
//document.getElementById("total_like_count").innerHTML = response.likes;
//document.getElementById("total_post_count").innerHTML = response.post;
------------------OR THIS Method-----------------
var my_array = response;
//var post_number = my_array["post"];
document.getElementById("total_array_count").innerHTML = my_array;
//document.getElementById("total_post_count").innerHTML = '<b>'+post_number+'</b>';
}
else {
document.getElementById("total_array_count").innerHTML='Error occured !';
}
});
},2500);
});
</script>
Now received output is {"post":10,"likes":1} , its an array . But when i access array values response.post or my_array["post"] the value returned is undefined.
I had gone through this :- http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_object
And kind of this too:- jQuery .val() returns undefined for radio button
Followed it but no success !
Please correct my mistakes .
Run JSON.parse() on your result before trying to access the values. The result comes as a raw string and you have to convert it to an object first.
result = JSON.parse(result);
Alternatively, since you're already using jQuery, you can use jQuery's alias for the function.
result = $.parseJSON(result);
They are essentially the same thing.
I have this code:
$show_location = mysql_query("SELECT * FROM location ORDER BY location_code");
while($row_location = mysql_fetch_array($show_location))
{
$location_code = $row_location['location_code'];
$show_store = mysql_query("SELECT * FROM store_list WHERE location LIKE '%$location_code%'");
$count_store = mysql_num_rows($show_store);
while($row_store = mysql_fetch_array($show_store))
{
$store_name = $row_store['store_name'];
}
if($count_store==0)
{
$status = "Inactive";
echo '<option value="'.$location_code.'">'.$location_code.'</option>';
$sql1 = "SELECT description FROM location WHERE location_code=$location_code";
$result1 = mysql_query("$sql1");
$row1 = mysql_fetch_assoc($result1);
$description=$row1['description'];
}
else
{
$status = "Active";
}
//echo '<option value="'.$location_code.'">'.$location_code.'</option>';
}
What I want to do is to display the $description somewhere in the form. I have the kind of combobox where you can select as many as you can. I want to display each $description once a location is selected. But I dont know where to put the trigger. Can sombody help me? Thanks!
correct me if i am wrong, but will every location_code have one description right?
well there are two ways:
1) Easy but not so efficient way
Make an ajax call for every selected value.
$("#myDropDown").change(function (event) {
//alert("You have Selected :: "+$(this).val());
$.ajax({
type: "POST",
url: "ajax.php",
data: { type: "1", location: $(this).val() }
}).done(function( msg ) {
("#mydata").html(msg)
});
});
You can check for type == 1 on php side, get the description and print it
The above method will cause a ajax request for every selection
2) A bit complex, but efficient
First of all json_encode your location_code and description. It will become something like {code:"AU", description:"blah blah"}
Then use something like this
$("#sel").change(function(e){
//alert($(this).val());
var array = $(this).val();
for(key in array){
var json = JSON.parse(array[key]);
$("#desiptions").html(json.description);
}
});
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?
Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)