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);
}
Related
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.
I want to count the items of an array returned by json. When I use response.length, it counts all the characters in the array(I guess so) while what I want it to do is to count how many items are there in the array. Same method works in another pages, just not with this one.
This is the php code:
...$response[] = array("id" => $row['appid'],
"hour" => $row['hour'],
"tname" => $tname,
"tsurname" => $tsurname,
"cname" => $cname,
"csurname" => $csurname,
"cgsm" => $cgsm,
"cemail" => $cemail,
"cdept" => $cdept,
"cdeg" => $cdeg,
"purpose" => $purpose,
"clientnotshown" => $row['clientnotshown']);
};
if(isset($response)){
echo json_encode($response);
} else {
$response = array("val" => 0);
echo json_encode($response);
};
Javascript code:
function updateTable() {
var getData = {
date: $("#displaydate").val(),
operation:"getData"
}
$.post( "printoperations.php", getData).done(function( response ) {
if (response.val != 0){
alert("so far so good")
var arrayLength = response.length
alert(response)
alert(arrayLength)}
};
Here is a picture of what I get. I want to get the count of items, which in this case is 2.
Whatever you send back from PHP is always a string.
jQuery will however parse that string for you automagically, if you either send the correct headers, or tell it that it's JSON in the settings
$.post("printoperations.php", getData, function(response) {
if (response.val != 0) {
console.log("so far so good")
var arrayLength = response.length
console.log(response)
console.log(arrayLength)
}
}, 'json'); // <- here
And use the console for debugging
You need to parse the response var response = JSON.parse(response) and then response.length will return the desired result.
var getData = {
date: $("#displaydate").val(),
operation:"getData"
}
$.post( "printoperations.php", getData).done(function( response ) {
if (response.val != 0){
alert("so far so good")
var responseArray = JSON.parse(response)
alert(responseArray)
alert(responseArray.length)}
};
Seems you are trying to find length of string. Instead, try to alert(typeof response), If it gives string, then before doing anything parse it to JSON with JSON.parse(response) and then try.
JSON.parse(response)That did the trick. Thanks for all answers!
You should put this
header('Content-Type: application/json');
in your server side php query.
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 am working on a project that uses a function I called AjaxRequest which handles all AJAX requests I make. I have no problems in making the request however getting the request back is the issue and placing it where I want it on my page is becoming stressful.
HTML BIT
<body onLoad="calling();">
<div id="status">Status: </div>
</body>
JAVASCRIPT BIT
function calling() {
var answer = ajaxRequest("testing", "test.php", "test=test");
document.getElementById("status").innerHTML += answer[1];
document.getElementById("status").innerHTML += " " + answer[3];
}
function ajaxRequest(app, location, credentials) {
var extras = "";
if(credentials === "" || credentials) {
extras = "&" + credentials;
}
var ajax = ajaxObj("POST", location);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var obj = JSON.parse(ajax.responseText);
var arrayObj = [];
for(var i in obj) { arrayObj.push([i, obj[i]]); }
return arrayObj;
}
}
ajax.send("app=" + app + extras);
}
there are two other functions running: ajaxObj and ajaxReturn but I excluded those because they is not the problem. Furthermore, I am trying to make ajaxRequest an efficient function that could be used by more than one application without having to rewrite all the code in more than one location. All error handling acquires before the actual use of ajaxRequest.
PHP BIT
<?php
if($_POST['app'] == "testing") {
$hey = array('success' => 1, 'message' => 'Successful');
echo json_encode($hey);
exit();
}
?>
I'm using calling as a javascript function that does all error handling, this is just basic for the whole of my project however I try to get the JSON from php and convert it to array and the issue is returning the array into calling. I try to display the information on the page yet nothing works.
I am not looking to use any JQuery for my project so I would like to exclude the use of it for this piece of code.
If you want, you could set the header before sending back the json.
header('Content-Type: application/json');
Usually you don't need it, but it will tell your javascript that it's json, and the array will be transform in a javascript object. It work with Jquery, but I assume it'll work without too