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.
Related
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
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
I have a PHP script setup that echo's JSON responses depending on what the user has done (or not done as the case may be):
The responses look like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
Each response is generated like this:
echo $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
This is picked up by pNotify and displayed - lovely. (See below .done function for ajax request)
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var array = json_to_array(msg);
}
if (array['type'] !== 'none') {
if (array['title'] !== null) {
pushNotification(array['title'], array['response'], array['type'], array['hide']);
} else {
pushNotification(ucfirst(array['type']), array['response'], array['type'], array['hide']);
}
}
ready_status();
});
If the response cannot be validated by tryParseJSON(); the reponse is written directly to the page for debugging.
The problem is when I echo multiple responses back like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NDat]","title":"Exception","hide":false}
tryParseJSON() sees it as mumbo jumbo and prints it to the page.
Question
How do i pick up the above two lines as separate responses and parse them through my function and sub-sequentially to pNotify without combining them into a single JSON array?
Solution
As pointed out this was over complicated. Instead I combined each response (PHP side) into a an array:
$res['json'][] = $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
Then echo'ed it at the end of the script:
echo json_encode($res['json');
On client side, I used a for loop, sending them to pNotify in each iteration:
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var obj = json_to_array(msg);
}
for (var i=0;i<obj.length;i++) {
if (obj[i]['type'] !== 'none') {
if (obj[i]['title'] !== null) {
pushNotification(obj[i]['title'], obj[i]['response'], obj[i]['type'], obj[i]['hide']);
} else {
pushNotification(ucfirst(obj[i]['type']), obj[i]['response'], obj[i]['type'], obj[i]['hide']);
}
}
}
ready_status();
});
Instead of creating so sperate JSON-Outputs merge it to one single output string.
For this just wrap your two arrays you are currently outputting separately in an array like so
$myOutput[0] = responseArray1;
$myOutput[1] = responseArray2;
echo json_encode($myOutput);
This way you will get a valid JSON-response. Everything else is just some dirty workaround and causes shivers to everyone who has to review your work.
To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!
I'm using PHP, Smarty, jQuery, AJAX, Colorbox - a jQuery lightbox, etc. for my website. There is some old code done using jQuery AJAX method to display the message in popup using standard jQuery library functions. Now I want to replace that typical popup using Colorbox popup. In short Iwant to change the design part only the message part is as it is. I tried to do this but couldn't succeeded yet. Can you help me in doing the necessary changes to the existing old code in order to show the messages in Colorbox popup instead of typical popup? For your reference I'm putting the old code below:
Code from smarty template to give a call to the jQuery AJAX function is as follows:
<span class="submit edit_user_transaction_status" value="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</span>
The code from js file which contains the existing AJAX code is as follows:
$(document).ready(function() {
//This function is use for edit transaction status
$(document).on('click', '.edit_user_transaction_status', function (e) {
e.preventDefault();
$.colorbox.close();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('value');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
Now the code snippet from PHP file which contains the PHP code and success message is as follows:
case "edit_user_transaction":
$transaction_no = $request['txn_no'];
$transaction_status_update = $request['transaction_status_update'];
$transaction_data_assign = $request['transaction_data_assign'];
$user_id = $request['user_id'];
$from_date = $request['from_date'];
$to_date = $request['to_date'];
$page = $request['page'];
if($request['transaction_no']!=''){
$query = "&transaction_no=".$request['transaction_no'];
}
// If public transaction status is entered
if($request['transaction_status']!='') {
$query .= "&transaction_status=".$request['transaction_status'];
}
// For checking transaction no is empty, blank, and numeric
if($transaction_no!='' && !empty($transaction_no)) {
$objUserTransactions = new UserTransactions();
$objUserPackages = new UserPackages();
//if transaction status update to success and transaction data not yet assign
if(empty($transaction_data_assign) && $transaction_data_assign == 0 && $transaction_status_update == "success") {
$user_transactions = $objUserTransactions->GetUserTransactionsDetailsByTransactionNo($transaction_no, $user_id);
$i = 0 ;
$j = 0 ;
//Create array related study and test
foreach($user_transactions['transaction_details'] as $my_cart) {
if(!empty($my_cart['pack_id'])) {
if($my_cart['pack_type'] == 'study') {
$data['study'][$i] = $my_cart['pack_id'];
$i++;
}
if($my_cart['pack_type'] == 'test') {
$data['test'][$j]['pack_id'] = $my_cart['pack_id'];
$data['test'][$j]['pack_expiry_date'] = $my_cart['pack_expiry_date'];
$data['test_pack_ids'][$j] = $my_cart['pack_id'];
$j++;
}
}
}
if(!empty($data['study'])) {
$objUserStudyPackage = new UserStudyPackages();
//Update packages sold count & purchase date in package table
$objUserStudyPackage->UpdateStudyPackagePurchaseData($data['study']);
//For insert packages related data to package_user table
foreach($data['study'] as $study_pack_id) {
$objUserPackages->InsertStudyPackagesToPackageUser($study_pack_id, $user_id);
}
}
if(!empty($data['test'])) {
$objUserTestPackage = new UserTestPackages();
//Update packages sold count & purchase date in test package table
$objUserTestPackage->UpdateTestPackagePurchaseData($data['test_pack_ids']);
//For insert test related data to test_user table
foreach($data['test'] as $test_pack_data) {
$objUserPackages->InsertTestPackagesToTestUser($test_pack_data['pack_id'], $test_pack_data['pack_expiry_date'], $user_id);
}
}
//This function is use for update status inprocess to success and transaction_data_assign flag 1
$user_transactions = $objUserTransactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update, '1');
} else {
// This function is use for update status
$user_transaction_details = $obj_user_transactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update);
}
//Email functionality when status update
include_once("transaction_status_update_email.php");
**$reponse_data['success_massage'] = "Transaction status updated successfully";
$reponse_data['title'] = "Transaction";
$reponse_data['href'] = "view_transactions.php?page=".$page."&from_date=".$from_date."&to_date=".$to_date.$query;
$reponse_data['login_error'] = 'no';
$reponse_data = json_encode($reponse_data);
echo $reponse_data;
die();**
}
break;
The code shown in bold font is the success response message. Can you help me in this regard, please? Thanks in advance.
Yo, you asked for help in PHP chat. Hopefully this helps:
So the dialog portion at the bottom needs to change to support colorbox. Firstly, load all your colorbox stuff. Second, you'll need to create your colorbox content dynamically by either grabbing content from an element on the page or building it on the fly.
You might need to debug some of this but here's generally how you do this...
Delete the entire $dialog variable
var $dialog = .....
And change that to something that will look similar to:
var $dialog = $('<div>').addClass('ui-state-success').append($('<p>').addClass('ui-state-error-success').html(dialog_message));
Then you'll need to do something like this:
$.colorbox({html: $dialog});
If you're having trouble seeing the content that is dynamically built inside your colorbox try calling $.colorbox.resize() on the opened callback:
opened: function(){
$.colorbox.resize();
}
If that doesn't work you may also need to pass a innerWidth/innerHeight or width/height property inside the resize method.