Parsing JSON data in WordPress - javascript

I want to get an Instagram user account info (follower, following and account name).
I used this endpoint:
https://www.instagram.com/{username}/?__a=1
When I add the username in the endpoint, it displays a JSON page that includes a lot of data such as follower, following and account name,
I use this code in WordPress for parsing the JSON code in functions.php and used a shortcode to a page.:
function insta_shortcode_func() {
$request = wp_remote_get('https://www.instagram.com/barkobco/?__a=1');
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
return $data -> { 'count'};
}
add_shortcode('count_of_followers', 'insta_shortcode_func');
But nothing is displayed, I want to display follower, following and account name data.

You need to return this to get the followers
return $data->graphql->user->edge_followed_by->count;
Here is the full code
function insta_shortcode_func()
{
$request = wp_remote_get('https://www.instagram.com/barkobco/?__a=1');
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
return $data->graphql->user->edge_followed_by->count;
}
add_shortcode('count_of_followers', 'insta_shortcode_func');
I think it will help you

Related

LocalStorage to sent to email via PHP from jQuery

I am trying to build a eCommerce/checkout system that is very bare bones, but I would like to take localStorage data and send it to PHP via jQuery or some other form (open to whatever is easiest). When the email was sent I received a '.' for 'productsInCart' and no text for 'totalCost'. I got the idea for this code from here, but seems like I am missing something on the jQuery side of things.
Relevant jQuery code (nested in a vanilla JS file):
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
// methods between
var orderDetails = localStorage.getItem('productsInCart');
var orderTotal = localStorage.getItem('totalCost');
jQuery.post("checkout-handler.php", {orderDetails: value}, function(data) {
}).fail(function(){
alert("Sorry, we messed up something on our end. Please try again.");
// localStorage.clear() on fail so the user can go back and fix issue?
// return user to previous page and show new alert?
});
jQuery.post("checkout-handler.php", {orderDetails: value}, function(data) {
// do something with PHP
}).fail(function() {
console.log('yikes');
});
Relevant PHP code:
$orderInfo = $_POST['orderDetails'];
$orderTotal = $_POST['orderTotal'];
// other variables needed are here
$body .= "".$name." ordered: ".$orderInfo. ". \r\n";
$body .= "Amount sent to paypal should be: ".$orderTotal. "\r\n";
//mail(....) is after
// HTML code to show user a confirmation message
Well you declared parameters but you never really used them:
var orderDetails = localStorage.getItem('productsInCart');
var orderTotal = localStorage.getItem('totalCost');
in your jQuery it should be:
jQuery.post("checkout-handler.php", {orderDetails: orderDetails}, function(data) {
}).fail(function(){
alert("Sorry, we messed up something on our end. Please try again.");
// localStorage.clear() on fail so the user can go back and fix issue?
// return user to previous page and show new alert?
});
jQuery.post("checkout-handler.php", {orderDetails: orderDetails}, function(data) {
// do something with PHP
}).fail(function() {
console.log('yikes');
});
You see I replaced value with orderDetails, because that holds your value.

Access $_POST data on a PayPal API returnURL

I have built a cart using localStorage and I'm using the PayPal PHP SDK to process the payment.
On clicking to pay by PayPal, via AJAX, I am posting $_POST the localStorage data (the cart) and form data (the user's details) to a PHP page where I have the PayPal API setup, which then grabs the $_POST data (to create the items, transaction, payment, redirectURLs) and on success it returns the approved URL to redirect to PayPal (using window.location.href, and this all works fine.
var formData = form.serialize();
var cartData = JSON.parse(localStorage.getItem('drfStorage'));
$.ajax({
url: rootURL + 'api/payment__paypal.php',
type: 'POST',
data: { formData: formData, cartData: cartData },
beforeSend: function() {
console.log('processing');
},
success: function(data) {
console.log('success!');
console.log(data);
window.location.href = data;
},
error: function(xhr,err) {
console.log('readyState: '+xhr.readyState+'\nstatus: '+xhr.status);
console.log('responseText: '+xhr.responseText);
}
});
Then my returnURL which is set as redirect__paypal.php?pp_success=true is visited, which if the $_GET request is 'success' then it validates and takes the payment.
This all works well up until this point. The next stage is that I want to send an email receipt to the user containing some of the data from the localStorage HOWEVER the issue is that on this returnURL there's no longer the localStorage stored in the $_POST request. I could obviously pass all this information as a $_GET request but don't really want this information in the URL (?email=&address=&order=) etc.
Is there any way or advice you can see me being able to access the localStorage OR $_POST data before it went off to PayPal on the returnURL?
Below is what is currently contained within my redirect__paypal.php to aid with explanation.
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
// Require relevent libraries
require_once('./sendgrid/sendgrid-php.php');
require_once('./api__paypal.php');
// SendGrid API init
$sgAPIKey = "REMOVED FROM EXAMPLE";
if (isset($_GET['pp_success'])) {
$approved = $_GET['pp_success'] === 'true';
if ($approved) {
$payerID = $_GET['PayerID'];
$paymentID = $_GET['paymentId'];
$payment = Payment::get($paymentID, $api);
$execution = new PaymentExecution();
$execution->setPayerId($payerID);
$payment->execute($execution, $api);
// Set email confirmation settings
$email_admin = 'REMOVED FROM EXAMPLE'; // Client
$email_customer = 'REMOVED FROM EXAMPLE';
$email_admin_subject = 'You have a new order from Testing McTest via PayPal';
$email_admin_customer = 'Your Testing McTest order';
ob_start();
require_once './confirmation__email--admin.php';
$email_admin_body = ob_get_contents();
ob_end_clean();
ob_start();
require_once './confirmation__email--customer.php';
$email_customer_body = ob_get_contents();
ob_end_clean();
// SendGrid init
function send_email($from_email, $to_email, $subject, $body/*, $attachments*/) {
global $sgAPIKey;
$from = new SendGrid\Email(null, $from_email);
$to = new SendGrid\Email(null, $to_email);
$content = new SendGrid\Content("text/html", $body);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
//foreach($attachments as $a) {
// $mail->addAttachment($a);
//}
$sg = new \SendGrid($sgAPIKey);
$response = $sg->client->mail()->send()->post($mail);
}
// Send confirmation to customer first before it clears the attachments
if ($email_customer) {
send_email($email_admin, $email_customer, $email_admin_customer, $email_customer_body/*, $attachments*/);
}
// Send to confirmation to admin
if ($email_admin) {
send_email($email_admin, $email_admin, $email_admin_subject, $email_admin_body/*, $attachments = []*/);
}
} else {
}
}
I think you need to save your data somewhere before your redirct to PayPal.
On a redirect, all $_POST fields are lost.
The easist way is to save all data in your session ($_SESSION)
You can grab it from there when you are back from PayPal ;)

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes

Pass coordinates via ajax to php server-side, and retrieve to javascript after they were processed

I want to transfer some coordinates to php (server-side) from javascript (client-side) via Ajax, and after processing (filter, etc) I want to retrieve the result to javascript, for use. The pass to php working, but I don't know how get and use the processed result from php. Any help is highly appreciated.
The php part script is:
$dbconn = pg_connect ("host=localhost port=5432 user=postgres password=xxxxxxx dbname=yyyyyyyy") or die('can not connect!'.pg_last_error());
//The nearest point of Start point
$ss='';
if (isset($_POST['kuldes_st'])){
$kuldes=$_POST['kuldes_st'];
$latk=$_POST['lat_st'];
$lngk=$_POST['lng_st'];
$query = "SELECT ST_X(the_geom), ST_Y(the_geom) FROM tbl_mypoints ORDER BY ST_Distance(the_geom, ST_GeomFromText('POINT($latk $lngk)', 4326)) LIMIT 1";
//$result = pg_query($query) or die('The query failed: ' . pg_last_error());
$result = pg_query($dbconn,$query);
if (!$result) {
die('The query failed: ' . pg_last_error());
}
else {
while ($line =pg_fetch_row($result))
{
$latitude=$line[0];
$longitude =$line[1];
$ss .= "L.latLng(".$latitude.", ".$longitude.")";
}
}
echo json_encode($ss);
}
Javascript code:
map.on('click', function(e) {
var container = L.DomUtil.create('div'),
startBtn = createButton('Start from this location', container),
destBtn = createButton('Go to this location', container);
nearestBtn = createButton('Find and go to nearest parking', container);
//Start
L.DomEvent.on(startBtn, 'click', function() {
control.spliceWaypoints(0, 1, e.latlng);
var lats=e.latlng.lat;
var lngs=e.latlng.lng;
$.ajax({
url : 'index.php',
type : 'POST',
async : true,
data : { 'kuldes_st':1,
'lat_st': lats,
'lng_st': lngs
},
success: function(data,response) {
if (response == 'success') {
alert("Post working fine");
alert(response);
console.log(data);
} else {
alert("Post don't working");
console.log(data);
}
}
});
map.closePopup();
});
I think the main problem is how to use return value.
in index.php file , you can return value without html tags. for example, if you wants to return array of number, just use code like this:
echo implode($array,",");
the data that return by ajax function is some things like this:
1,2,4,2
you can split this string to a javascript array with code like this:
var result = data.split(",");
after it, you can use the array result every where you want in jquery code.
My PHP is a bit rusty but I think the issue is that you are returning a string that is not JSON but trying to pack it up like JSON.
I think you want something more like
$ss = array();
while ($line =pg_fetch_row($result))
{
$latlng = array();
$latlng["lat"] = $line[0];
$latlng["lng"] = $line[1];
array_push($ss,$latlng);
}
echo json_encode($ss)
Forgive my PHP if it's wrong, but hopefullly from this you get the idea. At this point, the thing the server will return should look like real JSON like (
[
{"lat":46.5,"lng":24.5},
{"lat":46.5,"lng":24.5},
...
]
Then in the javascript, you can just deal with it like an array.
var latitudeOfTheFirstEntry = data[0].lat;
var longitudeOfTheSecondEntry = data[1].lng;
Do you know what L.latLng is supposed to be providing. This solution I've outlined is not using that and if that is needed, there maybe more work to figure out where that is supposed to happen.
Hope this helps

Login with facebook in codeigniter

I am using this, for login with Facebook, but i am not getting user response here is the link
http://demos.idiotminds.com/link.php?link=https://www.box.com/s/108pspt0o0oj0fpr6ghf
I have tried this solution also for codeigniter
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
for log in with Facebook but i am not getting value from this $user = $facebook->getUser(); it returns 0 value even if i have logged into Facebook.
I have used so many codes for this but did not success, kindly help me out.
I am very frustrated
Download PHP SDK for Facebook
Now create the a folder in application\libarires "facebook"
Put the "SRC" folder of PHP SDK
Now create a file with FacebookApp.php in that folder and put this code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/facebook/src/facebook.php' );
class FacebookApp extends Facebook {
var $ci;
var $facebook;
var $scope;
public function __construct() {
$this->ci =& get_instance();
$this->facebook = new Facebook(array('appId' => $this->ci->config- >item('app_id'),'secret' => $this->ci->config->item('app_secret'), 'cookie' => true));
$this->scope = 'public_profile';
}
public function login_url() {
$params = array('scope' => $this->scope);
return $this->facebook->getLoginUrl($params);
}
public function logout_url() {
return $this->facebook->getLogoutUrl(array('next' => base_url() .'logout'));
}
public function getFbObj(){
return $this->facebook;
}
public function get_user() {
$data = array();
$data['fb_user'] = $this->facebook->getUser();
if ($data['fb_user']) {
try {
$data['fb_user_profile'] = $this->facebook->api('/me');
return $data;
} catch (FacebookApiException $e) {
$this->facebook->destroySession();
$fb_login_url = $this->facebook->getLoginUrl(array('scope' => $this->scope));
redirect($fb_login_url, 'refresh');
}
}
}
Now in controller load this library
$this->load->library('facebook/FacebookApp)
in Method
$obj_fb = new FacebookApp();
$fb_user_data = $obj_fb->get_user();
$data['fb_login_url'] = $obj_fb->login_url();
put the fb_login_url in href of login button and now the login will done.
Hope it help you.
Rahul, I had a similar issue. You can find a pretty good solution here.
If you still cannot figure the solution, why don't you look into the JavaScript SDK. It is pretty straight forward and then use AJAX to act on the response that you get from Facebook.

Categories

Resources