How to pass JSON response in PHP to Javascript - 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

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

Related

Why am I getting a json parse error during an ajax call after updating to Codeigniter 3.x?

I am updating my Codeigniter framework from 2.2.6 to 3.0.6. It has broken the existing code that worked before. Specifically, I am getting the error "SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data" inside the browser console. I have tried to look and see if this is a known issue when updating, but I have not seen anyone else experiencing this.
Here is the javascript that I am using:
$('#addServiceItem').on('change', function() {
var serviceID = $(this).val();
$.ajax({
url: '/ajax/get_service_details/' + serviceID,
}).done(function(data) {
if (data.status == 'success') {
addServiceItem(data.service);
} else {
alert(data.message);
}
});
});
Also, here is the function that is being called in the ajax url:
public function get_service_details($serviceID = 0)
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
if ($serviceID == 0) {
header('Content-type: application/json');
echo json_encode(array(
'status' => 'error',
'service' => null,
'message' => 'We could not find the service.'
));
}
$service = $this->services_model->get_service_details($serviceID);
header('Content-type: application/json');
echo json_encode(array(
'status' => 'success',
'service' => $service,
'message' => ''
));
}
As stated above, this code worked in the previous version of Codeigniter. As far as I can tell there is an issue with the Ajax call returning a value. In the javascript variable data stays undefined. I assume that there is a syntax standard that has changed.
If your $serviceID == 0, then you get error Headers already sent because inside IF you output content and do not terminate code, and outside of IF you again try to set header.
Change your code to this one:
public function get_service_details($serviceID = 0)
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
if ($serviceID == 0) {
header('Content-type: application/json');
echo json_encode(array(
'status' => 'error',
'service' => null,
'message' => 'We could not find the service.'
));
// Terminate function execution
return;
}
$service = $this->services_model->get_service_details($serviceID);
header('Content-type: application/json');
echo json_encode(array(
'status' => 'success',
'service' => $service,
'message' => ''
));
}

Using fetch API with OOP php class - do i need a URL?

I'm trying to setup a simple Stripe payment on my Wordpress plugin. I've followed their documentation and they recommend using fetch API to get the server side paymentIntent response from a .php file like below.
fetch("/create-payment-intent.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(orderData)
})
However, my plugin is built using OOP and the code is within a class so I'm guessing if i point to this file directly it wouldn't work as it first needs to be first initialised. Is there a way of using fetch to call a method in a php class? Or is it better to use AJAX to handle the above?
Update
This is the code Stripe have in their documentation which i need to run in create-payment-intent.php. However, in my case i want to run the methods in a class so using fetch() woudln't work.
# vendor using composer
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
header('Content-Type: application/json');
# retrieve json from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$intent = null;
try {
if (isset($json_obj->payment_method_id)) {
# Create the PaymentIntent
$intent = \Stripe\PaymentIntent::create([
'payment_method' => $json_obj->payment_method_id,
'amount' => 1099,
'currency' => 'usd',
'confirmation_method' => 'manual',
'confirm' => true,
]);
}
if (isset($json_obj->payment_intent_id)) {
$intent = \Stripe\PaymentIntent::retrieve(
$json_obj->payment_intent_id
);
$intent->confirm();
}
generateResponse($intent);
} catch (\Stripe\Exception\ApiErrorException $e) {
# Display error on client
echo json_encode([
'error' => $e->getMessage()
]);
}
function generateResponse($intent) {
# Note that if your API version is before 2019-02-11, 'requires_action'
# appears as 'requires_source_action'.
if ($intent->status == 'requires_action' &&
$intent->next_action->type == 'use_stripe_sdk') {
# Tell the client to handle the action
echo json_encode([
'requires_action' => true,
'payment_intent_client_secret' => $intent->client_secret
]);
} else if ($intent->status == 'succeeded') {
# The payment didn’t need any additional actions and completed!
# Handle post-payment fulfillment
echo json_encode([
"success" => true
]);
} else {
# Invalid status
http_response_code(500);
echo json_encode(['error' => 'Invalid PaymentIntent status']);
}
}

How to fix WebPush 401 error for Google Chrome?

I'm trying to develop my own notification system on my website but I have a problem. I use firebase and his keys (I'm not using VapidKeys). One thing : every works on Firefox but not on Google Chrome.
For my application I followed this link.
and others tutorial on how does firebase works...
<?php
include_once (getenv('DOCUMENT_ROOT') . '/lib/include.php');
...
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\VAPID;
array of notifications
$notifications = array(
array(
'subscription' => Subscription::create(array(
'endpoint' => 'https://updates.push.services.mozilla.com/wpush/v1/gAAAAABcyExVQOIq3T0hJlKO6awqMrGwo0kcjjqi5mYKLddIfKcvva-2AcIMY1f1X32Zpdo3IlOqKb00eOhgUI_TTYMdmSwA6VxUjsQPgZwFmDQuvWjYnvax6yuV-WraBE9MclHMou6G', // Firefox 43+,
'publicKey' => 'BKVJQAkW1OFebroeetQBX1gVsDXQIs8TRYOk0b7ENCK3NBhOCxqCN2uAAZ5wQq7lqS0AqTu5qkKzNHH2oMQAJes', // base 64 encoded, should be 88 chars
'authToken' => 'PTYrPzIoW96SnYjjmSPvrg', // base 64 encoded, should be 24 chars
)
),
'payload' => 'hello !',
),
array(
'subscription' => Subscription::create(array(
'endpoint' => 'https://fcm.googleapis.com/fcm/send/dgSeLeTBqQs:APA91bGWVsUbkd5R9jOyqjDx5PMzuDtse1X9jGtJ3D_G_1wPehNFCq9-aEkyVSdqnzkuv5pbetE8k0rU_XrSGNvZ6WVG-7zZQJha_WvVK8zvUkGUxBsKzF6kPYMIDGZ6Qx2VjrWIbePS',
)
),
'payload' => null,
)
);
$webPush = new WebPush();
// send multiple notifications with payload
foreach ($notifications as $notification) {
$webPush->sendNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
);
}
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
echo "[v] Message sent successfully for subscription {$endpoint}.";
} else {
echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}

php json:encode returning undefined on http call on angular controller on server but works well on the localhost

php json:encode returning undefined on http call on angular controller on server but works well on the localhost.
if( hash_equals($hashed_password, crypt($password, $hashed_password))){
$pass = "true";
$result = array('pass' => $pass, 'FirstName' => $f_name,
'LastName' => $l_name,'id' => $id);
}else{
$pass = False;
$result = array('pass' => $pass, 'FirstName' => "", 'LastName' => ""
, 'id' => $id);
}
$json_response = json_encode($result);
echo $json_response;
For ajax calls, such as this requires the header to be set as application/json, so javascript can easily read it, and also need to make error reporting to false in ajax related API designs
<?php
error_reporting(0);
...
...
...
header('Content-Type:application/json;');
echo $json_response;
this output is easily readable by javascript

JavaScript code not checking ajax request properly

I have a case of the Thursdays and I am wondering why this isn't working.
The Problem: I cannot return the value of an array from AJAX request even though the page returns it successfully.
So, here's my AJAX request:
$.ajax({
type: "GET",
url: "get-sendgrid-info.php?username=" + emailToCheck,
success: function(dataSG) {
console.log("Length: " + dataSG.length + " Username: " + dataSG[0].username);
if (dataSG[0].username) {
console.log('CURRENTLY IN SEND GRID!');
$(".sgstatus").html("<div style='font-weight:bold;color:green;'>CURRENTLY IN SENDGRID</div>");
}else{
console.log('NOT IN SEND GRID!');
$(".sgstatus").html("<div style='font-weight:bold;color:red;'>NOT IN SENDGRID</div>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(errorThrown);
}
});
and that dataSG will call that php page:
if ($email) echo json_encode($data);
}
$stmt->close();
$mysqli->close();
which will output something like this:
Array
(
[0] => stdClass Object
(
[username] => sample#email.net
[email] => sample#email.net
[active] => true
[first_name] => John
[last_name] => Doe
[address] => 123 Fake Street
[address2] => Suite117
[city] => Denver
[state] => CO
[zip] => 12345
[country] => US
[phone] => 555-555-5555
[website] => http://website.com
[website_access] => true
)
)
1
(yes, even that 1).
So, when I try this after the AJAX request
if (dataSG[0].username) {
console.log('CURRENTLY IN SEND GRID!');
$(".sgstatus").html("<div style='font-weight:bold;color:green;'>CURRENTLY IN SENDGRID</div>");
}else{
console.log('NOT IN SEND GRID!');
$(".sgstatus").html("<div style='font-weight:bold;color:red;'>NOT IN SENDGRID</div>");
}
I always get NOT IN SENDGRID even though the response shows an array with a username clearly in it.
Help, please?
edit: I should add that I am on a IIS server.
edit: Response console says:
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}abort:
...
Object
create-email.php:2629 SyntaxError: Unexpected token A {stack: (...), message: "Unexpected token A"}message: "Unexpected token A"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
I think the reason is that your pho script is echoing the string start with "Array". The Ajax .get method does a smart guess for return object. When it receive a string from php, it could not convert it into either Jason nor xml so it think the dataSG is simply string. The Json_encode did not do it successfully. You have to format your php output to be something like "['a','b']", then Ajax can successfully convert it into a JavaScript array.
Try this:
...
success: function(dataSG) {
dataSG = JSON.parse(dataSG);
...

Categories

Resources