Break array retrieved from php using jquery - php

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.

Related

php how to return JSON for jQuery .get() or .post() request, parse it and output to browser

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;

How to put object into string and print

I have a script that takes variables from an html form and sends them to a php script. I query new data based on these numbers and format them into a string to be sent back to the script. The problem is that my php variables aren't printing and I think it is because they are objects. Here is my code:
//GET VENDOR PO NUMBER AND APPEND ONCHANGE OF # OF EXISTING POS
$('#numvendpo').mouseover(function(){
var countpre = $(this).val();
var p = $('#pro').val();
var c = $('#custponumhold').val();
var v = $('#vendorid').val();
var cp = (parseInt(countpre)+1);
var data_String;
data_String = 'p='+p+'&c='+c+'&v='+v+'&cp='+cp;
$.post('ft-final-v-po-num.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
});
});
I then post the values to this php script:
<?php
require "../inc/dbinfo.inc";
$p = $_POST['p'];
$c =$_POST['c'];
$v = $_POST['v'];
$cp = $_POST['cp'];
if ($c == 'null') { //cant use (!$customerpo) because $customerpo is passing the string of 'null' instead of the actual null value
$c = NULL; //so we change that to the actual null value
}
$getprojectnum = "SELECT ProjectNumber FROM tblProjects WHERE PROJECTNOID = '$p'"; //check
$getcustomerpo = "SELECT SequentialPONum FROM tblCustomerPOs WHERE CustomerPOID = '$c'"; //check
$getvendornum = "SELECT VendorNumber FROM tblVendors WHERE VENDORID = '$v'"; //check
$acpnhold = $conn->query($getprojectnum);
$accphold = $conn->query($getcustomerpo);
$acvnhold = $conn->query($getvendornum);
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
if($c){
$string = $acpn.'-'.$accp.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}elseif(!$c){
$string = $acpn.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}else{
echo json_encode('Error');
exit();
}
?>
The response on my webpage is ---2 instead of (ex: 18000-1-2-2). As mentioned earlier I think it is because they are objects but I am not quite sure. Any advice is appreciated.
Your problem is with this bit:
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
From the php docs:
object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, array $params ]] )
Your $acpn $accp and $acvn are not result objects. They are not even defined before you use them in those calls.
This should get the single column from each query result:
$acpn = $acpnhold->fetch_row()[0];
$accp = $accphold->fetch_row()[0];
$acvn = $acvnhold->fetch_row()[0];
Bear in mind you still have a major SQL Injection vulnerability with the original query calls.
Try like this code below:
$.ajax({
type: 'POST',
url: 'ft-final-v-po-num.php',
data: {
'p': p,
'c': c,
'v': v,
'cp': cp
},
success: function(msg){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
}
});

Cant make JSON/PHP echo message appear using jQuery

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.

Pass an array from PHP (from DB) to JS?

My goal is to get - finally - a 'normal' JS array in my js-file. Maybe json is the way to do it - but the elements in the array should remain in order and its just an array of three arrays: [["1","2","3"]["1","2","3"]["1","2","3"]].
my php-query (it does produce the array above - I mean: it does work):
// this is file 'dbquery.php'
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo $cd_answer;
?>
I assume json is not the adequat form here.
Now all I want is an js-array in my js-file like : my_array = [[1,2,3],[1,2,3],[1,2,3]]
But I terribly fail to achieve this.
With $.ajax() I don't know how to get ALL the data at once without 'data: ' each single value. I just want to "catch" my echo from the php - how to do so?
do like this
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo json_encode ($cd_answer); // encode in json format
?>
and in ajax:
$.ajax({
type: "GET",
url: "test.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON( data ); // parse the answer
// if you want in an array format then just use eval()
x = eval(x);
alert(x);
}
});
If you just need a PHP variable passed to JS when the page is rendered, then do this in your PHP view layer:
<script type="text/javascript">
var myInt = <?php echo $int ?>;
var myString = '<?php echo $string ?>';
var myArray = <?php echo json_encode($array) ?>;
// All these JS variables can now be used here
</script>
Obviously, you need to ensure that the variables are valid - so in the case of the int, if it is null or undefined, you need to ensure you don't render the assignment - otherwise it will produce a client-side error.

jQuery $.post not returning JSON data

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.

Categories