Load data from table using PHP & AJAX - javascript

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.

Related

Foreach in Controller returns Only one Output Laravel and Ajax

I'm trying to display names from the database using Ajax and I use foreach loop in the controller but it only returns one name instead of two(it doesn't loop correctly). I have seen some answers, peoples suggested to use foreach in the view but for my case I use Ajax in the view how can I use the foreach in Ajax or is there any way it can display all names?
I have tried using these, but it was returning one name instead of two.
$data = [];
$data[] = $review->user->name;
Controller
$products = Product::where('id','=',$id)->with('reviews.user')->get();
foreach ($products as $product)
{
foreach ($product->reviews as $review){
$data = $review->user->name;
dd($data); //This returns one name
}
}
Ajax
<script >
function userRatingname() {
$.ajax({
type: "GET",
url: '{{route('userRating.name ', $id)}}',
success: function(data) {
$('#userRatingname').html('<div>' + data + '</div>');
}
});
}
userRatingname();
</script>
You are overwriting the value of $data again and again, so it will away return the last user name.
You need to put the $data = []; out of loop. and use $data[] = $review->user->name; inside the loop:
$products = Product::where('id','=',$id)->with('reviews.user')->get();
$data = array(); // defined the $data here out of loop
foreach ($products as $product)
{
foreach ($product->reviews as $review){
$data []= $review->user->name; // push the username to $data
}
}
// Or you can use whereIn for User:
$data = User::whereIn('id', ProductReview::where('product_id',$id)->pluck('user_id'))->pluck('name')->toArray();
return response()->json(['code' => 200, 'data' => $data]);
Change your ajax code:
function userRatingname() {
$.ajax({
type: "GET",
url: '{{route('userRating.name ', $id)}}',
success: function(data) {
var html = '';
data['data'].forEach(function(name) {
html += '<div>' + name + '</div>'
});
$('#userRatingname').html(html);
}
});
try this one if its right tell me.
$data = [];//define empty array.
$products = Product::where('id','=',$id)->with('reviews.user')->first();
foreach ($product->reviews as $review){
$data[]= [$review->user->name];
}
i understand your issue you are using variable not array so in loop u use array and use[your storing value]
You have forgot to add the "csrf" tag in your ajax call

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.

JSON in PHP not correctly formatted from an JQuery Ajax request

I have a JQuery AJAX request send off some JSON data to a PHP script, however, when it comes to manipulating the data or even trying to access it, it behaves like a string but I need it to behave like an associative array.
JavaScript
var all_data = [];
$.each($("[id*=card]"), function(i, value) {
var name_a = $(value).find('#story_name_div').text();
var text_a = $(value).find('#story_text_div').text();
var point_a = $(value).find('#story_point_div').text();
var phase_a = $(value).find('#story_phase').val();
var date_a = $(value).find('#story_date').val();
var author_a = $(value).find('#username_div').text();
var story_data = {
"name": name_a ,
"text": text_a ,
"point": point_a ,
"data": phase_a ,
"date": date_a ,
"author": author_a
};
all_data.push(story_data);
});
$.ajax({
url: 'save_server_script.php',
type: 'POST',
processData:false,
dataType: "json",
data: "json=" + JSON.stringify(all_data),
success: function(res){
var json_a = $.parseJSON(res);
console.log(json_a);
},
error: function(err){
console.log("error");
}
});
JSON that is created
[json] => [{"name":"jhb","text":"gjh","point":"jhv","phase":"planning","date":"21/9/2013 - 4:23:16","author":"Created by - ljhlkjhb"}]
PHP
print_r($_POST); // prints out entire JSON
print($_POST["json"][0]["story_name"]);
// Warning : Illegal string offset 'story_name' in C:\xampp\htdocs\save_server_script.php on line 15
print($_POST["json"][0]); // prints out a '['
foreach($_POST["json"] as $hello) { // invalid argument supplied for foreach
print $hello["story_name"];
}
I have also tried decoding via PHP but to no avail.
Try
$json = json_decode($_POST['json']);
echo $json[0]->author;
In your snippet you're referring to story_name, but that's not an element in your JSON string.
You have to decode the json into array in php first:
$arr = json_decode($_POST["json"]);
//now you can use foreach on the array it returned
foreach($arr as $key => $value){
//now you can use $value["text"] , $value["author"] etc
}
The data received by php is in json format that needed to be converted into array format in order to use foreach on it.
PS There is not "story_name" in your json data.

JSON parse data in javascript from php

I'm trying to retrieve data in a javascript file from a php file using json.
$items = array();
while($r = mysql_fetch_array($result)) {
$rows = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
array_push($items, array("item" => $rows));
}
ECHO json_encode($items);
and in the javascript file I try to recover the data using an ajax call:
$.ajax({
type:"POST",
url:"Locali.php",
success:function(data){
alert("1");
//var obj = jQuery.parseJSON(idata);
var json = JSON.parse(data);
alert("2");
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
The first alert is printed, the latter does not, it gives me error: Unexpected token <.... but I do not understand what it is.
Anyone have any idea where am I wrong?
I also tried to recover the data with jquery but with no positive results.
This should do it.
$.post("Locali.php",{
// any parameters you want to pass
},function(d){
alert("1");
for (var i=0; i<d.length; i++) {
point = new google.maps.LatLng(d[i].item.latitudine,d[i].item.longitudine);
alert(point);
}
}, 'json');
the PHP is fine if it is giving the response you mentioned above.
I think u should look more for the data you are getting from the php file. Definitely this is a parse error and must be missing some bracket/something else, ultimately not making the data returned to be a json parseable string.
You should be Ok with this slight modifications:
$items = array();
while($r = mysql_fetch_array($result)) {
$items[] = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
}
echo json_encode($items);
And the jQuery:
$.ajax({
type:"POST",
dataType: 'json',
url:"Locali.php",
success:function(data){
console.log(data);
for (var i=0; i<data.length; i++) {
point = new google.maps.LatLng(data[i].item.latitudine,data[i].item.longitudine);
alert(point);
}
}
})
data $.ajax({
type:"POST",
dataType: json,
url:"Locali.php",
success:function(data){
for (i in data) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
Try it like that.
yeah just try
for (var i=0; i<json[0].length; i++) {
cause you have an object there..

Why Javascript array doesn't implode in php?

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()+",";
});

Categories