json.Parse on special character and becomes null - php

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.

Related

jQuery Ajax Request fails to bring all data with SQL Query to fields

i have a form that works by filling the next select fields with data based on the previous ones, it works perfect on Localhost / Xampp with PHP8 but now when i try to get it on my server it only works "once" per category.
My problem simplified.
I select category1 and get two results based on that to the next select
Only one of these results works with returning data to the 3rd Select and the other one doesn't return anything with json_encode and only throws an error
More info:
Request that works.
{
"request": "2",
"subcategoryid": "11",
"alakategoriaID": "15"
}
[
Response which is correct.
{
"ID": "23",
"name": "Puu 25"
},
{
"ID": "24",
"name": "Puu 50"
}
Request that doesn't return anything
{
"request": "2",
"subcategoryid": "10",
"alakategoriaID": "15"
}
Main function that contains the select fields etc..
´´´<script>
$(function () {
// Country
$('#sel_country').change(function () {
var categoryID = $(this).val();
// Empty state and city dropdown
$('#sel_state').find('option').not(':first').remove();
$('#sel_city').find('option').not(':first').remove();
$('#varichanger').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 1,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_state").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 3,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#varichanger").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
// State
$('#sel_state').change(function () {
var subcategoryid = $(this).val();
var alakategoriaID = $('#sel_country').val();
// Empty city dropdown
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 2,
subcategoryid: subcategoryid,
alakategoriaID: alakategoriaID
},
dataType: 'json',
success: function (response) {
console.log(response);
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['ID'];
var name = response[i]['name'];
$("#sel_city").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
});
</script>´´´
Helper.php
include "pdoconfig.php";
error_reporting(0);
$request = 0;$request = 0;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Fetch subcategory list by categoryID
if(trim($request) == 1){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT * FROM alakategoriat WHERE kategoriaID=:kategoriaID ORDER BY subcategoryname");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$subcategorysList = $stmt->fetchAll();
$response = array();
foreach($subcategorysList as $subcategory){
$response[] = array(
"id" => $subcategory['id'],
"name" => $subcategory['subcategoryname']
);
}
echo json_encode($response);
exit;
}
// Fetch city list by subcategoryid
if(trim($request) == 2){
$kategoriaID = $_POST['alakategoriaID'];
$alakategoriaID = $_POST['subcategoryid'];
$stmt = $conn->prepare("SELECT * FROM tuotteet
WHERE kategoriaID=$kategoriaID
AND alakategoriaID=$alakategoriaID
ORDER BY productname");
$stmt->execute();
$productslist = $stmt->fetchAll();
$response = array();
foreach($productslist as $product){
$response[] = array(
"ID" => $product['ID'],
"name" => $product['productname']
);
}
echo json_encode($response);
exit;
}
if(trim($request) == 3){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT *
FROM kategoriavarit
INNER JOIN varit ON kategoriavarit.variID = varit.variID
WHERE kategoriaID=:kategoriaID");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$varilist = $stmt->fetchAll();
$response = array();
foreach($varilist as $vari){
$response[] = array(
"id" => $vari['variID'],
"name" => $vari['varinimi']
);
}
echo json_encode($response);
exit;
}
you have to save your first category value to session and use it for second time ajax call. As per your code you always get
trim($request) == 1
because each time ajax call it consider as new request. So use session or cookie for store and use parent category.
Solved the problem by clearing and reinserting my database values and following #Foramkumar Patel's answer
EDIT: Cancel that, problem was with scandinavian letters in the response from JSON causing many different problems, solved the problem by utf_8 encoding the response.

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

Error when JSON array is echoed back to AJAX script

I have a text box where I search database for a specific information.
The PHP code when I just type and click on search is the following:
try
{
$date_emp = $_POST['date_emp'];
$val = $_POST['data1'];
$gender = $_POST['gen'];
if($date_emp == "choose" && $gender == "specify")
{
$search = "SELECT * FROM employee
WHERE emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
And here the AJAX script for it:
$("#search").click(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
//console.log(txt);
if(txt == '' && drop == "choose" && gender == "specify")
{
$("#txtSearch").css('border-color', 'red');
}
else
{
if(drop == "choose" && gender == "specify")
{
$.ajax
({
url: 'search.php',
type: 'POST',
data: {data1: txt, date_emp: drop, gen: gender},
dataType: 'JSON',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Something Wrong");
}
});
}
$("#date_employed, #sex").change(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
$.ajax({
url: 'search.php',
type: 'post',
data: {data1: txt, date_emp: drop, gen: gender},
datatype: 'json',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Couldn't find any data!");
}
});
});
}
});
WHERE gender and drop are 2 drop lists that forming a search filters
When I change one of the drop lists, per example, when I choose the date equal to: this week I should see in table 2 rows.
But I can only see them in the network (in devTool), and at console tab I see the following error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
[{"id":"48","0":"48","emp_name":"Alexa","1":"Alexa","position":"Secretary","2":"Secretary","salary":"8000","3":"8000","date_employed":"2016-02-23","4":"2016-02-23","gender":"female","5":"female"}]
The PHP code when I change drop lists is:
if($date_emp == "week" && $gender == "specify")
{
$search = "SELECT * FROM employee WHERE (emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val) AND date_employed > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
When you make an ajax call and expect the response to be a json you need to send a json header from the PHP
header('Content-Type: application/json');
echo json_encode($data);
Sending the json header from the PHP will turn the "res" param in your ajax to a json object and not a json string.
If you don't send the the header you need to parse the json string into a json object
var json = JSON.parse(res);

AJAX cannot access an object data value passed from php

I have a php.php file to receive data then pass the result back to AJAX, like this:
<?php
$p1 = $_POST["p1"];
$c1 = $_POST["c1"];
$resultx['r1'] = "XXX";
$resultx['r2'] = 0;
$resultx['r3'] = 100;
$resultx['r4'] = 1000;
echo json_encode($resultx);
And in my js file I have:
$.ajax({
url: 'php.php',
type: 'POST',
data: {
p1: 5,
c1: 100
},
cache: false,
success: function (resultx) {
var result = resultx;
console.log(result);
var my1 = document.getElementById('my1');
var my2 = document.getElementById('my2');
var my3 = document.getElementById('my3');
var my4 = document.getElementById('my4');
my1.textContent = "Id : "+result.r1;
my2.textContent = "Rank : "+result.r2;
my3.textContent = "Total players : "+result.r3;
my4.textContent = "Top credit : "+result.r4;
},
});
The my1 my2 my3 my4 fields all print with undefined even though the console log show the value of:
{"r1":"XXX","r2":0, "r3":100, "r4":1000}
When I change the statement
var result = resultx;
to
var result = JSON.parse(resultx)
the javascript console prints a error message of uncaught syntax error unexpected token.
Please help!

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