ñ returns null - jQuery en PHP - php

I use jQuery to run a function in PHP to get data from the database.
$.ajax({
url: 'service.php',
data: { functie: type, param: radiobutton },
dataType: 'json',
success: function (data) {}
});
Everything works. Except the strings with special characters return as null in the succes function. For example: ñ
The answer for this is here explained:
Special characters break json returned to jQuery
But it doesn't work for me.
In php I tried:
$result = mysql_query("SELECT * FROM wines");
$array = array();
while($row = mysql_fetch_assoc($result)){
$array[]=htmlentities($row);
}
Who knows how to make sure everything returns in a good way?

In your while statement you're using htmlentities on an array, not a string (each key in the array is a column in the database).
You could do either of the following:
Use array_map:
while($row = mysql_fetch_assoc($result)){
$array[] = array_map("htmlentities", $row);
}
or change your while loop:
while($row = mysql_fetch_assoc($result)){
foreach ($row as $key => $value) {
$row[$key] = htmlentities($value);
}
$array[] = $row;
}

Related

save table records in associative array in php

I have an associative array. After I select my records from my table (with two columns: objName,objCost), I want to save them in my array like this:
array(
'objName'=>$row['objName'],
'objCost'=>$row['objCost']
)
How should I do this?
This is my code:
$output = '';
$arr = array();
$sql = "SELECT * FROM obj WHERE objName LIKE '%" . $_POST["search"] . "%'";
$result = $db->query($sql) or die(mysql_error());
if ($result->rowCount() != 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
//here i should insert my rows into my array
}
$json_arr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo $json_arr;
} else {
echo 'Data Not Found';
}
According to your code,
$arr[] = ['objName'=>$row['objName'],'objCost'=>$row['objCost']];
Then you can encode the array and pick up the object on the other side with javascript or php. Which ever suits you
json_encode($arr);
In you Ajax success, get the objects and use the values as you deem fit
success: function (data) {data = JSON.parse(data);
for(var i = 0; i < data.length; i++){
alert(data[i].objName);
}
}
see jQuery loop over JSON result from AJAX Success? on how to loop through your results in jquery

How to add rows to jquery table from mysql query with ajax?

I need insert rows into a jQuery DataTable from AJAX. In AJAX I call a PHP file when I make a query to my mySql database, but I get show only a character in rows. It is because the format returned is incorrect, but I can't to parse the correct format.
$query = "..myquery..";
if ($row = mysql_fetch_array($sql)) {
do {
$arr []= $row['name'];
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr); // Here I tried return array without json_encode and a lot of things...
}
I know that the format to add the rows with .DataTable().row.add() is the below, but I do not get the desired format.
[["Element software"], ["Software dist"],["Global envir"], ["Software"], ["Software list"]]
How can I get this format in the echo to returned this??
Thanks!
It is array of arrays, so you need to push an array to $arr, not a string:
$query = "..myquery..";
$arr = []; // init an empty array
// no need to do if() and do{}while() inside. You can just while(){} it
while($row = mysql_fetch_array($sql)){
$arr[]= [$row['name']]; // <== these square brackets do the trick
}
echo json_encode($arr); // still need to json_encode
do{
$arr[]= array($row['name']);
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr);
Note the
$arr[]= array($row['name']);
instead of
$arr []= $row['name'];
One:two run mysql_fetch_array($sql) because php return null;
Two:code ajax for insert table .
$.ajax({
dataType:"json",
url:"recive.php",
type:"POST",
data:{id:id},
success: function(res){
for(var j=0;j<res.length;j++)
{
$("#tabel").append("<table ><tr><td style='width:100%;' > "+res[j].id+"</td></tr></table>");
}
}

Populating a #mentions array from mysql

So, I am using the mention.js library to add a #mentionUser functionality into my application. I am wondering what is the best way to replace the array with an array I build, fetching users from my database.
I have build the query to fetch the users, I'm just not sure how to use the resulting array in jQuery below.
PHP code (pseudocode mostly, will ofc use PDO)
$fetchUsers = mysql_query("SELECT * FROM users1 WHERE organisationId = '1'");
$results = array();
while ($row = mysql_fetch_assoc($fetchUsers)) {
$results[] = $row['name'];
}
Thanks alot!
<textarea id="full"></textarea>
<script>
$("#full").mention({
delimiter: '#',
users:
[{
username: "ashley"
}, {
username: "roger"
}, {
username: "frecklefart123"
}]
});
</script>
Have your PHP script return a JSON encoded array of user objects...
$fetchUsers = mysql_query("SELECT * FROM users1 WHERE organisationId = '1'");
$results = array();
while ($row = mysql_fetch_assoc($fetchUsers)) {
$results[] = array(
'username' => $row['name']
);
}
echo json_encode($results);
And then use jQuery's $.getJSON...
$.getJSON('/users.php', function(data) {
$("#full").mention({
delimiter: '#',
users: data
});
});
Simples :)
To answer your second question; use some regex (note my example is very basic)...
$string = '#matt #james #seb';
if (preg_match_all('/#(\w+)/i', $string, $matches)) {
$mentions = $matches[1];
}

how merge arrays receiving from mysql by json_encode function

I'm sitting on this for a long time and can't find a solution:
By using the function json_ encode in php file (script below) i receives data from mysql as group of arrays e.g. ["9,8","15,14","18,17","29,40,10,9"],in the main file by use $.parseJSON function(script below),
receives a array with indexed object as ["9,8","15,14","18,17","29,40,10,9"....]
instead [9,8,15,14,18,17,29,40,10,9],
How merge all this object together??
I tried to use $.merge function, but doesn't work.Help??;-)
/////receive.php file//////
$ask = mysql_query("SELECT numbers FROM bying");
if(!ask)
{
die('incorrect ask'.mysql_error());
}
else{
$tab = array();
while ($row = mysql_fetch_assoc($ask))
{
$data=$row['numbers'];
array_push($tab,$data);
}
echo json_encode($tab);
mysql_free_result($ask);
}
html file with $.parseJSON function
$.post('receive.php', function(data)
{
var table1=[];
table1 = $.parseJSON(data);
var numbers=$.merge([],table1);)
for(var i=0;i<numbers.length;i++)
{
alert(numbers[i]);
}
}
It looks as $data is a comma separated string of numbers, if so, you can slit it on commas and then merge the two arrays:
$ask = mysql_query("SELECT numbers FROM bying");
if(!ask)
{
die('incorrect ask'.mysql_error());
}
else {
$tab = array();
while ($row = mysql_fetch_assoc($ask)) {
$data = explode( ',', $row['numbers'] );
$tab = array_merge( $tab, $data );
}
echo json_encode($tab);
mysql_free_result($ask);
}
Why not do it the 'obvious' way and iterate through the array yourself splitting each string on ',' and appending each parsed number to an array you construct as you go?
e.g.
var newNums = [];
for (var i=0; i<table1.length; i++) {
newNums = newNums.concat(table1[i].split(','));
}

parse json in javascript

I load a php/json file. This is my json file:
echo '{';
echo '"position":[';
while($inhoud = mysql_fetch_array($result))
{
echo '{';
echo '"lat":"'.$inhoud['lat'].'",';
echo '"long":"'.$inhoud['long'].'",';
echo '}';
}
echo ']}';
This works. I want to load it in my javascript and do it like this:
$.getJSON('req/position.php', function(data) {
$.each(data, function(key, val) {
newLatLng = key;
});
});
but this doesn't work. It loads the file but i don't get this data. What should i do?
Thanks,
I think you have some syntax errors in the JSON output.
When you output "long" data, you append a comma , at the end, but you should not, because "long" is the last key of the object.
You print out an object in a while cycle. These objects are part of an array. So, except for the last one, you have to append a comma , after the closing }.
And, if I can ask, why you are not using the json_encode() PHP function, instead of build all the JSON string manually? With it, you build all the data as normal PHP array, and then encode (translate) it in JSON. You will avoid all these annoying syntax stuffs.
Just try it:
$data = array();
$data['position'] = array();
while($inhoud = mysql_fetch_array($result))
{
$data['position'][] = array(
"lat" => $inhoud['lat'],
"long" => $inhoud['long']
);
}
echo json_encode($data);
You have your co-ordinates defined in the array named position. You need to iterate through that. The Array contains objects with the properties lat and long. If you want to use the values, you should try something like:
$.getJSON('req/position.php'), function(data){
$.each(data.position, function(index, value){
var newLatLng = { latitude: value.lat, longitude: value.long };
});
});
Return proper header in PHP script
header('Content-type: application/json');
And it should work.
Also use json_encode to encode PHP values into valid JSON.
Constructing JSON in php through strings works but is primitive. Start constructing an array and use json_encode().
$arr = array();
while($inhoud = mysql_fetch_array($result)){
$temp = array();
$temp['lat'] = $inhoud['lat'];
$temp['long'] = $inhoud['long'];
$arr[] = $temp;
}
echo json_encode($arr);
If all that you select in your mysql query is 'lat' and 'long' you could also just place $inhoud into $arr inside your while loop like so.
while($inhoud = mysql_fetch_array($result)){
$arr[] = $inhoud;
}
If you do this just make sure you only select columns in your mysql query that you would want to output in JSON.
$.getJSON('req/position.php', function(data) {
var obj = JSON.parse(data);
// At this point, obj is an object with your JSON data.
});
Source: MDN

Categories