Separating PHP variables in JSON string - javascript

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.

Related

how to seperate each variable in JSON

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.

jquery ajax refreshes page on failed callback

so i'm just not sure where i'm going wrong on this issue. it's one of those things everything was working fine and i made an adjustment, then i fell asleep and can't remember what i did. so my issue is that this ajax call fails:
var url = 'lib/php/addToCart.php';
var sent = $.post(url, data, null, 'json');
sent.done(function (data) {
$('.badge').html(Object.keys(data).length);
console.log('item added to cart');
alert("Added To Your Cart. Please Continue Shopping");
});
sent.fail(function (data, b, c) {
console.log("failed adding item: " + c);
var propValue;
for(var propName in b) {
propValue = b[propName];
console.log(propName,propValue);
}
});
the only errors i can get from the fail is "error" and when i do the jqXHR error i get a function in response.
here is my php file that is being called:
session_start();
$itemNum = $_POST['upc'];
$price = $_POST['price'];
$title = $_POST['title'];
$qty = 1;
$cartData = $conn->prepare("SELECT available FROM yardSale.dvdTbl WHERE upc = ?");
$cartData->bind_param("s", $itemNum);
$cartData->execute();
$cartData->store_result();
$cartData->bind_result($available);
$cartData->fetch();
$linePrice = $price * $qty;
$cartName = $title;
$_SESSION['cart'][$cartName] = array(
"cartName" => $cartName,
"itemNum" => $itemNum,
"title" => $title,
"itemPrice" => $price,
"linePrice" => $linePrice,
"qty" => $qty,
"available" => $available
);
echo json_encode($_SESSION['cart']);
and then if you need it i have an event handler to go to the function with the ajax call:
event.stopImmediatePropagation();
var upcNum = $(this).attr('id');
var formID = 'info:' + upcNum;
console.log(upcNum);
var formData = $(this).serialize();
console.log(formData);
addItem(formData);
i'm sure this is another one of those really stupid things i'm over looking... but i can't figure out where the error would be coming from, or why the page is refreshing.
in fire bug the file just shows up red and only has the request headers, no response headers. the real kicker for me is that the php file actually processes the information like it's supposed to and the json that should be returned would be valid json.
and please don't laugh at my code... if you want to help i take criticism very well; but please don't patronize me.
Just needed event.preventDefault()... thanks Code Spirit
I think the error is in this part of code:
for(var propName in b) {
propValue = b[propName];
console.log(propName,propValue);
}
The variable propName is not the index but is the value, so you must do something like this:
for(var propIndex in Object.keys(b)) {
propValue = b[propIndex];
console.log(propIndex,propValue);
}

jQuery Ajax return few values from php

I'm picking errors from php file using ajax and i face few troubles. Like in php file i take errors into $email_error and $password_error so i want to return error reports to ajax and assign $email_error to id = "email_errors" and $password_error to id = "password_errors". Maybe someone could explain how i specify what variables i want to return and what id should it take .I will leave some commented code below. Thanks!
php
<?php
if (isset($_POST['email']) && isset($_POST['password1']) && isset($_POST['password2'])) {
$email = trim ($_POST['email']);
$password1 = trim ($_POST['password1']);
$password2 = trim ($_POST['password2']);
}
$email_error = 'No errors<br>';
$password_error = 'No errors<br>';
if (empty($email))
$email_error = ('Pleas fill in email field<br>');
if ($email == 'example')
$email_error =('There already is user with this email<br>');
if (empty($password1))
$password_error = ('Please fill in password fields<br>');
if (empty($password2))
$password_error = ('Please fill in password fields<br>');
$email_error; //this variable must be returned to ajax and assigned to id "email_errors"
$password_error; //this variable must be returned to ajax and assigned to id "password_errors"
?>
javascript
$(document).ready(function () {
$('#push_button').click(function() {
$.post('php.php',
{
email : $('#email').val(), // i take these variables to php
password1 : $('#password1').val(),
password1 : $('#password2').val()
} ,
function ( data ) { //what do i return here?
$('#email_errors').val(data); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data); //how to assign $password_error to #password_errors
}
)
})
})
to return value simply echo the variable with json_encode()
e.g.
$return_array = new array();
$return_array['email_error'] = $email_error;
$return_array['password_errors'] = $password_errors;
echo json_encode($return_array);
in the javascript function (data){}:
function ( data ) { //what do i return here?
$('#email_errors').val(data['email_error']); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data['password_errors']); //how to assign $password_error to #password_errors
}
If you want to return several variables to ajax, you would have to return some json
PHP :
// .. your php code
$ret = array("email_error" => $email_error, "password_error" => $password_error);
echo json_encode($ret);
Be careful, json_encode needs PHP >= 5.2
JS :
$.ajax({
url: "php.php",
type: "POST",
dataType: "json", // The type of data that you're expecting back from the server
data: {
email: $("#email").val(),
password1: $("#password1").val(),
password2: $("#password2").val() // careful, you had "password1" as variable name 2 times
},
success: function(obj) {
// obj is your php array, transformed into a js object
// you may want to use .html() instead of .val() since your errors are strings with html tags - depends if #email_errors / #password_errors are inputs or divs
$("#email_errors").html(obj.email_error);
$("#password_errors").html(obj.password_error);
}
});
In PHP, the following will return nothing:
$email_error;
$password_error;
Your not echo'ing the values or anything. If you want to pass two different values, I'd return a JSON object like so (in PHP):
echo json_encode(array(
'email_error' => $email_error,
'password_error' => $password_error
));
And then in JavaScript, your data should now be a JavaScript object, as jQuery should parse the JSON object and understand it as an object. So you'll be able to do like this in JavaScript:
$('#email_errors').val(data.email_error);
$('#password_errors').val(data.password_error);
If you don't want to use an array, you could create a new object and then pass that object to json_encode.
$obj = new stdClass;
$obj->email_error = $email_error;
$obj->password_error = $password_error;
echo json_encode($obj);

passing javascript array to php via jquery AJAX

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.

Values not being transfered from JS to php

I have a JS script of:
function addTasteingNote(userID,beerID)
{
//get values
var note = $('#note1').val();
var ajaxSettings = {
type: "POST",
url: "a.php",
data: "u="+userID+"&b="+beerID+"&n="+note,
success: function(data){
} ,
error: function(xhr, status, error) { alert("error: " + error); }
};
$.ajax(ajaxSettings);
return false;
}
and the php script to add to the db is:
<?php
error_log("starting code");
require_once('connect.inc.php');
$u = $_GET['uID'];
$b = $_GET['bID'];
$n = $_GET['n'];
//do some checks etc
$db = new myConnectDB();
error_log("Successfully created DB");
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ($u, '$b', '$n')";
error_log($query3);
$result = $db->query($query3);
?>
The problem is that the error log shows nothing being put into the query:
[01-Nov-2013 23:40:29] Successfully created DB
[01-Nov-2013 23:40:29] INSERT INTO x (userID,beerID,note) VALUES (, '', '')
I have put alerts in the success of the ajax call, so I know that values are being passed through...
You need to give data like
var ajaxSettings = {
type: "POST",
url: "a.php",
data: {u:userID,b:beerID,n:note},
success: function(data){
}
data wont be and Query string,And since you are posting the values through ajax you need to get them via POST only like
$u = $_POST['u'];
$b = $_POST['b'];
$n = $_POST['n'];
And your query should be like
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ('".$u."', '".$b."', '".$n."')";
And Better to use escape strings with your POST variables to prevent from SQL injection.
You are using post method so, you need to get data using $_POST or $_REQUEST instead of $_GET
$u = $_REQUEST['u'];
$b = $_REQUEST['b'];
$n = $_REQUEST['n'];

Categories