How to pass JSON response in PHP to Javascript
I have problems passing a JSON request from PHP to Javascript. I am sending a request to my Flask RESTful API and I'm recieving a JSON reponse (I believe). PHP:
$urlContents = file_get_contents("http://192.168.2.201:5000/dataprovider", false, $context);
$travelArray = json_decode($urlContents);
My Object looks like this:
stdClass Object
(
[1] => stdClass Object
(
[var1] =>
[var2] =>
[var3] => 763
[var4] => 6:22:30
[var5] => München
[var6] => 58
[var7] => Bremen
[var8] => 239
)
[2] => stdClass Object
(
[var1] =>
[var2] =>
[var3] => 145
[var4] => 3:12:23
[var5] => München
[var6] => 583
[var7] => Bremen
[var8] => 9
)
)
JavaScript
<script type="text/javascript">
var response = JSON.parse('<?php echo $travelArray; ?>');
if (response != null) {
console.log(response);
} else {
console.log("test");
}
</script>
When I press F12 and look into sources it says:
var response = JSON.parse('<br />
<b>Recoverable fatal error</b>: Object of class stdClass could not be converted to string in <b>/var/www/html/greenTravelWizard.php</b> on line <b>83</b><br />
I have tried several things like using $urlContents instead of $travelArray in the JavaScript part ([1]: https://i.stack.imgur.com/Tujy3.png), but I haven't figured out how to correctly pass the JSON to a correct JavaScript format.
Also when I haven't send the request via the form yet I get
Notice: Undefined variable: context in /var/www/html/greenTravelWizard.php on line 83
Warning: file_get_contents(192.168.2.201:5000/dataprovider): failed to open stream: HTTP request failed! HTTP/1.0 405 METHOD NOT ALLOWED in /var/www/html/greenTravelWizard.php on line 83
1 answer
-
answered 2020-11-10 10:23
mplungjan
You should not decode it unless you encode it before echoing
You can likely just do
var response = <?php echo $file_get_contents("http://192.168.2.201:5000/dataprovider", false, $context); ?>;
If you have written a proxy, then you just need to do
<?php header("content-type: application/json"); echo file_get_contents("http://192.168.2.201:5000/dataprovider", false, $context); ?>
and then use
fetch
to get it from your server
See also questions close to this topic
-
Creating a linked list object using js
I want to make a linked list using
custom Object
that pushes a value, pop a value, display all its content, remove an item from a specific place, and insert at a specific place as long as the value is missing from the sequence otherwise through an exception. All of the properties should be defined using data descriptor, prevent them from being deleted, iterated, or being modified.I can do no more than this ... I'm new to js.
var linkedList = {}; /* linkedList.name = 'Ahmed'; [].push.call(linkedList, 'sad', "sd"); */ Object.defineProperty(linkedList, "name", { value: "mohamed", writable: false, configurable: false, enumerable: false }) linkedList.next = {'sd':'as'};
Any help? thanks in advance
-
Trying to trigger a CSS animation with a button press through Javascript
I'm trying to trigger a CSS animation with a button press by using Javascript. I've used other question and answers here, but to no avail. My code seems like it should work -- what am I missing? When I click the button, the background color of the div which I specify should change color over 2 seconds to light blue. I've tried changing the color of both my Body and my Test div, but nothing changes. My alert() triggers, which is confusing as it is in the same function as my colorChange.
<!DOCTYPE html> <html lang="en"> <head> <title><model-viewer> example</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script> function colorChange() { alert("The button works"); document.getElementByID('test').style.animation="changeColor"; } </script> <style> body { background-color: darkblue; -webkit-transition: all 2s ease; -moz-transition: all 2s ease; -o-transition: all 2s ease; -ms-transition: all 2s ease; transition: all 2s ease; } .test { width: 500px; height: 500px; background-color: pink; } @keyframes changeColor { to { background-color: lightblue; } } </style> </head> <body id="body"> <div class="test"></div> <button id="button" onclick="colorChange()">test animation</button> </body> </html>
-
No output from (GET) Ajax Result From Php Array with json_encode
I have a GET form that gets a Php Array and json encodes it. The Issue I am having is the success data is not displaying. I want the success to display data in a Alert or console but for some reason it's not working. I have tried many options. Thanks for your help.
PS: I know the GET and all files work because when I got the script the Ajax response result would populate/append a table successfully. I am modifying it.
Here is the php index file with the AJAX:
<!doctype html> <html> <head> <title>Return JSON response from AJAX using jQuery and PHP</title> <link href="style.css" type="text/css" rel="stylesheet"> <script src="jquery-3.1.1.min.js" type="text/javascript"></script> </head> <body> <script> $(document).ready(function() { $.ajax({ url: 'ajaxfile.php', type: 'get', dataType: 'JSON', success: function(data) { var obj = jQuery.parseJSON(data); alert(obj.username); } }); }); </script> </body> </html>
Here is the php file that queries the database and encodes/array json:
<?php $return_arr = array(); $sql = "SELECT * FROM users ORDER BY NAME"; $result = $conn->query($sql); // Check database connection first if ($conn->query($sql) === FALSE) { echo 'database connection failed'; die(); } else { while($row = $result->fetch_array()) { $id = $row['id']; $username = $row['username']; $name = $row['name']; $email = $row['email']; $return_arr[] = array("id" => $id, "username" => $username, "name" => $name, "email" => $email); } // Encoding array in JSON format echo json_encode($return_arr); } ?>
echo json_encode array output from the php file looks like below (test content):
[{"id":"1","username":"jiten","name":"Jiten singh\t","email":"jiten9"},{"id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldee"},{"id":"3","username":"mayank","name":"Mayank","email":"mayank"},{"id":"9","username":"mohit","name":"Mohit","email":"mohit"},{"id":"13","username":"mukesh","name":"Mukesh","email":"mukesh"},{"id":"6","username":"nitin","name":"Nitin","email":"niti"},{"id":"12","username":"palash","name":"Palash","email":"palash"},{"id":"7","username":"rahul","name":"Rahul singh","email":"rahul"},{"id":"10","username":"rohit","name":"Rohit singh","email":"rohit"},{"id":"8","username":"shreya","name":"Shreya","email":"shreyam"},{"id":"11","username":"sonarika","name":"Sonarika","email":"sonarika"},{"id":"5","username":"vijay","name":"Vijay","email":"vijayec"},{"id":"14","username":"vishal","name":"Vishal Sahu\t","email":"visha"},{"id":"4","username":"yssyogesh","name":"Yogesh singh","email":"yoges"}]
when I make the success result (data) and alert(data), this is what I get,empty objects
-
How Do I Clear $_GET Variables with "href"?
I have an
a
tag on my search results page (www.mysite.com/?search=test
). I would like to simply refresh the page and remove all the $_GET variables from the URL by clicking the<a>
link. Right now I am achieving this with a simple<a href="?">
but that still leaves the URL with a question mark:www.mysite.com/?
.Is it possible to have an
<a>
tag simply clear these variables completely? Or am I stuck with the question mark. -
Option value cant get full name in php form
So Im trying to put a option value of only purchased products id and names, for user to rate and comment but my code only takes the first word of product name. It should be "Hot chocolate" but it gives Hot only. And I echoed 1 index of the array name and its working fine but in below somehow its not. I really appreciate help. TY Here is my code.
-
Registration of many extensions created in Realtime MySQL at once. it's possible?
I am developing a voice robot simulator to stress the Asterisk server. I am having difficulties making calls automatically answered (auto answer) using .call files (AMI). Another difficulty is in registering extensions in large quantities. Any tips on which Asterisk applications I can use for the auto answer? Any tips on soptphone or php / python scripts that can register many extensions and make calls between them?
-
Server error while posting JSON data to server in C#
I have a problem that I can't seem to wrap my head around. I am trying to call my web api using httpClient but getting a 500 Internal server error. Searched several posts but couldn't find the exact issue. I know it is JSON formatting but not sure what's missing. Below is my client function:
[Microsoft.SqlServer.Server.SqlProcedure(Name = "myCallStoredProc")] public static void myCallStoredProc(SqlString BaseApiUrl, SqlString ApiName, SqlString ApiKey, SqlString InputJson, out int RtnCd, out string RtnMsg) { try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(BaseApiUrl.ToString()); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("API_KEY", ApiKey.ToString()); //var content = new StringContent(null, Encoding.UTF8, "application/json"); var content = new StringContent(InputJson.ToString(), Encoding.UTF8, "application/json"); var response = httpClient.PostAsync(ApiName.ToString(), content).Result; RtnCd = response.IsSuccessStatusCode == true ? 0 : -1; RtnMsg = RtnCd == -1 ? response.Content.ReadAsStringAsync().Result : ""; return; } catch (Exception ex) { RtnCd = -1; RtnMsg = ex.ToString(); } }
This is my InputJson:
"{\"PnsHandle\":\"<value>\",\"PnsType\":\"<value>\",\"Template\":\"{\"data\":{\"title\":\"$(title)\",\"message\":\"$(message)\"}}\",\"TagList\":\"<value>\",\"InstallationId\":\"<value>\",\"AzureHubServiceName\":\"<value>\",\"AzureHubName\":\"<value>\",\"AzureHubListenAccessKeyName\":\"<value>\",\"AzureHubListenAccessKeyValue\":\"<value>\"}"
When I execute myCallStoredProc with required input and above InputJson value, I get following error:
After parsing a value an unexpected character was encountered: d. Path 'Template', line 1, position 110.
My web api looks like below:
[HttpPost] public async Task<HttpResponseMessage> myAPI(HttpRequestMessage request) { try { string input = await request.Content.ReadAsStringAsync(); JObject inputValues = JObject.Parse(input); // Do Something with inputValues return Request.CreateResponse(HttpStatusCode.OK, result); } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } }
I tried to format the input json using online json formatters and after removing the escape '' the json turned out fine.
I searched multiple posts with same issues here and here but they are talking about how to send the post data like using httpwebrequest or using httpClient which I am already doing.
Any comments on what I might be doing wrong here? It seems to me the json formatting issue but not sure.
-
Python seems to only read one item per top-level arrays
I have a JSON file that I read in Python. The JSON (see below) contains two top-level items, both are arrays, containing complex structure, including other arrays at lower levels. For some reason, Python seems to only read one item from both top level arrays.
This is the JSON:
{ "deliverables": [ { "name": "<uvCode>gadget1", "objects": [ { "name": "handler-plate" }, { "name": "Cone" } ] }, { "name": "<uvCode>gadget2", "objects": [ { "name": "handler-plate" }, { "name": "Cone" } ] } ], "uvCombinations": [ { "name": "st01", "uvMapping": [ { "objectNameContains": "handler-plate", "uvLayer": "UVMap1" }, { "objectNameContains": "Cone", "uvLayer": "UVMap1" } ] }, { "name": "st02", "uvMapping": [ { "objectNameContains": "handler-plate", "uvLayer": "UVMap3" }, { "objectNameContains": "Cone", "uvLayer": "UVMap2" } ] } ] }
This is my code to read and dump the JSON file:
with open("file.json") as configFile: configuration = json.load(configFile) logging.debug("CONFIG: %s", json.dumps(configuration, indent=4))
And this is the output:
CONFIG: { "deliverables": [ { "name": "<uvCode>gadget1", "objects": [ { "name": "handler-plate" }, { "name": "Cone" } ] } ], "uvCombinations": [ { "name": "st02", "uvMapping": [ { "objectNameContains": "handler-plate", "uvLayer": "UVMap3" }, { "objectNameContains": "Cone", "uvLayer": "UVMap2" } ] } ] }
The second item of array
deliverables
(with name<uvCode>gadget2
) and the first item of arrayuvCombination
(the one with namest01
) is somehow missing.I'm not a Python expert, but I think this should work like charm, and it's strange that the missing items are not even of the same index. It get even more interesting if you observe that arrays called
objects
anduvMapping
are read properly.What am I doing wrong?, the poor guy asks
-
The JSON value could not be converted to System.Int32 python POST
I have an issue with the POST method in python.
My code :
url = "https://blablabla.com" data = { "data1": "blalba", "data2": "12" } resp = requests.post(url, json=data) print(resp.text)
My output is :
{"result":false,"data":null,"error":{"httpStatusCode":0,"errorMessages":null,"isError":false},"validationErrors":[{"field":"$.sicno","error":["The JSON value could not be converted to System.Int32. Path: $.sicno | LineNumber: 0 | BytePositionInLine: 18."]}],"isError":true}
how can I handle it? Thank you.
-
Error : Object of class stdClass could not be converted to string
I don't understand what's wrong with the code I created
public function postRegister(Request $request) { $admin = new SuperAdmin(); $admin->NIP = Input::get("NIP"); $admin->username = Input::get("username"); $admin->password = bcrypt(Input::get("password")); $admin->nama_adm = Input::get("nama_adm"); $admin->no_hp = Input::get("no_hp"); $admin->role_id = DB::table('roles')->select('id')->where('namaRole', 'superadmin')->first(); $admin->save(); }
when I'm using
var_dump($admin);
the result :
object(App\SuperAdmin)#258 (27) { ["table":protected]=> string(10) "admin_role" ["fillable":protected]=> array(3) { [0]=> string(4) "name" [1]=> string(3) "NIP" [2]=> string(8) "password" } ["hidden":protected]=> array(2) { [0]=> string(8) "password" [1]=> string(14) "remember_token" } ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(false) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(6) { ["NIP"]=> string(12) "092173092713" ["username"]=> string(5) "fazan" ["password"]=> string(60) "$2y$10$NRc7xG9VPIlmgN12gYPPF.W0vD/u7KmE/yzY5KzchyGG8xQBoJBDC" ["nama_adm"]=> string(3) "zan" ["no_hp"]=> string(9) "097123123" ["role_id"]=> object(stdClass)#268 (1) { ["id"]=> int(1) } } ["original":protected]=> array(0) { } ["changes":protected]=> array(0) { } ["casts":protected]=> array(0) { } ["classCastCache":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) { } ["dispatchesEvents":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["timestamps"]=> bool(true) ["visible":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } }
-
PHP stdClass nested properties
This used to work for me but it no longer does. What's the new / better methodology for this?
$myObj = new stdClass(); $myObj->foo->bar = "content"; $payload = json_encode($myObj);
Now I get:
Uncaught Error: Attempt to modify property "bar" on null
-
How to set new attribute in stdClass in laravel
I am creating a new stdClass Object and want to asign a array in a key. I am tying
<?php namespace App\Http\Controllers; class TestController extends Controller{ function test(){ $dataObj = new \stdClass(); $dataObj->setAttribute("open",[]); $dataObj->open=['name','age']; return $dataObj; } } ?>
I want a object like
{ 'open':[ 'name', 'age' ] }