can't set variable in JavaScript based on json id from php - php

I have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)
$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');
header('Content-type: application/json');
echo json_encode($array);
and it echos as:
[{"id":1,"price":"325"},{"id":2,"price":"486"}]
now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as
counterval1 = 325;
counterval2 = 486;
but I can't seem to get it to read that way. Here is the script at the current moment.
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval + data[i].id = data[i].price;
console.log (counterval2);
});
$('#results').html(counterval2);
});
var counterval1 = 0;
var counterval2 = 0;
any help on this would be greatly appreciated.

you can't do that... but you can do this...
var counterval = [];
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval[data[i].id] = data[i].price;
console.log (counterval[2]);
});
$('#results').html(counterval[2]);
});
counterval[1] = 0;
counterval[2] = 0;

See my comment on your post. If you really want the vars to look like you explained:
eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);

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;

Ajax and php when inserting into MySQL

Simple question guys , i have AJAX that pickup all data from page and it suppose to open new php page to update MySQL database , its only updating last row of data , BUT when i use alert from javascript just to check all data i got he does update whole table ... is there any chance that AJAX is not working fast enough or something?
here is my code
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 MatchID = '';
var HomeTeam = '';
var AwayTeam = '';
var TipID = '';
var arrayMaxValues = 3;
var myArray = new Array(3);
var i = 0;
$('#teams_table input[type=text]').each(function () {
myArray[i] = $(this).val();
if (!!myArray[2])
{
MatchID = myArray[0];
HomeTeam = myArray[1];
AwayTeam = myArray[2];
if (HomeTeam > AwayTeam) {
TipID = 1;
}
else if (HomeTeam == AwayTeam) {
TipID = 2;
}
else if (HomeTeam < AwayTeam) {
TipID = 3;
}
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' +
TipID + '&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, true);
http.send(null);
myArray = new Array(3);
i=0;
}
else
{
i++;
}
});
It is kinda odd to me when i use
alert('MatchID = ' + MatchID + ' HomeTeamScore = ' + HomeTeam + ',
AwayTeamScore = ' + AwayTeam)
Inside of AJAX code i get whole table updated , without it just last row
And my php page
<?php
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$HomeScore = $_GET['HomeTeam'];
$AwayScore = $_GET['AwayTeam'];
$query="update probatip1.matches set ResultTipID=".$tipID.",HomeTeamScore = "
.$HomeScore.",AwayTeamScore= ".$AwayScore." where MatchID =".$matchID;
$UpdateGame= mysql_query($query) or die(mysql_error());
mysql_close()
?>
Try encoding the data. i.e:
MatchID = encodeURIComponent(myArray[0]);
HomeTeam = encodeURIComponent(myArray[1]);
AwayTeam = encodeURIComponent(myArray[2]);
in php use
function escapedata($data) {
if(get_magic_quotes_gpc()) {
$data= stripslashes($data);
}
return mysql_real_escape_string($data);
}
to escape your data before updating the table. i.e:
$query="update probatip1.matches set ResultTipID=".escapedata($tipID).",HomeTeamScore = ".escapedata($HomeScore).",AwayTeamScore= ".escapedata($AwayScore)." where MatchID =".escapedata($matchID);
Hope this works.
Not really a direct answer, just something that you can base your answer from. What the code does is to submit a whole object using the $.post method in jquery which takes in 2 parameters and a callback function which is executed once the request is done.Not really sure by: open new php page to update MySQL database but I assume that you're simply using that page to update the database and not actually open it.
<script src="js/jquery.min.js"></script>
<script>
var obj = {
'teams' : [
{'name' : 'teamA', 'grade' : 'A'},
{'name' : 'teamB', 'grade' : 'B'}
]
};
$.post('access.php', {'obj' : obj}, function(data){
var d = JSON.parse(data);
for(var x in d){
console.log(d[x].name);
}
});
</script>
access.php:
<?php
$post = $_POST['obj']['teams'];
$array = [];
foreach($post as $row){
$name = $row['name'];
$grade = $row['grade'];
$array[] = ['name'=>$name, 'grade'=>$grade];
}
echo json_encode($array);
?>
So you only have to modify the php page, and put your database query inside the loop. This way you won't need to perform so many ajax request by putting it inside $.each
Then utilize $.each to build the object that you're going to submit via ajax through $.post method:
var obj = {};
$().each(function(index){
var myArray[i] = $(this).val();
var MatchID = myArray[0];
var HomeTeam = myArray[1];
var AwayTeam = myArray[2];
obj[index] = [];
obj[index]['match_id'] = MatchID;
});
The problem is with your logic in the way you are sending requests to php file to update the MYSQL. Actually you are running the ajax request in a loop and the loop is too fast that kills the previous update request.
Solution
You can compose an array and send it to the php outside the loop. That will work for you.
Guys with your help i managed to fix my problem
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' + TipID +
'&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, false);
http.send(null);
var response = http.responseText;
So basicly with this line i told http request not to go for next line of code until update in table is not completed , when http has done his job then it moves on next line of code.
Thank you for help

How to put my JSON info into a jQuery Array

I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.

php to js array convert with jquery's ajax

Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander
Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}
For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.
You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>

returning JSON and HTML from PHP script

Hi searched through the questions here, but couldn't find anything. I'm new at writing PHP and jQuery, so bear with me.
What I'm trying to do is send an ajax request using jQuery to my script which runs a mysql query on data from my database and serializes it into the JSON format using php's json_encode. The response is then parsed with the available json2.js script. All of this works fine, but I'd also like to return more data other than just JSON from this script.
mainly, i'd like to also echo the following line before the json_encode:
echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
however, my jQuery is evaluating the entire response during the ajax success, making the json.parse function fail due to the script's return being in an invalid format.
success: function(data) {
//retrieve comments to display on page by parsing them to a JSON object
var obj = JSON.parse(data);
//loop through all items in the JSON array
for (var x = 0; x < obj.length; x++) {
//Create a container for the new element
var div = $("<div>").addClass("bubble").appendTo("#comments");
//Add author name and comment to container
var blockquote = $("<blockquote>").appendTo(div);
$("<p>").text(obj[x].comment).appendTo(blockquote);
var cite = $("<cite>").appendTo(div);
$("<strong>").text(obj[x].name).appendTo(cite);
$("<i>").text(obj[x].datetime).appendTo(cite);
}
$("#db").attr("value", '' + initialComments + '');
}
does anyone know how i can return the html line as well as the json_encode to use this script for more than just json population?
thankyou, this website has been wonderful in answering my noob questions.
my php:`
for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));
}
//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
$response = json_encode($comments);
echo $response;`
Don't echo the line, save it in a variable. Construct a simple array
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
); and send that back ( via json_encode ) instead.
Also, you don't need json2.js, jQuery has an excellent JSON parser.
you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );
Changed to match your newly introduced iteration.
for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array(
"name" => stripslashes($row["name"]),
"comment" => stripslashes($row["comment"]),
"datetime" => date("m/d/Y g:i A", strtotime($comment['datetime']))
);
}
$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
echo json_encode(array( 'comments' => $comments, 'html' => $html ));
then, in your javascript, you have
function success( parsedObject ){
parsedObject.html; // "<h1 style..."
parsedObject.comments; // an array of objects
parsedObject.comments[0].name
+ " on " + parsedObject.comments[0].datetime
+ " said \n" + parsedObject.comments[0].comment; // for example
}
As said above just put all the data you want to get back in an array and encode that.
<?php
echo json_encode(array(
'html' => $html,
'foo' => $bar,
'bar' => $baz
));
?>
Also as said you don't need json2.js. You can parse JSON data with any of jQuery's ajax functions by specifying the data type as json.
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($data) {
var html = $data.html;
var foo = $data.foo;
var bar = $data.bar;
// Do whatever.
}
});
EDIT Pretty much what Horia said. The only other variation I could see is if you wanted everything in the same array.
For example:
PHP:
<?php
// You have your comment array sent up as you want as $comments
// Then just prepend the HTML string onto the beginning of your comments array.
// So now $comments[0] is your HTML string and everything past that is your comments.
$comments = array_unshift($comments, $your_html_string);
echo json_encode($comments);
?>
jQuery:
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($comments) {
// Here's your html string.
var html = $comments[0];
// Make sure to start at 1 or you're going to get your HTML string twice.
// You could also skip storing it above, start at 0, and add a bit to the for loop:
// if x == 0 then print the HTML string else print comments.
for (var x = 1; x < $comments.length; x++) {
// Do what you want with your comments.
// Accessed like so:
var name = $comments[x].name;
var comment = $comments[x].comment;
var datetime = $comments[x].datetime;
}
}
});
You might be interested in jLinq, a Javascript library that allows you to query Javascript objects. A sample query would be:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
jLinq supports querying nested objects and performing joins. For example:
var results = jLinq.from(data.users)
.join(data.locations, //the source array
"location", //the alias to use (when joined)
"locationId", // the location id for the user
"id" // the id for the location
)
.select(function(r) {
return {
fullname:r.first + " " + r.last,
city:r.location.city,
state:r.location.state
};
});

Categories