one JSON call returned with many? - php

My question is... How to make json have 1 call back with several objects.
I will use this example of 3 values to be returned... Here is the calclickM.php file, but I can not understand why it is not woking...
<?php
$choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d");
$con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$choice."' group by date"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$dayPowerP = array ('dayPowerP');
?>
<?php
$choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$monthPowerP = array ('monthPowerP');
?>
<?php
$choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$yearPowerP = array ('yearPowerP');
?>
<?php
$outarr['dayPowerP'] = $dayPowerP;
$outarr['monthPowerP'] = $monthPowerP;
$outarr['yearPowerP'] = $yearPowerP;
echo json_encode($outarr);
?>
Here is the Jquery I am using to post and the json
<script type="text/javascript">
$(document).ready(function () {
$('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) {
var myDate = $(this).datepicker('getDate');
$('#apDiv1').html($.datepicker.formatDate('DD, d', myDate));
$('#apDiv5').html($.datepicker.formatDate('MM', myDate));
$('#apDiv7').html($.datepicker.formatDate('yy', myDate));
$.ajax({
type: "POST",
url: "calclickM.php",
data: {choice: dateText},
dataType: "json",
success: function(json_data) {
$('#apDiv2').html(json_data['dayPowerP']);
$('#apDiv6').html(json_data['monthPowerP']);
$('#apDiv8').html(json_data['yearPowerP']);
}
})
}});
});
Thanks,
Alan

At first the load method you are calling is making an AJAX GET request to your server. You probably support both POST and GET requests in your PHP script.
Secondly you have some errors in the your $.ajax calls. There are some unterminated strings, the data variable you are using as ('#apDiv9').html(data) isn't defined and if it was, it will be probably contain JSON data that you can't directly put in an HTML element.
Last, but not least, the second attempt won't make your code faster. A browser can only support a limited number of parallel ajax requests (1-2). You are still making the same number of requests and some of them need to wait for the others to complete. Re-design your code so that you return everything in a single call.

Not a solution to your immediate problem, but your code needs some serious refactoring. The level of repetition here hurts my eyes. The second code block, the one with the ajax-calls, could be changed to something like this:
var pages = [
{ url: "dayPower.php", div: "#apDiv4" },
{ url: "dayGraph", div: "#apDiv2" },
{ url: "monthPower.php", div: "#apDiv6" },
{ url: "monthGraph", div: "#apDiv9" },
{ url: "yearPower.php", div: "#apDiv8" },
{ url: "yearPower", div: "#apDiv10" }
};
for ( var i=0; i<pages.length; i++ ) {
$.ajax({
type: "POST",
url: pages[i].url,
data: { choice: dateText},
dataType: "json",
success: function(json_data )
(pages[i].div).html(data).show(); // Did you mean json_data here?
}
});
}
The case is similar with the first piece of code in your question.
Once again, I know it won't solve the actual problem, but it will make it easier to implement the solution when you (or someone else) finds it.
EDIT
On second thought, I can see at least one strange thing: in the success-function you call the parameter json_data, but you access a variable that you've called data. Did you intend to name them the same thing?

There is a way to do what you are asking, but you will need to handle the results yourself. Essentially all your Ajax calls have the same parameters, but different resultsets. So first, the client side code that does the magic:
$.post('datePacked.php', {choice: dateText}, function(data) {
$('#apDiv2').html(data['dayPower']);
$('#apDiv4').html(data['dayGraph']);
$('#apDiv6').html(data['monthPower']);
$('#apDiv9').html(data['monthGraph']);
$('#apDiv8').html(data['yearPower']);
$('#apDiv10').html(data['yearGraph']);
});
If you refactored your HTML so taht you actually match the div Ids with the result of your JSon response, you can simplify the call even further:
$.post('datePacked.php', {choice: dateText}, function(data) {
$.each(data, function(id, value) {
$('#'+id).html(value);
});
});
On the server side your new datePacked.php needs to return a JSON result that provides a hash of names to content. Essentially it will look something like this:
{ "dayPower" : "<p>My Content</p>", "dayGraph" : "<p>Day graph</p>", ... }
The ellipsis is there for you to fill in the remainder of the content. Choosing meaningful id names for your HTML elements is not only good practice, it can save you a lot of repitition if you take advantage of it. An example of that would be the second form of the client example. This is a case where the content has to be JSON for it to work--unless you want to split up a DOM returned by the server.

I’m not exactly sure what you’re asking, but here’s a couple of points:
$('#apDiv2').load('dayPower.php', {choice: dateText} does the same thing as $.ajax({type: "POST", url: "dayPower.php", data: { choice: dateText}. Both $.ajax and $.load make HTTP requests via JavaScript, which is what “AJAX” means.
Your second block of example code has some basic syntax errors. Here’s the first $.ajax call corrected:
$.ajax({
type: "POST",
url: "dayPower.php",
data: { choice: dateText},
dataType: "json",
success: function(json_data ) { // “{” added to start the function block
('#apDiv2').html(data).show();
}
}) // “})” added to end the object literal and function call

if you never need call any of this separately, why not just make one ajax call to a php file, package all your data into a multidimensional array, convert to json, and send back to the client.
Once you have this json, you can then break it up with js and figure out what goes where on your front end.
Depending on how much data you're getting it may take a while. If it's a huge query, then breaking it up into several little calls be actually be better. Its asynchronous so at least parts of your page will be loading. while other parts are gathering data.

Related

Sending array from PHP script

Here's the values I am sending to the PHP script from the Javascript:
$('.verdi_knapp').click(function() {
$(this).siblings().removeClass("aktiv_verdi"); // ta vekk aktiv på de andre alternativene
$(this).addClass("aktiv_verdi"); // sett denne til aktiv
var min_id = $(this).attr('id').split("_")[1];
var aktuelle_verdier = []
$('.aktiv_verdi').each(function() {
aktuelle_verdier.push($(this).attr('id').split("_")[1]);
})
console.log("disse verdiene skal vi spørre etter", aktuelle_verdier)
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
This is the PHP script which queries a set of values from an SQL database and prints them to the console in the javascript:
$ids = $_GET['aktuelle_verdier'];
$value = implode(", ", $ids);
$antall = count($_GET);
$sql = "SELECT `art_id`
FROM `art_has_verdi`
WHERE `verdi_id` IN (".$value.")
GROUP BY `art_id` HAVING COUNT(*)=".$antall.";";
$result = mysqli_query($conn, $sql);
$arter_igjen = array();
while($row = mysqli_fetch_array($result)){
array_push($arter_igjen, $row['art_id']);
}
echo json_encode($arter_igjen);
What I am trying to find out next is how to send this array: $arter_igjen, which contains a set of IDs, to another page where I can run a query to the database for all the data containing these IDs and print them out in a list.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
Please check data Paramter in ajax call. You forgot to pass key in JSON.
If I understand you right you like after ajax return you clone the window and in new one window you will make some new searches, but on the current one will be generate a log. In cas I'm understand you right, then why don't try to generate form on fly by with returned data end post it to the _blank window.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
// Here you have to generate the form on fly
// Include hidden fields, containing your result data
// and finally send form with action some new.php on blank_ target
console.log(result);
}});
If the other page contains code like in this one (not in a class or function), you can just include it (include_once "..."), but it is not recommended that you just keep scripts like that.
Instead, encapsulate your code (put it within functions and classes). This will allow you to freely insert your scripts (include_once "...") and call these functions or create classes that will work.
Also, try to avoid too many http requests. If that list of ids won't be needed, do all of the work in the php scripts and return the needed result.
There are a few issues with your code. If you are just starting with PHP I would suggest you read:
PDO: Creating a connection
PDO with prepared statements (prevents SQL injections)
User-defined functions (I don't have enough reputation to put the link. Search: "w3schools php 5 functions")

Delaying key strokes in php mysql search

So I've put together a search feature which searches as you type and displays the result in the text field but now the catch is that it won't let me delete easily and is 'thinking' too fast. Any ideas on how to slow this down?
<script>
$(document).ready
(function()
{
$("#tag").keyup
(function()
{
var tag= $(this).val();
if(tag!='')
{
$.ajax(
{
type: "GET",
url: "autocomplete.php",
data: "q=" + tag,
cache: false,
success: function(result)
{
$("#tag").val(result);
}
}
);
}
return false;
}
);
}
);
</script>
and then this
<?php
$q_incoming=$_GET['q'];
//$my_data=mysql_real_escape_string($q_incoming);
$mysqli=mysqli_connect('localhost','XXXXXXX','XXXXXXXX','XXXXX') or die("Database Error");
$sql = "SELECT auto_complete_suggestions FROM auto_complete WHERE auto_complete_suggestions LIKE '$q_incoming%' LIMIT 0,1";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo $row['auto_complete_suggestions']."\n";
}
}
?>
The thing I think is happening is that if I type "he" it prompts "help" but when i delete the "p" it's going to prompt again since it has "hel" to search on. Any ideas on how to allow it to delete as well as slow the querying down so that you can type a letter at a reasonable typing pace? I could fidget with a timing function or maybe tell it to ignore after a delete?
Thanks!
The easiest way is to use this jQuery plugin:
http://benalman.com/projects/jquery-throttle-debounce-plugin/
Have a look at the usage example below "Debouncing". That's exactly what you're looking for.
You should use prepared statements or your application is vulnerable for SQL injections!

POST data through AJAX and set as variable

I am not very familiar with javascript especialy when it comes to functions and ajax. I am trying to get some data from another php page and have it put into a div. When I ever i load the page nothing comes up.
My ultimate goal is to get the data into a php or javascript but first need to figure out how to get / receive data.
here is the php code of feedupdate.php
<?php
require "dbc.php";
$function = $_POST['function'];
switch($function)
case('initiate'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$mostrecent= mysql_fetch_array($request);
$mostrecentid = $mostrecent['id']
echo json_encode($mostrecentid);
break;
case('update'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
echo json_encode($updateid);
break;
?>
here is the ajax
<div id="datacheck"></div>
<script>
$(document).ready(function() {
$.ajax({
type: 'POST'
url: 'feedupdate.php'
data: {'function': 'initiate',},
datatype: "json"
success: function(msg) {
$('#datacheck').html(msg);
}
});
}); // document ready
There is a typo in the ajax jquery code
success: fuction(msg) {...
it should be spelled "function".This typo might be the problem , plus there should be switch case for
getState
in your php code.
You are passing getState in data from JavaScript while in PHP you do not have a similar case to match in switch statement. Instead of getState pass update or initiate.
If you just want to check either AJAX call is working or not write
echo "something message"; exit();
In your AJAX you are passing data back to the PHP script:
data: {'function': 'getState'},
But in your php script you don't have a case statement that matches getState you only have initiate and update. So you can either write code to support getState or you can pass in either initiate or update to the data parameter.
Also watch out for trailing comma's. They won't work in IE. You should remove the comma after 'getState' on the data line.
You are also missing a comma after type, url, and datatype
$(document).ready(function() {
$.ajax({
type: 'POST', // add comma
url: 'feedupdate.php', //add comma
data: {'function': 'initiate'}, // remove comma
dataType: "json", // add comma
success: function(msg) {
$('#datacheck').html(msg);
}
});
});
Alos you can look at using the shorthand method $.post docs

Better approach for displaying two PHP variable switch jQuery Ajax

I'm getting two random values from a table. The values are in the same row.
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"];
echo $row["surname"];
?>
And I want to display these two values at different div's on my HTML page by using jQuery Ajax functions.
$(function()
{
$("#sentence-form").submit(function()
{
$.ajax(
{
type: "GET",
url: "newperson.php",
success: function(response)
{
$("#top-container").append(response); /* Both name and surname */
}
});
});
});
The problem is separating two values to display different in div's. I tried to use two Ajax calls and I send boolean data to PHP to use with an if statement. So one of the Ajax calls displays name and the other one displays surname. But because of randomization, it's a bit complicated to find surname of a name.
What is a better approach?
Yes: send the data in a data structure – probably JSON – so your client-side code knows which bit is which.
First, send the data with PHP's json_encode function:
echo json_encode(array(
'name' => $row['name'],
'surname' => $row['surname']
));
Then use your browser's ability to parse JSON:
$.ajax({
type: "GET",
url: "newperson.php",
dataType: 'json',
success: function (response) {
$("#name-container").append(response.name);
$("#surname-container").append(response.surname);
}
});
response is now a Javascript object (something like {name: 'John', surname: 'Smith'}), so you can access the two parts as normal object members.
Send the variables as a JSON array
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
$output['name'] = $row["name"];
$output['surname'] = $row["surname"];
echo json_encode($output);
?>
And on the JavaScript code, access it as:
data.name and data.surname
Although I like lonesomeday's answer, and I think that that is the way to go, I will post the alternative:
Relevant PHP:
echo $row["name"].'||'.$row["surname"];
Relevant JavaScript code:
success: function (response) {
var parts = response.split('||');
$("#name-container").append(parts[0]); //name
$("#surname-container").append(parts[1]); //surname
}
Use this:
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"]."&".$row["surname"];
?>
$(function(){
$("#sentence-form").submit(function(){
$.ajax({
type : "GET",
url : "newperson.php",
success : function(response){
items=response.split('&')
$("#top-container").append(items[0]); /* name */
$('#bottom-container").append(items[1]); / /*s(u should be i)rname */
}
});
});
});

Multiple one-time PHP database updates using jquery's .error()

I have a webpage with some broken images, these images are being show by a database. I am using the following jQuery to hide the images that are broken.
//images are wrapped in an anchor
$("img").error(function() {
$(this).parent().hide();
});
I would like to utilize the "status" column in the database to set all of the broken images to "hidden". Every anchor that wraps an image on the page has a "id" attribute that matches the primary database key "id".
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: "status=hidden&id=".error.""
});
});
// changestatus.php
<?php
mysql_connect("localhost", "stackoverflowexampleuser", "stackoverflowexamplepass") or die(mysql_error());
mysql_select_db("stackoverflowexampledatabase") or die(mysql_error());
$id = $_POST['id'];
$status = $_POST['status'];
$query="UPDATE stackoverflowexampletable SET status = '".$status."' WHERE id ='".$id."'";
mysql_query($query) or die ('error');
mysql_close();
header( 'Location: MYSOURCE' ) ;
?>
This is my first stab at ajax, and I know I got some stuff seriously wrong. I saw a couple of examples using KEY VALUE pairs but I don't know what the $_POST['var'] should be.
Can you even request something like this "when the page loads"? I tried wrapping it in an arbitrary button and it didn't work.
Since this just needs to be used once I'm not really focused on using AJAX.
Try this:
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: {
status: "hidden",
id: error
}
});
});
If you're wanting to initiate it on page load, be sure to include it in the $(document).ready() function.

Categories