Ajax read PHP generated json - javascript

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);

First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}

As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

Related

send data from php array in javascript forEach loop to url of ajax call

I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.

Regarding Data table source data access

I have used the datatable ajax call for listing I received the below json data in ajax call:
{
"sEcho":1,
"iTotalRecords":"1",
"iTotalDisplayRecords":"1",
"aaData":[
["Demo to Mam","2"]
],
"countOfTotalRecords":2
}
How I can use the countOfTotalRecords var value on view page?
You've to decode your JSON data using json_decode, then you have an object. Looks something like this:
$json = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords"
:2}';
$decode = json_decode($json);
echo $decode->countOfTotalRecords; // this will display 2, regarding your data
use the below code
$str = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords":2}';
$arr = json_decode($str);
$tcount = $arr->countOfTotalRecords;
echo $tcount;

convert js array to php array and check its content

I want to sent a JS array to remote php server and convert it to a php array.
To check if php array is equal to js array I'm trying to get its members inside result div, but without success.
var rlist = ["title1", "title2", "title3"];
var b = JSON.stringify(rlist);
$.ajax({
url: 'reorder.php',
type: 'post',
data: {'b': b},
success: function(data) {
$("#result").html(data);
}
});
reorder.php
$rlist = json_decode( $_POST['b'], true );
echo $rlist;
try to put this code in the reorder.php
$rlist = json_decode( $_POST['b'], true );
foreach ($rlist as $value) {
echo "<div>" . $value . "</div>";
}
You can use json_decode as jQuery ajax submits it's arrays as json.
// Use as object
$json = json_decode($_POST['postdata']);
// Use as
echo $json->seomthign
$json = $_POST['postdata'];
// Output array
echo "<pre>";
var_dump(json_decode($json));
echo "</pre>";

php decode json array

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in php ?
after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"}; outputs nothing either
how can i actually get the array contents?
javascript:
var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};
myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;
myString = JSON.stringify(myObject); //this line removed
var jsonString = JSON.stringify(myObject);
$.ajax({
type: "POST",
url: "n3.php",
data: {data : jsonString},
cache: false,
success: function(aaa){
alert("OK");
$("#pageContent").html(aaa);
}
});
php:
<?php
$value = json_decode($_POST['data']);
echo $value; //this echos the whole json object
echo $value->{"key"}; //this outputs nothing
?>
You are JSON encoding your data twice on the Javascript side. When you call json_encode in PHP once, you get a JSON encoded object back. That's why echo $value outputs the whole string. If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content.
Either json_decode it again, or don't double encode it in Javascript.

json_encode with multidimensional array returning string "array" instead of data

I am passing a multidimensional array back to a .php file using json, jquery, and ajax. My goal is essentially to fill a drop down box (id=project) with multiple entries. Here's some code snippets:
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
In send_input.php (backend), I query a db, and send the information to an array. Then I use json_encode.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => "$proj_option");
echo json_encode($output);
My problem is that this is RETURNING THE STRING "Array".
For example, if I do: response.proj[0], I get "A" returned.
What gives? I've seen a few people with questions about this error, but no definite solution. Any help?
This is because you are casting $proj_option to a string by enclosing it in quotes. Just remove the quotes and you will get the array.

Categories

Resources