I'm trying to send a picture stored in localstore with javascript but can't retrieve it and show it.
Javascript part :
liste['pic'] = localStorage['pic'];
$.ajax({
type: "POST",
url: "save.php",
data: { pic : liste['pic'] },
dataType: "json",
success: function(data) {
if(data) {
alert("Picture sent succesfully");
}
}
});
The php part that receive the data :
require "lib/connect.php";
$pic = $_POST['pic'];
$insert_query = "INSERT INTO liste ( `pic` ) VALUES ( '".$pic."' );";
$result = mysql_query($insert_query);
The php part that shows the pic.
There's something in the table but since it's blob , I can't check if the right data.
$select_query = "Select `pic` From liste;";
$result = $dbhandle->query($select_query);
echo "<table border='1'>
<tr>
<th>Image</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><img src=\"" . $row['pic'] . "\" width=\"200\"/><br/><br/></td>";
echo "</tr>";
}
echo "</table>";
$result->closeCursor();
mysqli_close($dbhandle);
from this I get a broken image. What is missing ? Text works but not image, why ?
What you need to know is that when you are sending values encoded in json through POST, these values are not present in the $_POST variables.
The only way to have values in the POST variables is by using having the application/x-www-form-urlencoded and multipart/form-data.
If you wish to use another content-type, you actually need to use 'php://input'.
e.g.
$data = json_decode(file_get_contents('php://input'), true);
$text = print_r($data, true);
You should then see an array containing your image's data.
Related
I have a PHP script in which I get the content of a query made into a Postgresql database :
<?php
require_once 'connection.php';
$query1 = pg_query("This_is_my_query");
$instruction = "[";
while ($row = pg_fetch_array($query1)) {
$row1= $row['row1'];
$row2= $row['row2'];
$instruction .= "{name : '". $row1. "', y : ". $row2. "},";
}
$instruction .= "]";
echo $instruction;
?>
The echo $instruction gives :
[{name : 'Prestation', y : 1}]
Then I have a JS file in which I try to display and use the $instruction variable.
I use Ajax and my script is the one :
$.ajax({
url : 'Path_To_Php_File_Is_OK', // requesting a PHP script
dataType : 'json',
type: "GET",
async : false,
success : function (data) { // data contains the PHP script output
alert(data);
},
error: function(data) {
alert('error');
},
})
The result is that the success function is not called and I have the alert('error').
But when I use the dataType 'text' and not 'Json', the success function is ok and I have the alert(data).
How to explain that behaviour ? And how could I parse the PHP variable $instruction ?
Any help would ve very appreciated, thanks !
There is no need to create a json string manually. Just build up and array and encode it to json with json_encode()
You have to set JSON content-type in the response headers
Closing ?> tag is redundant and is not recommended to use (see PSR-12)
So eventually your code should look like this
<?php
require_once 'connection.php';
$query1 = pg_query("This_is_my_query");
$instructions = [];
while ($row = pg_fetch_array($query1)) {
$row1 = $row['row1'];
$row2 = $row['row2'];
$instructions[] = ['name' => $row1, 'y' => $row2];
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($instructions);
I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.
Hi i'm a beginner in using JavaScript i have this html page with JavaScript codes that receives data from the server and display it on this current page, what i'm trying to do is use that data and sending it to another PHP page for my SQL query to get back results.
<script>
var json = sessionStorage.xhr;
var object = JSON.parse(json);
var hard = object["red-fruits"];
var string = JSON.stringify (hard);
var stringData = encodeURIComponent(string);
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
cache: false,
success: function(){
console.log("OK");
}
});
var user = sessionStorage.getItem('impData');
console.log(user);
</script>
This is my PHP page codes, what i'm doing here is getting the data "dataA" from that html page and sending it to this PHP page for the SQL query and getting the results which is the "$haha" array and using JavaScript session function to send it back to the HTML page. But my console only shows "null" can anyone tell me if i'm doing anything wrong or have any suggestion would be really appreciated.
<?php
$connection = mysqli_connect("localhost","root","","") or
die("Error " . mysqli_error($connection));
if (isset($_POST['dataA'])) {
echo $name = $_POST['dataA'];
}
else {
echo "Error";
}
$string = str_replace("]", "", str_replace("[", "", str_replace('"','',$falcon)));
$array = explode(',', $string);
$array2= implode("', '",$array);
$sql = // "SQL query"
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .
mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$haha[] = $row['row_name'];
}
?>
<script type="text/javascript">
var tills = <?php echo '["' . implode('", "', $haha) . '"]' ?>;
console.log (tills);
sessionStorage.setItem('impData', tills);
</script>
You are now mixing ajax and session data on a strange way. The session data used by your javascript will not be updated by the php-script till you refresh your page. The correct way to handle data is in the "success" function:
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
dataType : "json",
cache: false,
success: function(data){
console.log(data);
}
});
and in you PHP output the data you want to send to the browser as a json string:
echo json_encode($your_object);
Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.
So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]
You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.
you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);