so, I have an ajax call that displays my JSON like this:
{"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"}}
but I would like to have it like this:
{"main_object":{"language":"nl_NL","getExerciseTitle":"asd","question_takeAudio_exerciseWord":["asd"],"Syllablescounter":["ASDasd",""]}}
The only thing I want to add is the "id":"new".
This is my ajax call (my JSON starts looking like the first one with my ajax call)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {id: getUrlParameter('id'), formData: $('#my_form').serialize()},
dataType: 'json',
}).done(function (response) {
window.location = 'index.php';
});
});
}
edit: Ouni wanted me to show what is going on in the php script so here it is:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
} // closing off the else statement
$newExerciseData['main_object'] = $database['data'];
header('Content-Type: application/json');
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
how could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my ajax call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id')
Just to focus on your question itself without regard for the perfectly valid comments made about your overall approach, it looks like you have data in a querystring format and you want to parse it into a JSON format. The quesrystring format is the data that looks like this:
language=nl_NL&getExerciseTitle=test
And you ultimately wants this:
{
language: "nl_NL",
getExerciseTitle: "test"
}
and so on.
One way to accomplish this is to use an existing library that does precisely that for you. For example, the query-string package.
For example, given a string:
const result = "language=nl_NL&getExerciseTitle=test";
const parsed = queryString.parse(result);
will produce the result you expect.
Here's how to parse your query string in vanilla JavaScript, without installing a third-party package:
const start = {"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"}}
const temp = Object.assign({}, start);
temp.formData = decodeURIComponent(start.main_object.formData)
.split("&")
.reduce((result, data) => {
const components = data.split("=");
let prop_name = components[0];
const prop_value = components[1];
const array_char_index = prop_name.indexOf('[');
if (array_char_index > 0) {
prop_name = prop_name.substring(0, array_char_index);
if (result[prop_name] === undefined) { result[prop_name] = []; }
result[prop_name].push(prop_value);
}
else {
result[prop_name] = prop_value;
}
return result;
}, {})
;
console.log(temp.formData);
I recommend using vanilla JS whenever possible, so that you learn the concepts, and so you can adapt it to your own needs, when you find yourself wanting more.
Related
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:
{data: [{IdProduct: "1", Name: "Name here..........",…}]}
For example I want to select only Name, I tried doing this:
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
success: function (data) {
var aRC = JSON.parse(data);
for (var i = 0; i < aRC.length; i++) {
console.log(aRC[i].Name);
}
}
});
}
But this doesn't shows anything, how can I do this? This is my PHP code:
while($row = mysqli_fetch_array($registros)) {
$table.='{
"IdProduct":"'.$row['IdProduct'].'",
"Name":"'.$row['Name'].'",
"Description":"'.$row['Description'].'",
"ImagePath":"'.$row['ImagePath'].'"
},';
$table = substr($table, 0, strlen($table) -1);
echo '{"data":['.$table.']}';
}
There are couple of things you need to change in your code, such as:
That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.
$table = array();
while($row = mysqli_fetch_array($registros)) {
$table[]= array(
'IdProduct' => $row['IdProduct'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
);
}
echo json_encode($table);
Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].Name);
}
}
});
}
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.
Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:
// Define the response array
$response = [
'data' => []
];
while($row = mysqli_fetch_array($registros)) {
// Push a new array to 'data' array
$response['data'][] = [
'IdProduct' => $row['IdProduct'],
'Name' =>.$row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
];
}
// Now, let's encode the data:
echo json_encode($response);
In you PHP file make changes according to this:-
$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);
For make sure that json_encode don't return null
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));
You JavaScript is okay You just need to change code in PHP.
I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .
I'm kinda lost in how to fix a problem of mine. I've got a little code on PHP that's passing data(errors, page(id, name, title etc) trough an array and that array has been set with parseJSON. If I alert the response I will get an array with the correct value. But my problem is, that the response is always different hence it are PHP variables that change.
I've tried something like responseText.pageid or responseText.error[1], but that can't work because it can be different. And I don't know if I need to call it responseText.pageid because in the array it's $pageid or something different...
So alerting responseText is giving me a good result, but separating it won't unfortunately work.
My JS code:
// Variables
var content_page = $('#content-page').val();
var content_url = 'action=chose&page='+content_page;
/* Starting AJAX post form */
$.ajax({
type: 'POST',
dataType: "JSON",
url: 'handlers/content.handler.php',
data: content_url,
success: function(responseText)
{
var obj = $.parseJSON(responseText);
console.dir(obj.error);
if(obj.error[1] > -1)
{
noty({ text: 'U hebt geen pagina gekozen!' });
}
else if(obj.error[2] > -1)
{
noty({ text: 'De gekozen pagina bestaat niet!' });
}
else if(obj.error[100] > -1)
{
noty({ text: 'Uw pagina wordt opgehaald...' });
}
}
});
return false;
});
My PHP code:
// Storing the variables.
$stringPage = trim($_POST['page']);
$error = array();
$bolean = false;
// Prepared statement.
$stmt = $mysqli->prepare('SELECT id,name,title,text FROM pages WHERE name = ?');
$stmt->bind_param('s', $stringPage);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($pageID, $pageName, $pageTitle, $pageText);
$stmt->fetch();
$intPage = $stmt->num_rows();
$stmt->close();
# Controle
if(empty($stringPage))
{
$error[] = 1;
$bolean = false;
}
if($intPage == 0)
{
$error[] = 2;
$bolean = true;
}
if($bolean == false)
{
$error[] = 100;
}
header('Content-Type: application/json');
$aVariables = array('error' => $error, 'id' => $pageID, 'name' => $pageName, 'title' => $pageTitle, 'text' => $pageText);
echo json_encode($aVariables, JSON_FORCE_OBJECT);
I've Googled and came to the conclusion that I need to make a variable out of the parseJSON but then I get no result unfortunately. My current result(http://prntscr.com/72c39h) is working but separating it with responseText.home isn't working.
Thank you in advance, and my apologies for the bad grammar and language!
There is no need to var obj = $.parseJSON(responseText);, this responseText is already in json format. If you want to access error then just refer it by simply responseText.error or 'alert(responseText.error);' and there is also no need to set header('Content-Type: application/json');
When calling JQuery's parseJSON() you have to both call it properly, e.g. $.parseJSON(), and store it in a variable, e.g. var obj = $.parseJSON(responseText);, as per the documentation.
I am having problems passing my javascript array to a php file. i know that the JS array has the correct users input data because I have tested this by using toString() and printing the array on my web page. My plan was to use send the JS array to my php script using AJAX's but I am new to using AJAX's so there is a good chance I am doing something wrong. I have look through a good lot of different posts of people having this same problem but everything i have tried has not worked so far. All I know at this point is the JS has data in the array fine but when I try to pass it to the php file via AJAX's the php script dose not receive it. i know this because I keep getting undefined variable errors. To be fully honest I'm not to sure if the problem in how I'm trying to pass the array to the php script or if it how I'm trying to request and assign the array values to variables on the php side. At the moment my code is as follows:
My Javascript:
function createAsset(str, str, str, str, str, str, str, str, str)
{
var aID = assetID.value;
var aName = assetName.value;
var pPrice = purchasedPrice.value;
var pDate = purchasedDate.value;
var supp = supplier.value;
var cValue = currentValue.value;
var aOwner = actualOwner.value;
var wEdate = warrantyExpiryDate.value;
var dDate = destroyedDate.value;
//document.write(aID);
//var dataObject = new Array()
//dataObject[0] = aID;
//dataObject[1] = aName;
//dataObject[2] = pPrice;
//dataObject[3] = pDate;
//dataObject[4] = supp;
//dataObject[5] = cValue;
//dataObject[6] = aOwner;
//dataObject[7] = wEdate;
//dataObject[8] = dDate;
//dataObject.toString();
//document.getElementById("demo").innerHTML = dataObject;
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
$.ajax
({
type: "POST",
url: "create_asset_v1.0.php",
data: dataObject,
cache: false,
success: function()
{
alert("OK");
location.reload(true);
//window.location = 'create_asset_v1.0.php';
}
});
}
My PHP:
<?php
// Get Create form values and assign them to local variables.
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
// Connect to the SQL server.
$server='PC028\ZIRCONASSETS'; //serverName\instanceName
$connectinfo=array("Database"=>"zirconAssetsDB");
$conn=sqlsrv_connect($server,$connectinfo);
if($conn)
{
echo "Connection established.<br/><br/>";
}
else
{
echo "Connection couldn't be established.<br/><br/>";
die(print_r( sqlsrv_errors(), true));
}
// Query the database to INSERT record.
$sql = "INSERT INTO dbo.inHouseAssets
(Asset_ID, Asset_Name, Perchased_Price, Date_Perchased, Supplier, Current_Value, Actual_Owner,Worranty_Expiry_Date, Destroyed_Date)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = array($assetID, $assetName, $purchasedPrice, $purchasedDate, $supplier, $currentValue, $actualOwner, $warrantyExpiryDate, $destroyedDate);
// Do not send query database if one or more field have no value.
if($assetID && $assetName && $purchasedPrice && $purchasedDate && $supplier && $currentValue && $actualOwner && $warrantyExpiryDate && $destroyedDate != '')
{
$result = sqlsrv_query( $conn, $sql, $params);
// Check if query was executed with no errors.
if( $result === false )
{
// If errors occurred print out SQL console data.
if( ($errors = sqlsrv_errors() ) != null)
{
foreach( $errors as $error )
{
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br/>";
echo "code: ".$error[ 'code']."<br/>";
echo "message: ".$error[ 'message']."<br/>";
}
}
}
else
{
echo "Record Created!<br/>";
}
}
// Close server connection
sqlsrv_close( $conn );
if($conn)
{
echo "<br/>Connection still established.";
}
else
{
echo "<br/>Connection closed.";
}?>
Just as extra info if its not obvious from my code I am trying to send user data from a html form to a php script that process it and uses it to query a MSSQL database. This function that I am working on now is the create database entry function.
You need to match the keys you send through AJAX:
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
with the POST array keys:
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
Your code should look like this:
$assetID = $_POST['assitID'];
$assetName = $_POST['assitName'];
$purchasedPrice = $_POST['purchasedPrice'];
...
You are reading the wrong keys.
$assetID = $_POST['aID'];
Must be:
$assetID = $_POST['assitID'];
As per your sent object.
I actually have this array var checked_rls= ['24','56'];
var checked_rls = []
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls.push($(this).val());
});
and then I tried to pass it using AJAX
$.ajax(
{
type :"POST",
url : "sale_ajax.php",
data:
{
rls : checked_rls,
rls_date : $("#rls_date").val()
},
success: function(msg)
{
alert('saved successfully');
},
error: function()
{
alert("Failure");
}
});
and then i received the array in sale_ajax.php file like this $cont = $_POST['rls'];
Now the problem is that I can run this array in a forEach function, but when I tried to implode this array into a string it only returns one value.
For e.g. in this scenario I passed 24,56 and when I tried to implode(",",$cont); it only returns the very first value, 24:
var_dump($cont) output is
array(2){[0]=>string(2) "24" [1]=>string(2) "56"}
and the php code is:
if(isset($_POST['rls']))
{
$rls_date = $_POST['rls_date'];
$cont = $_POST['rls'];
$rls_cont_sold = implode(",",$cont);
$rls_insert = mysql_query("INSERT INTO release_details (release_date, cont_sold_id) VALUES (STR_TO_DATE('$rls_date', '%d-%m-%Y'), '$rls_cont_sold')")or die(mysql_error());
$id = mysql_insert_id();
foreach($cont as $val)
{
$cont_sold_update = "UPDATE cont_sold SET release_details_id = '$id' WHERE cont_sold_id = '$val'";
$insert = mysql_query($cont_sold_update)or die(mysql_error());
}
}
and the var_dump($_POST) is
array(2){
["rls"]=>(array(2){[0]=>string(2) "24" [1]=>string(2) "56"})
["rls_date"]=>string(10) "10-04-2015"
}
What is actually happening in this condition?
Thank you
Put below code in click event of chk_count element:-
$("input[name='chk_cont[]']").click(function(){
var checked_rls = [];
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls.push($(this).val());
});
});
Rather than passing passing an array why don't you pass a string itself, it will reduce your number of steps.
var checked_rls = "";
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls += $(this).val()+",";
});