ajax to a php and get JSON from it - php

I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?

Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.

I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()

Related

Messaage (array) php to ajax with [echo json_encode'] not show data

I'm trying to send an array of data from PHP to ajax. I'm using echo json_encode to do it. When I do that, I try 'console.log(data)' to see the response data but it not show anything. How can I get it to display the data? I really don't know what I'm missing here. I have this script:
var scard = $('#cardid').val();
$.ajax({
type: 'GET',
url: 'cardapi.php?scard=' + scard,
success: function (data) {
console.log($.parseJSON(data));
console.log(data);
}
});
And here is my code for cardapi.php
if(isset($_GET["scard"])){
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no='$scard'";
$q = sqlsrv_query($conn, $sql);
while($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)){
array_push($data,[
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1,
]);
}
echo json_encode($data);
}
So I try to follow this echo json_encode() not working via ajax call
It still not show anything. Please tell me why?
Thank you.
You may try the following:
Always check the result from the sqlsrv_query() execution.
Always try to use parameterized statements. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Check the result from the json_encode() call.
Fix the typing errors ("signed_status" => 1, should be "signed_status" => 1 for example).
Sample script, based on your code:
<?php
if (isset($_GET["scard"])) {
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no = ?";
$params = array($scard);
$q = sqlsrv_query($conn, $sql, $params);
if ($q === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)) {
$data[] = array(
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1
);
}
$json = json_encode($data);
if ($json === false) {
echo json_last_error_msg();
exit;
}
echo $json;
}
?>

convert doctrine resultset to json from findby query using zend json

I've seend much assistance for everything BUT transforming data when using the findBy query.
What I want is a json string of the resulset from this query ensuring that the objects are serialized so i can use this somewhere else:
$posts = $entityManager->getRepository(\Application\Entity\Post::class)
->findBy(['status'=>\Application\Entity\Post::STATUS_PUBLISHED],
['dateCreated'=>'DESC']);
Json::encode($posts,true) from Zend Framework Json but the data is not showing up when i do this.
The result will be a json encoded string with the entity objects that i can pass somewhere else
I will use for the decoding:
\Zend\Json\Decoder::decode($posts,\Zend\Json\Json::TYPE_OBJECT)
UNLESS I should be using \Zend\Json\Json::TYPE_ARRAY)
Here is the way I do it :
include : use Zend\Json\Json;
here is my example of function / action :
public function getListAction(){
$request = $this->getRequest();
if($request->isPost()){
// recuperer le produit choisi :
$element = $request->getPost("element");
$result = null;
$result = $this->getEntityManager()->getRepository('Application\Entity\Element')->findBy(array('etat' => 'valide' , 'pkElement' => $element));
$champs = array();
$i = 0;
foreach ($result as $value) {
$champs[$i] = array("id"=>$value->getPkElement() , "nom"=>$value->getNom());
$i++;
}
$data = array(
'result' => true,
'data' => $champs
);
return $this->getResponse()->setContent(Json::encode($data));
}
}
Then the call in the view.phtml :
$.post('/application/controller_name/getList', {element: $("select[name=element]").val()}, function(result) {
var options = $("select[name=element]");
var obj = JSON.parse(result);
var data = obj.data;
var selected = "";
options.empty();
for (var i = 0; i < data.length; i++) {
options.append($("<option />").val(data[i]['id']).text(data[i]['nom']));
}
});
Hope it helps.

How to insert array values in mysql with a loop

Reading a Textarea with jquery , splitting each line in Array then with ajax posting that array in mysql through php but in results only first value inserted.
Table:
CREATE TABLE IF NOT EXISTS addresses (
id int(8) NOT NULL PRIMARY KEY,
user_id int(8) DEFAULT NULL,
address_value varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Here is Jquery Code :
$('#insertad').click(function(){
var lines = $('#txtArea').val().split('\n');
var phparray = new Object();
for(var i = 0;i < lines.length;i++){
phparray[i] = lines[i]; //store value in object
}
$.post('functions.php?action=insertad', {array1:$.param(phparray)}, function(resp){
$('.text-success').html(resp);
if(resp == 'Added'){
$('.text-success').html('Added Address :');
}
});
});
Here is PHP Code :
if ($action == 'insertad') {
$pieces = explode('&', $_POST['array1']); //explode passed serialized object
$phparray = array();
foreach ($pieces as $piece) {
list($key, $value) = explode('=', $piece);
$phparray[$key] = $value; //make php array
}
$length = count($phparray);
for ($i = 0; $i < 7; $i++) {
$sql = "select address_value from addresses where address_value = '$phparray[$i]'";
$qry = mysql_query($sql);
$numrows = mysql_num_rows($qry);
if ($numrows > 0) {
echo "One Found !!" ;
} else {
$sql = "insert into addresses (address_value) values ('$phparray[$i]')";
$qry = mysql_query($sql);
if ($qry) {
echo "Added";
}
}
}
}
Try this please...
JS:
var $textarea = $('textarea'); // maybe you have to specific your selector!
var textArray = $textarea.val().split("\n"); // this array is already done, your have not todo next for() loop
$.post('functions.php', {
action: 'insertad',
array1: textArray
}, function(results) {
$.each(results, function(reslt) {
if(result === 'Added') {
$('.status').append(result);
}
else {
$('.status').append(result);
}
});
});
PHP:
if($action === 'insertad') {
$results = [];
$input = $_POST['array1'];
foreach($input AS $textLine) {
$escapedTextLine = mysqli_real_escape_string($resource, $textLine);
$result = mysqli_query($resource, 'select address_value from addresses where address_value = "'.$escapedTextLine.'"');
$affectedRows = mysqli_num_rows($result);
if($affectedRows > 0) {
$results[] = 'One Found !!';
}
else {
$result = mysqli_query($resource, 'INSERT INTO `adresses` (`address_value`) VALUES("'.$escapedTextLine .'");
if($result) {
results[] = 'Added!';
}
}
}
return $results; // we return all done results to check this array in ajax response
}
Notice: I wrote the code blind, so maybe you have to make some small changes for e.g. your variables or something like that.
Notice 2: I write the code with mysqli, so you have to rewrite your Database connection setup code.
Please never forget to use mysqli_real_escape_string do something with user contents.

How to add result rows to json object

Im using ajax to update my data. Ajax calls my function.php where i use a switch to determent which function to run. I save my results in a json object ($resp = new stdClass).
But how do i save multiple rows (with multiple columns) into the json object?
function func1($mysqli){
$result = $mysqli->query("select * from order");
///how do i fetch all rows in a loop and save it correctly to my json object?
return json;
}
$resp = new stdClass;
if (isset($_POST["action"])) {
switch($_POST["action"])) {
case "func1":
$resp->data = func1($mysqli);
break;
}
}
echo json_encode($resp);
Here is the function which stores rows in an array and returns it. If query fails, null is returned.
function func1($mysqli){
$result = $mysqli->query("select * from `order`");
if ($result){
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row ;
}
return $data ;
} else {
return null ;
}
}
In your code you already save a return value in a STDClass, so it is fine:
case "func1":
$resp->data = func1($mysqli);
break;
}

Undefined offset: 0 in first PHP app

I'm currently building my first PHP application. I want to read in bus times from a csv file and give back ti users the next bus from their residence to our university. It is my first try with PHP, so be gentle:
<?php
// configuration
require("../includes/config.php");
if (!empty($_SESSION["id"]))
{
//lookup database entries for house
$users = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
if ($users === false)
{
apologize("Sorry, there was an error");
}
//lookup database entries for house
$residences = query("SELECT * FROM residences WHERE id = ?", $users[0]["residence"]);
if ($residences === false)
{
apologize("Sorry, there was an error");
}
//if user specified a residence in his profile
if($residences[0]["id"] != 0)
{
$times = array();
//if there is no bus today, in this case sat and sun
if(date( "w", $timestamp) == 0 || date( "w", $timestamp) == 6)
{
$times[0] = "There is no bus today";
}
//load the busplan for his residence
else
{
//open file and load in array if time is higher than date("His");
$timesList = file_get_contents($users[0]["residence"] . ".csv");
$nextbuses = explode(',', $timesList);
$hoursMins = date("Gi");
$num = 0;
for($i = 0; $i < count($nextbuses); $i++)
{
if($hoursMins < $nextbuses[$i])
{
$times[$num] = $nextbuses[$i];
$num++;
}
}
}
render("shuttle_show.php", ["title" => "Next Shuttle from your residence.", "times" => $times]);
}
}
This uses the function query:
function query(/* $sql [, ... ] */)
{
// SQL statement
$sql = func_get_arg(0);
// parameters, if any
$parameters = array_slice(func_get_args(), 1);
// try to connect to database
static $handle;
if (!isset($handle))
{
try
{
// connect to database
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
// ensure that PDO::prepare returns false when passed invalid SQL
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
// trigger (big, orange) error
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
// prepare SQL statement
$statement = $handle->prepare($sql);
if ($statement === false)
{
// trigger (big, orange) error
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
// execute SQL statement
$results = $statement->execute($parameters);
// return result set's rows, if any
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}
the other functions it uses are not relevant I guess. Now I cant seem to find why this keeps producing:
Notice: Undefined offset: 0 in /Applications/MAMP/htdocs/html/shuttle.php on line 16
Notice: Undefined offset: 0 in /Applications/MAMP/htdocs/html/shuttle.php on line 22
The relevant lines are
$residences = query("SELECT * FROM residences WHERE id = ?", $users[0]["residence"]);
and
if($residences[0]["id"] != 0)
Would appreciate some help! :)
Edit:
I transferred the same file to my linux system and without any changes I get a vardump. If I use the same vardump on MAMP on my Mac the array is empty. Now I get for:
var_dump($users);
array (size=1)
0 =>
array (size=5)
'id' => int 12
'username' => string 'frechdaxx' (length=9)
'mail' => string '*************#gmail.com' (length=23)
'hash' => string '$1$qr5axj4C$BET5zZGJza2DcHI8eD8fV0' (length=34)
'residence' => int 9573
Why is this a problem at all? the function query worked with the exact same syntax before when I accessed the user table and as we can see it gives back all other values correctly.
Why the difference between my environments? The array is empty on my MAMP server, but works on Linux. However, other code examples with the query function work perfectly on both environments
Why the big int of 9573? The value in the table is 2.
This is simply that $users[0]["residence"] doesn't exists (is not set). You should check it before attempting to use it. As you can see, it's only a notice, not a error. This means that in some case scenarios, the variable can be unset and PHP won't complain THAT much, but this is definitely not good as a general rule.
I would change it to:
$users = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
if (empty($users[0]["residence"]))
{
apologize("Sorry, there was an error");
}
Furthermore, that only "fixes" it. If you want to go to the root of the problem, it's in the query() function that is called in $users = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);:
// execute SQL statement
$results = $statement->execute($parameters);
// return result set's rows, if any
if ($results !== false)
{
$fetched = $statement->fetchAll(PDO::FETCH_ASSOC);
// Check that ther was actually something fetched
if(!empty($fetched))
{
return $fetched;
}
}
/* You don't need to return false, null is the default returned value.
* If you *want* it, then delete the else. */
}
From the documentation, fetchall returns an empty array if there's nothing, so the function might return an empty array.
$users = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
if ($users === false) { }
You are strictly checking if query returned false, that only occurs when something was wrong with query or parameters. That does not check if any result was returned, and you are referring to the first returned record ($users[0]["residence"]) that is not present ($users is an empty array).
Since user id comes from $_SESSION["id"] it should be present and available in database, but there is possibility that somewhere in your code you are overwriting it with other id.

Categories