I have a Json that I build after dropping a tab separated text into a text area (from this codepen example):
[
{
"0": "2019-08-31",
"1": "Bank Exp.",
"2": "EUR"
},
{
"0": "2019-08-31",
"1": "Legal",
"2": "EUR"
},
{
"0": "2019-08-31",
"1": "Legal",
"2": "EUR"
}
]
and is stored in variable:
jsonString = JSON.stringify(data, null, 2);
I then pass this json via ajax to a php file
var options = {
type: "POST",
url: "test.php",
data: { test: jsonString },
dataType: 'json',
success: function( data, status, xhr ) {
alert ("php:"+data);
},
error: function( xhr, status, error ) {
alert (data);
}
};
$.ajax( options );
to process a simple MYSQL insert of the different rows in the columns 0, 1, 2 in my 'test.php' file:
<?php
$host="localhost";
$user="renaud";
$pass="Mod100572$";
$db="accounting";
$con= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect to the database!!!");
$test = utf8_encode($_POST['test']);
$data_array = json_decode($test);
foreach($data_array as $row) {
$query .= "INSERT INTO `test` set
`field1` = '".$row['0']."',
`field2` = '".$row['1']."',
`field3` = '".$row["2"]."';";
}
if(mysqli_multi_query($con, $query)) {
$msg = "success";
} else {
$msg = "Something wrong! Please try again.";
}
mysqli_close($con);
?>
I Apparently do not achieve to convert my '$_POST['test']' into a correct array and the loop only gets '[' values. It is considered as a string, not an array.
I tried other parameters such as $data_array = json_decode($test,true); with no luck.
Any help to understand my error is deeply appreciated...
Insert syntax error
$query .= "INSERT INTOtestVALUES (
field1= '".$row['0']."',
field2= '".$row['1']."',
field3= '".$row["2"]."');";
Related
post function in js:
var srcd = document.getElementById("pictwo").src;
$.ajax({
type: "POST", //type of method
url: "/file.php", //your page
data: {
src: srcd
}, // passing the values
success: function(res) {
location.reload(); //do what you want here...
}
});
}
file.php:
<?php
header('Access-Control-Allow-Origin: *');
$src = $_POST["src"];
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode( $jsonString, true );
foreach ( $data as $key => $entry )
{
if ( $entry['src'] == $src )
{
$data[$key]['counter']++;
}
}
$newJsonString = json_encode( $data );
file_put_contents( 'jsonFile.json', $newJsonString );
?>
I know that the POST is successful, because I added a console.log(srcd) to the js function, and it was the desired value.
jsonFile.json:
[
{
"src": "https://",
"counter": "0"
},
{
"src": "https://",
"counter": "0"
},
{
"src": "https://",
"counter": "0"
},
The error in error_logs is :
PHP Warning: Invalid argument supplied for foreach() in /file.php on line 8
After the function is called, the json file is changed to null.
Why is this happening?
How can I fix this?
Thank you.
I need some help with a script, i have an ajax request that returns a GeoJSON
Images:
JSON Format
"id_map": "2",
"description": "AC1",
"geojson": {a GeoJSON coordinate }
"file": "AC1.geojson"
I can use AJAX JSON Leaflet (plugin( to create a polygon layer using the JSON value file ex (ac1.geojson) and point it up to a folder with the GeoJSON files (ex. geojson), but i have the same GeoJSON saved as a text variable in a database and i want to use it besides the file because of the risk of losing the files, so i recover it (i use GeoJson.io to validate the geojson and copy paste it in a column in my database) using a database connection and then i JSON encode it, but i am unable to use it. And I'm having problems with the format that comes out from the PHP.
$(document).ready(function() {
document.body.onload = function() {
var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 20,
minZoom: 13,
attribution: 'x'
}),
latlng = L.latLng(-32.0312422, -52.0917713);
var mymap = L.map('mapid', {
center: latlng,
zoom: 18,
layers: [tiles]
});
L.marker([-32.0312422, -52.0917713]).addTo(mymap);
function popUp(f, l) {
var out = [];
if (f.properties) {
for (key in f.properties) {
out.push(key + ": " + f.properties[key]);
}
l.bindPopup(out.join("<br />"));
}
}
var j_url = "somephp.php";
var results = $.ajax({
url: j_url,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(results) {
console.log("Data successfully loaded.");
alert("OK");
$.each(results, function(index, value) {
var geojsonTESTE = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-52.101760, -32.031909],
[-52.102275, -32.028598],
[-52.100794, -32.028435],
[-52.099206, -32.029053],
[-52.097554, -32.029362],
[-52.097511, -32.029672],
[-52.096760, -32.029672],
[-52.096696, -32.029544],
[-52.095795, -32.029617],
[-52.094142, -32.029835],
[-52.088585, -32.030672],
[-52.088392, -32.030763],
[-52.088027, -32.034656],
[-52.101631, -32.032145],
[-52.101760, -32.031909]
]
]
}
}]
};
var geoObject = JSON.parse(value.geojson);
L.geoJSON(geojsonTESTE).addTo(mymap);
L.geoJSON(features).addTo(mymap);
//With Leaflet Ajax e Files
//j_url = "json/"+value.file;
//var jsonTest = new L.GeoJSON.AJAX([j_url]{onEachFeature:popUp}).addTo(mymap);
});
}
function AjaxFailed(results) {
console.log("ERROR AJAX");
alert("ERRO");
}
$.when(results).done(function() {
});
};
});
<?php
header('Content-Type: application/json');
$connStr = { database connection string }
$conn = pg_connect($connStr);
$result = pg_query($conn, "select * from mapas");
$qtd = pg_num_rows($result);
$res = "[";
if($qtd > 0){
$i = 0;
foreach(pg_fetch_all($result) as $row)
{
$x = $row['geojson'];
$patterns = array ('/[^A-Za-z0-9\-\,\"\:\{\}\[\]]/');
$replace = array ('');
$desc = preg_replace($patterns, $replace,$x);
$desc = str_replace('\"', '"', $desc, $count);
$data['id_map'] = $row['id_map'];
$data['description'] = $row['description'];
$data['geojson'] = $desc;
$data['file'] = $row['file'];
$map = json_readable_encode($data,null,true);
$res .= $map;
if($i < $qtd -1 ){
$res .= ",";
}
$i++;
}
}
$res .= "]";
echo trim($res);
pg_free_result($result);
pg_close();
?>
i have json data like this :
[
{
"id_user":"31",
"grade" : "A"
},
{
"id_user":"32",
"grade" : "A"
},
{
"id_user":"33",
"grade" : "B"
},
{
"id_user":"34",
"grade" : "B"
}
]
then i send the data with jquery
$.post("myaction.php",
{send: myjsondata }, function(res) {
}, "json");
then in myaction.php, i decode the json and i want to send the data to database
$conn = mysqli_connect( "localhost","root","","mydb");
$data = json_decode($_POST['send']);
foreach($data as $row){
$id_user = $row->id_user;
$grade = $row->grade;
mysqli_query($conn, "INSERT INTO tbl_user
(id_user,grade) VALUES ('$id_user','$grade') ");
}
but the problem is i want insert with id_user where the value is equal to grade A, how can i write the query?
You can check the grade's value in the for loop.
$grade = $row->grade;
if($grade == 'A'){
//proceed here.
}
I am posting some data to a PHP file using ajax and saving it to a MySQL database. This works fine, but I also want to save one of the data elements to a text file (which should be created) on the server but I can't get it to save to a file.
This is how my code looks:
jQuery (snippet)
var uid = "1";
var name = "bruno";
var number = "0889-123-123";
var location = "{"locationInfo":[{"title":"home","lat":-16.450902223672625,"lng":10.6103515625,"speed":""},{"title":"work","lat":-14.94621907436008,"lng":17.99560546875,"speed":""}]}"
$.ajax({
type: "POST",
url: "process.php",
data: {uid:uid, name:name, number:number, location:location},
dataType: 'json',
cache: false,
})
PHP - process.php
<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
$mysqli = new mysqli('localhost', "root", "", "tp");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$mysqli->query("
INSERT INTO `table`(`uid`, `name`, `number`)
values ('".$inputvalues['uid']."', '".$inputvalues['name']."', '".$inputvalues['number']."');
");
file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));
}
mysqli_close($mysqli);
$returnResult ="success";
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
change this:
file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));
to this:
file_put_contents('saved/file.txt', $inputvalues['location']);
Also, in JS you need to remove the quotations from your location object.
It should be like this:
var location = {"locationInfo": [{"title": "home", "lat": -16.450902223672625, "lng": 10.6103515625, "speed": ""}, {"title": "work", "lat": -14.94621907436008, "lng": 17.99560546875, "speed": ""}]};
#CodeGodie $inputvalues['location'] doesn't seem to contain a file location.
Maybe like this?
file_put_contents('saved/file.txt', $inputvalues['location']);
Error:
data[i].last_name is null
I check the result from php and which has "Beñas" which triggers the null value.
xhr.queue({
url: 'controller/agents_handler.php',
data: {load_request: 'top_earners'},
type: 'POST',
success: function(data) {
var data = JSON.parse(data);
var topEarnersDiv = $('.top_earners_container ul');
var str = "";
for ( i in data) {
str += '<p class="lastname boldthis">'+data[i].last_name.substr(0,8)+'</p>';
}
topEarnersDiv.html(str);
}
Sample response:
{
"user_id": "12345",
"user_name": "johnb",
"first_name": "john",
"last_name": null
}
from php response:
it has Beñas value which becomes null
PHP:
$sql = "SELECT * FROM students WHERE x= active";
db::query($sql);
$mtd_list = array();
while ($rows = db::fetch_assoc()) :
$mtd_list[] = $rows;
endwhile;
return $mtd_list;
It should be an enconding error, if you change change the php code, you should use utf8_encode() to parse every string in that object.