This multidimensional array is returned to jQuery
foreach($results as $result) {
$note_id = $result->ID;
$return_array[$note_id]['status_type'] = $result->status_type;
$return_array[$note_id]['note'] = $result->notes;
$return_array[$note_id]['username'] = $result->username;
$date_time = $result->updated;
$timestamp = strtotime($date_time);
$day_submitted = date("F jS Y", $timestamp);
$time_submitted = date("H:i", $timestamp);
$return_array[$note_id]['date_time'] = "$day_submitted<br>$time_submitted";
}
echo json_encode($return_array);
The problem is i can't access the values.. here is my attempt
jQuery.post(ajaxurl, data, function(response) {
load_btn.hide();
$.each(response, function(index, item) {
alert(response[index].status_type);
});
});
How do i solve?
You didn't parse the string to JSON.
response = JSON.parse(response);
Add this as first statement in post callback.
Related
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
I am trying to get the string "Name n" out of the php array $F[], which is randomised inside the function DataInit1(), and put it in a div inside my html file. However, the PHP file cannot be changed because the arrays are randomised and used to plot a series of graphs.
PHP file:
<?php
$Return = array();
$P = array();
$S = array();
$F = array();
$P[] = [0];
$S[] = [[0.00,111],[0.50,104.74],[1.00,91.29],[1.50,93.28],...];
$F[] = "Name 1";
$P[] = [0];
$S[] = [[0.00,199],[0.50,84.06],[1.00,82.43],[1.50,83.02],...];
$F[] = "Name 2";
for($i=0; $i<count($P); $i++)
{
$Return[] = $P[$i];
$Return[] = $S[$i];
$Return[] = $F[$i];
}
die(json_encode($Return));
?>
HTML file:
<div id="GRAPH">
<div id="title"><h1 id='graphtitle'></h1></div>
<h1 id='GraphNum'></h1>
<div id="chart"></div>
<h1 id='PointNum'></h1>
</div>
The string should be placed in the "ARRAY $F" as shown below in the JS file:
function DataInit1()
{
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(Data1)
{
SeriesList = [];
CurrentGraph.Series = 0;
for(var i=0; i<Data1.length; i+=3)
{
var P = Data1[i+0];
var S = Data1[i+1];
var F = Data1[i+2];
var NewSeries = new SeriesClass(P,S,F);
NewSeries.SeriesNumber = (i/3)+1;
SeriesList.push(NewSeries);
}
}
);
for(var i=SeriesList.length-1; i>0; i--)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
}
........
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(data)
{
var name = ARRAY $F;
});
$("#graphtitle").html(name);
}
Any other idea or suggestion on this issue will be very welcome. Thank you.
UPDATE:
Based on the suggestion by ironpilot. Could the solution be something like this?:
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("CurrentGraph.Series",
function(data)
{
var titleGraph = (json_decode($F, true));
var name = data.titleGraph[0];
$("#graphtitle").html(name);
});
}
You have a few issues in your code that you would need to correct before this is possible. First let's look at your PHP code. It appears that you want to create a few parallel arrays and then return them to your front-end code. However, the way that you add each array into the $Return array makes predicting where the elements are nearly impossible.
Let's start by converting the $Return variable to an object of stdClass. This will allow you to specify arbitrary properties on the object and make them accessible via a JavaScript object.
<?php
$Return = new stdClass();
$Return->P = array();
$Return->S = array();
$Return->F = array();
$P = array();
$S = array();
$F = array();
$P[] = [0];
$S[] = [[0.00,111],[0.50,104.74],[1.00,91.29],[1.50,93.28],...];
$F[] = "Name 1";
$P[] = [0];
$S[] = [[0.00,199],[0.50,84.06],[1.00,82.43],[1.50,83.02],...];
$F[] = "Name 2";
for($i=0; $i<count($P); $i++)
{
$Return->P = $P[$i];
$Return->S = $S[$i];
$Return->F = $F[$i];
}
die(json_encode($Return));
?>
Now that we have a little more predictable object to work with we can correct the jQuery code:
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(data)
{
var name = data.F[0]; //Select the first element of the $F array.
$("#graphtitle").html(name);
});
}
Now that we have an object that is returned from PHP you can access the array of names specifically to get the value that you need with var name = data.F[0];. Additional since this variable was declared with the var keyword inside the success function it's value would not be accessible outside of that function where it was set.
We also needed to move your selector for #graphtitle inside the jQuery success method. Since this method is actually a promise and doesn't execute until the AJAX request completes, what would have happened is that the function to set the html content of the element you were selecting would have executed before you received a response from the server with the content to place. This is called a Race Condition: https://en.wikipedia.org/wiki/Race_condition.
I hope that helps!
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.
I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .
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()+",";
});