Save Ajax POST data to file using PHP - php

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']);

Related

Insert JSON into Mysql problem (ajax/php)

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"]."');";

Getting a JSON from a Ajax request and creating a polygon layer in Leaflet

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();
?>

Get php id with ajax?

$.ajax({
url: "salvar.php",
type: "post",
async: false,
dataType : "html",
data: {
"feito": 1,
"id": id,
"html": html,
"css": css,
"js": js
},
success: function(data) {
alert(data.id);
}
});
I am using the following code made in ajax to send data to the php page doing the processing along with the database.
<?php
require_once 'banco/conexao.php';
if(isset($_POST['feito'])){
$id_setado = $_POST["id"];
if($id_setado === ''){
$id = base_convert(time(), 10, 36);
$busca = mysqli_query($conn,"SELECT id FROM codigos WHERE id = '$id'");
$buscaId = mysqli_fetch_array($busca);
if ($buscaId == false) {
$html = base64_encode($_POST['html']);
$css = base64_encode($_POST['css']);
$js = base64_encode($_POST['js']);
$inserir = mysqli_query($conn,"INSERT INTO codigos (id,html,css,js) VALUES ('$id','$html','$css','$js')");
}
}else{
$id = $id_setado;
$html = base64_encode($_POST['html']);
$css = base64_encode($_POST['css']);
$js = base64_encode($_POST['js']);
$atualizar = mysqli_query($conn,"UPDATE codigos SET html='$html',css='$css',js='$js' WHERE id = '$id'");
}
}
?>
What I would like is to know how I can get the $id that receives base_convert(time(), 10, 36); in the "success" response of ajax. Specifically this data that I want. How can I get this php variable with ajax?
Use echo to get the value of $id
echo $id

DataType JSON doesn't work with php

Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];

php not getting JSON object

For some reason my php can't read the json object javascript has created.
Here is is printed to the console.
{
"product": {
"shipsTo": "Please choose …",
"accountExec": "Please choose …",
"product": "Please choose …",
"productSize": "Please choose …",
"qty": "",
"comments": ""
},
"billing": {
"billingName": "",
"billingAttn": "",
"billingAddress1": "",
"billingAddress2": "",
"billingCity": "",
"billingState": "",
"billingZip": "",
"billingPhone": "",
"billingFax": "",
"billingEmail": "asdf#asdf.com"
}
}
The only thing I have filled in is the billingEmail.
I get these values by collecting about 15 fields from a form and putting them in a javascript object
$(document).ready(function(){
$('#CBS_submit').on("click", function(){
//validate
//collect information
var orderInfo = {};
orderInfo.product = {};
orderInfo.billing = {};
orderInfo.product.shipsTo = $('#CBS_ship_to_select option:selected').val();
orderInfo.product.accountExec = $('#CBS_account_execs_select option:selected').val();
orderInfo.product.product = $('#CBS_product_select option:selected').val();
orderInfo.product.productSize = $('#CBS_product_size_select option:selected').val();
orderInfo.product.qty = $('#CBS_qty').val();
orderInfo.product.comments = $('#CBS_comments').val();
//capture textarea information if other is selected for
//shipsTo, product, productSize
if ( get_selected_id ('CBS_ship_to_select') == 4 ) {
orderInfo.product.shipsTo = $('#other_ship_to_text').val();
}
if ( get_selected_id ('CBS_product_select') == 4 ) {
orderInfo.product.product = $('#other_product_text').val();
}
if ( get_selected_id ('CBS_product_size_select') == 4 ) {
orderInfo.product.productSize = $('#other_product_size_text').val();
}
orderInfo.billing.billingName = $('#CBS_billing_name').val();
orderInfo.billing.billingAttn = $('#CBS_billing_attn').val();
orderInfo.billing.billingAddress1 = $('#CBS_billing_address1').val();
orderInfo.billing.billingAddress2 = $('#CBS_billing_address2').val();
orderInfo.billing.billingCity = $('#CBS_billing_city').val();
orderInfo.billing.billingState = $('#CBS_billing_state').val();
orderInfo.billing.billingZip = $('#CBS_billing_zip').val();
orderInfo.billing.billingPhone = $('#CBS_billing_phone').val();
orderInfo.billing.billingFax = $('#CBS_billing_fax').val();
orderInfo.billing.billingEmail = $('#CBS_billing_email').val();
var orderInfoJSON = JSON.stringify(orderInfo);
console.log(orderInfoJSON);
$.ajax({
type: "POST",
url: "queries/submit_order.php",
data: "order_info=" + orderInfoJSON,
dataType: "json",
success: function (data) {
console.log('test');
}
});
});
});
then request it on the php page and start putting it into html
<?php
$order_info = $_REQUEST['order_info'];
$order_info = json_decode($order_info, TRUE);
$msg = <<<EOD
<table style='width:600px; font-family:\"Helvetica\",\"Arial\", sans-serif; margin:15px' border="0">
accessing the variables like
{$order_info['product']['product']}
But for some reason, I get nothing submitted. Even though when I copy/paste the object
$order_info = '{"product":{"shipsTo":"Please choose …","accountExec":"Please choose …","product":"Please choose …","productSize":"Please choose …","qty":"","comments":""},"billing":{"billingName":"","billingAttn":"","billingAddress1":"","billingAddress2":"","billingCity":"","billingState":"","billingZip":"","billingPhone":"","billingFax":"","billingEmail":"asdf#asdf.com"}}';
it works
what am I doing wrong?
Thanks a million!
Sending it as a string might mess stuff up if it contains special characters. Try using this method instead:
$.ajax({
type: "POST",
url: "queries/submit_order.php",
data: {order_info: orderInfoJSON},
dataType: "json",
success: function (data) {
console.log('test');
}
});

Categories