Get Price for stripe integration (in form elements) in PHP - php

I integrate Stripe my website,
I find the script (works fine) but I want to put 4 articles to buy, so I need to get the price, and it doesn't work :/ I have put a hidden input, but impossible get the value
first my form (In modal) => I put an input with value 12 for example
<!-- Stylesheet file -->
<link rel="stylesheet" href="css/style.css">
<!-- Stripe JS library -->
<script src="https://js.stripe.com/v3/"></script>
<script src="js/checkout.js" STRIPE_PUBLISHABLE_KEY="<?php echo STRIPE_PUBLISHABLE_KEY; ?>" defer></script>
<div class="panel">
<div class="panel-heading">
<!-- Product Info -->
<p> <?php echo $itemName; ?></p>
<p><b>Price:</b> <?php echo '$'.$itemPrice.' '.$currency; ?></p>
</div>
<div class="panel-body">
<!-- Display status message -->
<div id="paymentResponse" class="hidden"></div>
<!-- Display a payment form -->
<form id="paymentFrm" class="hidden">
<div class="form-group">
<label>NAME</label>
<input type="text" id="name" class="field" placeholder="Enter name" required="" autofocus="">
</div>
<div class="form-group">
<label>EMAIL</label>
<input type="email" id="email" class="field" placeholder="Enter email" required="">
</div>
<input type="hidden" class="field" name="prix" id="prix" value="12" >
<div id="paymentElement">
<!--Stripe.js injects the Payment Element-->
</div>
<!-- Form submit button -->
<button id="submitBtn" class="btn btn-success">
<div class="spinner hidden" id="spinner"></div>
<span id="buttonText">Pay Now</span>
</button>
</form>
<!-- Display processing notification -->
<div id="frmProcess" class="hidden">
<span class="ring"></span> Processing...
</div>
<!-- Display re-initiate button -->
<div id="payReinit" class="hidden">
<button class="btn btn-primary" onClick="window.location.href=window.location.href.split('?')[0]"><i class="rload"></i>Re-initiate Payment</button>
</div>
</div>
</div>
JS :
// Get API Key
let STRIPE_PUBLISHABLE_KEY = document.currentScript.getAttribute('STRIPE_PUBLISHABLE_KEY');
// Create an instance of the Stripe object and set your publishable API key
const stripe = Stripe(STRIPE_PUBLISHABLE_KEY);
// Define card elements
let elements;
// Select payment form element
const paymentFrm = document.querySelector("#paymentFrm");
// Get payment_intent_client_secret param from URL
const clientSecretParam = new URLSearchParams(window.location.search).get(
"payment_intent_client_secret"
);
// Check whether the payment_intent_client_secret is already exist in the URL
setProcessing(true);
if(!clientSecretParam){
setProcessing(false);
// Create an instance of the Elements UI library and attach the client secret
initialize();
}
// Check the PaymentIntent creation status
checkStatus();
// Attach an event handler to payment form
paymentFrm.addEventListener("submit", handleSubmit);
// Fetch a payment intent and capture the client secret
let payment_intent_id;
async function initialize() {
const { id, clientSecret } = await fetch("payment_init.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ request_type:'create_payment_intent' }),
}).then((r) => r.json());
const appearance = {
theme: 'stripe',
rules: {
'.Label': {
fontWeight: 'bold',
textTransform: 'uppercase',
}
}
};
elements = stripe.elements({ clientSecret, appearance });
const paymentElement = elements.create("payment");
paymentElement.mount("#paymentElement");
payment_intent_id = id;
}
// Card form submit handler
async function handleSubmit(e) {
e.preventDefault();
setLoading(true);
let customer_name = document.getElementById("name").value;
let customer_email = document.getElementById("email").value;
let customer_prix = document.getElementById("prix").value;
const { id, customer_id } = await fetch("payment_init.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ request_type:'create_customer', payment_intent_id: payment_intent_id, name: customer_name, email: customer_email, prix: customer_prix }),
}).then((r) => r.json());
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: window.location.href+'?customer_id='+customer_id,
},
});
// This point will only be reached if there is an immediate error when
// confirming the payment. Otherwise, your customer will be redirected to
// your `return_url`. For some payment methods like iDEAL, your customer will
// be redirected to an intermediate site first to authorize the payment, then
// redirected to the `return_url`.
if (error.type === "card_error" || error.type === "validation_error") {
showMessage(error.message);
} else {
showMessage("An unexpected error occured.");
}
setLoading(false);
}
// Fetch the PaymentIntent status after payment submission
async function checkStatus() {
const clientSecret = new URLSearchParams(window.location.search).get(
"payment_intent_client_secret"
);
const customerID = new URLSearchParams(window.location.search).get(
"customer_id"
);
if (!clientSecret) {
return;
}
const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);
if (paymentIntent) {
switch (paymentIntent.status) {
case "succeeded":
// Post the transaction info to the server-side script and redirect to the payment status page
fetch("payment_init.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ request_type:'payment_insert', payment_intent: paymentIntent, customer_id: customerID }),
})
.then(response => response.json())
.then(data => {
if (data.payment_txn_id) {
window.location.href = '?o=shop&pid='+data.payment_txn_id;
} else {
showMessage(data.error);
setReinit();
}
})
.catch(console.error);
break;
case "processing":
showMessage("Your payment is processing.");
setReinit();
break;
case "requires_payment_method":
showMessage("Your payment was not successful, please try again.");
setReinit();
break;
default:
showMessage("Something went wrong.");
setReinit();
break;
}
} else {
showMessage("Something went wrong.");
setReinit();
}
}
// Display message
function showMessage(messageText) {
const messageContainer = document.querySelector("#paymentResponse");
messageContainer.classList.remove("hidden");
messageContainer.textContent = messageText;
setTimeout(function () {
messageContainer.classList.add("hidden");
messageText.textContent = "";
}, 5000);
}
// Show a spinner on payment submission
function setLoading(isLoading) {
if (isLoading) {
// Disable the button and show a spinner
document.querySelector("#submitBtn").disabled = true;
document.querySelector("#spinner").classList.remove("hidden");
document.querySelector("#buttonText").classList.add("hidden");
} else {
// Enable the button and hide spinner
document.querySelector("#submitBtn").disabled = false;
document.querySelector("#spinner").classList.add("hidden");
document.querySelector("#buttonText").classList.remove("hidden");
}
}
// Show a spinner on payment form processing
function setProcessing(isProcessing) {
if (isProcessing) {
paymentFrm.classList.add("hidden");
document.querySelector("#frmProcess").classList.remove("hidden");
} else {
paymentFrm.classList.remove("hidden");
document.querySelector("#frmProcess").classList.add("hidden");
}
}
// Show payment re-initiate button
function setReinit() {
document.querySelector("#frmProcess").classList.add("hidden");
document.querySelector("#payReinit").classList.remove("hidden");
}
and the payment_init.php where i need to get price
<?php
// Include the configuration file
require_once 'config.php';
// Include the database connection file
include_once 'dbConnect.php';
$itemPrice = $_POST['prix'];
// Include the Stripe PHP library
//require_once 'stripe-php/init.php';
require_once('vendor/autoload.php');
// Set API key
\Stripe\Stripe::setApiKey(STRIPE_API_KEY);
// Retrieve JSON from POST body
$jsonStr = file_get_contents('php://input');
$jsonObj = json_decode($jsonStr);
if($jsonObj->request_type == 'create_payment_intent'){
// Define item price and convert to cents
$itemPriceCents = round($itemPrice*100);
// Set content type to JSON
header('Content-Type: application/json');
try {
// Create PaymentIntent with amount and currency
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $itemPriceCents,
'currency' => $currency,
'description' => $itemName,
'payment_method_types' => [
'card'
]
]);
$output = [
'id' => $paymentIntent->id,
'clientSecret' => $paymentIntent->client_secret
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
}elseif($jsonObj->request_type == 'create_customer'){
$payment_intent_id = !empty($jsonObj->payment_intent_id)?$jsonObj->payment_intent_id:'';
$name = !empty($jsonObj->name)?$jsonObj->name:'';
$email = !empty($jsonObj->email)?$jsonObj->email:'';
// Ajout client a la base
try {
$customer = \Stripe\Customer::create(array(
'name' => $name,
'email' => $email
));
}catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $customer){
try {
// Mise a jour de l'intention avec l'id du client
$paymentIntent = \Stripe\PaymentIntent::update($payment_intent_id, [
'customer' => $customer->id
]);
} catch (Exception $e) {
// pour apres
}
$output = [
'id' => $payment_intent_id,
'customer_id' => $customer->id
];
echo json_encode($output);
}else{
http_response_code(500);
echo json_encode(['error' => $api_error]);
}
}elseif($jsonObj->request_type == 'payment_insert'){
$payment_intent = !empty($jsonObj->payment_intent)?$jsonObj->payment_intent:'';
$customer_id = !empty($jsonObj->customer_id)?$jsonObj->customer_id:'';
// Retrieve customer info
try {
$customer = \Stripe\Customer::retrieve($customer_id);
}catch(Exception $e) {
$api_error = $e->getMessage();
}
// Check whether the charge was successful
if(!empty($payment_intent) && $payment_intent->status == 'succeeded'){
// Transaction details
$transaction_id = $payment_intent->id;
$paid_amount = $payment_intent->amount;
$paid_amount = ($paid_amount/100);
$paid_currency = $payment_intent->currency;
$payment_status = $payment_intent->status;
$customer_name = $customer_email = '';
if(!empty($customer)){
$customer_name = !empty($customer->name)?$customer->name:'';
$customer_email = !empty($customer->email)?$customer->email:'';
}
// Check if any transaction data is exists already with the same TXN ID
$sqlQ = "SELECT id FROM transactions WHERE txn_id = ?";
$stmt = $db->prepare($sqlQ);
$stmt->bind_param("s", $transaction_id);
$stmt->execute();
$stmt->bind_result($row_id);
$stmt->fetch();
$payment_id = 0;
if(!empty($row_id)){
$payment_id = $row_id;
}else{
// Insert transaction data into the database
$sqlQ = "INSERT INTO transactions (customer_name,customer_email,item_name,item_price,item_price_currency,paid_amount,paid_amount_currency,txn_id,payment_status,created,modified) VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())";
$stmt = $db->prepare($sqlQ);
$stmt->bind_param("sssdsdsss", $customer_name, $customer_email, $itemName, $itemPrice, $currency, $paid_amount, $paid_currency, $transaction_id, $payment_status);
$insert = $stmt->execute();
if($insert){
$payment_id = $stmt->insert_id;
}
}
$output = [
'payment_txn_id' => base64_encode($transaction_id)
];
echo json_encode($output);
}else{
http_response_code(500);
echo json_encode(['error' => 'Transaction has been failed!']);
}
}
?>

Related

Append Ajax Response Multiple Times Foreach Data Send

I have a list of users who waiting for pending payment. I Would like to created a mass payment to users who have pending.
I created ajax request for that
<script>
jQuery(document).ready(function(){
$("#boxesAll").click(function () {
$('input[name="boxes[]').prop('checked', this.checked);
$submit_act.toggle( $submit_box.is(":checked") );
$submit_act_paid.toggle( $submit_box.is(":checked") );
if($(this).is(':checked')){
var numberChecked = $('input[name="boxes[]"]:checked').length;
$('#count_item').html(numberChecked +' items');
$('tr>td:first-child').addClass('bg-warning');
} else {
$('tr>td:first-child').removeClass('bg-warning');
}
});
var id,resp,
$submit_act = $(".btn-act").hide(),
$count_item = $("#count_item").hide(),
$submit_box = $('input[name="boxes[]"]').click(function() {
$submit_act.toggle( $submit_box.is(":checked") );
$count_item.toggle( $submit_box.is(":checked") );
$('input[name="boxes[]"]').change(function() {
$(this).parents('tr>td').toggleClass('bg-warning', $(this).is(':checked'));
});
var numberChecked = $('input[name="boxes[]"]:checked').length;
$('#count_item').html(numberChecked +' items selected');
});
$('.btn-act').click(function(){
var btnid = jQuery(this).attr("id");
var page = '<?=$page;?>';
id = [];
$(':checkbox:checked').each(function(i){
id[i] = $(this).val();
});
if (confirm("Are you sure to "+btnid+" these items?")) {
if(id.length === 0){
alert("Please Select atleast one item(s).");
}else{
$.ajax({
type: 'POST',
url: '/<?=$settings['admin_dir'];?>?p=jquery&act='+btnid,
data: {page:page,id:id},
beforeSend: function() {
$(".btn-act").attr("disabled", true);
$(".btn-act").html('<span class="spinner-border spinner-border-sm align-middle" role="status" aria-hidden="true"><span class="sr-only">Loading...</span></span> Please wait...');
}
}).done(function(t) {
setTimeout(function() {
data = JSON.parse(t);
if(data['result']=='success'){
var pages = "<?=$settings['admin_dir'];?>?p="+page;
if(data['type']=='payments'){
$(".btn-act").html('All Payment Paid');
$(".btn-act").attr("disabled", true);
for(var i=id.length; i>0; i--){
$("#action_response").append('<div id="resp">'+data['msg']+'</div>');
}
}
}else{
$(".btn-act").attr("disabled", false);
$(".btn-act").html('Failed to action');
}
}, 3000);
});
}
}
});
});
</script>
And the php to process it
if($_GET['act']=="payments"){
if(isset($_POST["page"]) && isset($_POST["id"])){
foreach($_POST["id"] as $id){
$details = getDetails('user_payments','id',$id);
$user = getDetails('users','id',$details["user_id"]);
}
$msg = array(
"result" => 'success',
"type" => 'payments',
"msg" => 'Successfully paid to '.$user['username']
);
echo json_encode($msg);
}
}
All code is working, but I have a problem about the result. The result always return in same result.
For example I checked 4 items for payments, the result goes here
Successfully paid to user1
Successfully paid to user1
Successfully paid to user1
Successfully paid to user1
The result I want is append each user that I checked.
Successfully paid to user1
Successfully paid to user2
Successfully paid to user3
Successfully paid to user4
So we know which user have been paid successfully.
Let me know if someone can fix this
You only return one message in your ajax response.
To get the multiple results you have to build the message in a loop
if($_GET['act']=="payments"){
if(isset($_POST["page"]) && isset($_POST["id"])){
$msg = [];
foreach($_POST["id"] as $id){
$details = getDetails('user_payments','id',$id);
$user = getDetails('users','id',$details["user_id"]);
$msg[] = 'Successfully paid to '.$user['username'];
}
$response = array(
"result" => 'success',
"type" => 'payments',
"msg" => $msg
);
echo json_encode($response);
}
}
.
for(var i=id.length; i>0; i--){
$("#action_response").append('<div id="resp">'+data.msg[i]+'</div>');
}

Unexpected token < in JSON at position 0 when submitting array form in ionic

I want to send an array data to my database through an api and when i click on submit button, i get this error exeption : EXCEPTION: Unexpected token < in JSON at position 0
I have a form in this array format format:
<ion-item class="mylist hideme">
<ion-input type="text" *ngFor="let post of postList" value="{{post.phoneNo}}" placeholder="Phone" name="phones" #phones></ion-input>
</ion-item>
<ion-item class="mylist chat-item item-remove-animate item-avatar item-icon-right list card animated fadeInUp">
<ion-input type="text" readonly name="party" placeholder="APC" value="apc"></ion-input>
<ion-input type="number" placeholder="Total Votes" name="vote" #vote></ion-input>
</ion-item>
<ion-item class="mylist chat-item item-remove-animate item-avatar item-icon-right list card animated fadeInUp">
<ion-input type="text" readonly name="party" value="pdp"></ion-input>
<ion-input type="number" placeholder="Total Votes" name="vote" #vote></ion-input>
</ion-item>
<ion-item class="mylist chat-item item-remove-animate item-avatar item-icon-right list card animated fadeInUp">
<ion-input type="text" readonly name="party" value="apga"></ion-input>
<ion-input type="number" placeholder="Total Votes" name="vote" #vote></ion-input>
</ion-item>
In my post.ts, I tried submitting it to a php api this way
#ViewChild("party") party = [];
#ViewChild("vote") vote = [];
#ViewChild("phones")phones;
submit(){
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
let data = {
party: this.party = [],
vote: this.vote = [],
phone: this.phones.value
};
let loader = this.loading.create({
content: 'Submitting, please wait…',
});
loader.present().then(() => {
this.http.post('http://myschool.com/Api/addResult.php',data, options)
.map(res => res.json())
.subscribe(res => {
loader.dismiss()
if(res=="RESULT SUCCESSFULLY ENTERED"){
let alert = this.alertCtrl.create({
//title:"CONGRATS",
subTitle:(res),
buttons: ['OK']
});
alert.present();
this.navCtrl.push(PostPage);
}else if(res=="YOU ARE NOT AUTHORISE TO SEND RESULT MORE THAN ONCE"){
let alert = this.alertCtrl.create({
//title:"ERROR",
subTitle:(res),
buttons: ['OK']
});
alert.present();
}else
{
let alert = this.alertCtrl.create({
//title:"ERROR",
subTitle:(res),
buttons: ['OK']
});
alert.present();
}
});
});
}
in my php
if (isset($data)) {
$request = json_decode($data);
$votes = $request->vote;
$partys = $request->party;
$phones = $request->phone;
}
$phone = $phones;
$party = $partys;
$vote = $votes;
$limit = count($party);
$date = date("Y-d-m h:i:s A",strtotime('+1 hour'));
$i = 0;
$Scope = 0;
$UserAuth = mysqli_query($db,"select * from Master where phoneNo = '$phone'" );
if ($fetch = mysqli_num_rows($UserAuth)){
$aso = mysqli_fetch_assoc($UserAuth);
$from = $aso['phoneNo'];
$incidentAuth = mysqli_query($db,"select * from res where trim(phoneNo) = '$from'");
if (!$fetch = mysqli_num_rows($incidentAuth)){
$upRup = "UPDATE Master SET ReportedPU = '1' WHERE trim(phoneNo) = '$from'";
mysqli_query($db,$upRup);
while($i < 6){
$vcast = $vote[$i];
$pcast = $party[$i];
if($i+1<= 6){
$sql = "insert into res (phoneNo,category,cNo,date) values ('$from','$pcast','$vcast','$date')";
$result = mysqli_query($db,$sql);
}else{
$Scope = "200";
}
$i++;
}
if($Scope == "200"){
$response = 'RESULT NOT SUCCESSFULLY ENTERED. PLEASE TRY AGAIN ' .$db->err;
}else{
$response = 'RESULT SUCCESSFULLY ENTERED';
}
}else{
$response = 'YOU ARE NOT AUTHORISE TO SEND RESULT MORE THAN ONCE';
}
}else{
$response = "THIS IS AN UNCONFIRMED AGENT";
}
echo json_encode( $response);
$db->close();
I have tried everything possible but to no avail. How can I submit the array form and pass it to my php?
Now where I’m stuck is how submit the array values values in ionic.
Thanks.

Display chat for specific page

I use a ready php ajax chat script.The problem is that i can't make it to allow chats according to specific page.
How can i edit the code to allow chatting for specific page and prevent data entry to be the same in all pages.
simply,how can i allow the chat to be between the 2 selected users in a specific page only.
HTML:
<div id="chatTopBar" class="rounded"></div>
<div class="line_holder" id="chatLineHolder<?php echo htmlspecialchars($_GET['did']); ?>"></div>
<input type="hidden" name="did_hidden" id="did_hidden" value="<?php echo htmlspecialchars($_GET['did']); ?>" />
<!--<div id="chatUsers" class="rounded"></div> -->
<div id="chatBottomBar" class="rounded">
<div class="tip"></div>
<form id="loginForm" method="post" action="">
<input id="name" name="name" value="<?php echo $_SESSION['real_name']; ?>-<?php echo htmlspecialchars($_GET['deal_no']); ?>" class="rounded" maxlength="16" />
<input id="email" name="email" value="<?php echo $_SESSION['username']; ?>" class="rounded" />
<input type="submit" class="blueButton" value="Login" />
</form>
<form id="submitForm" method="post" action="">
<input type="hidden" name="did_hidden" id="did_hidden" value="<?php echo $_GET['did']; ?>" />
<textarea cols="40" id="chatText" name="chatText" class="rounded"></textarea>
<!-- <input id="chatText" name="chatText" class="rounded" maxlength="255" /> -->
<input type="submit" class="blueButton" value="send" />
</form>
</div>
Js:
$(document).ready(function(){
//toggle
$("#toggle_seller").click(function(){
$("#toggle_seller_details").slideToggle();
})
$("#toggle_buyer").click(function(){
$("#toggle_buyer_details").slideToggle();
})
// Run the init method on document ready:
chat.init();
});
var chat = {
// data holds variables for use in the class:
data : {
lastID : 0,
noActivity : 0
},
// Init binds event listeners and sets up timers:
init : function(){
// Using the defaultText jQuery plugin, included at the bottom:
var username=$("#name").val();
var email=$("#email").val();
$('#name').defaultText(username);
$('#email').defaultText(email);
var line_holder=$('.line_holder').attr('id');
// Converting the #x div into a jScrollPane,
// and saving the plugin's API in chat.data:
chat.data.jspAPI = $('#'+line_holder).jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}).data('jsp');
// We use the working variable to prevent
// multiple form submissions:
var working = false;
// Logging a person in the chat:
$('#loginForm').submit(function(){
if(working) return false;
working = true;
// Using our tzPOST wrapper function
// (defined in the bottom):
$.tzPOST('login',$(this).serialize(),function(r){
working = false;
if(r.error){
chat.displayError(r.error);
}
else chat.login(r.name,r.gravatar);
});
return false;
});
// Submitting a new chat entry:
$('#submitForm').submit(function(){
var text = $('#chatText').val();
if(text.length == 0){
return false;
}
if(working) return false;
working = true;
// Assigning a temporary ID to the chat:
var line_holder=$('.line_holder').attr('id');
var tempID = 't'+Math.round(Math.random()*1000000),
params = {
id : tempID,
author : chat.data.name,
gravatar : chat.data.gravatar,
text : text.replace(/</g,'<').replace(/>/g,'>')
};
// Using our addChatLine method to add the chat
// to the screen immediately, without waiting for
// the AJAX request to complete:
chat.addChatLine($.extend({},params));
// Using our tzPOST wrapper method to send the chat
// via a POST AJAX request:
$.tzPOST('submitChat',$(this).serialize(),function(r){
working = false;
$('#chatText').val('');
$('div.chat-'+tempID).remove();
params['id'] = r.insertID;
chat.addChatLine($.extend({},params));
});
return false;
});
// Logging the user out:
$('a.logoutButton').live('click',function(){
$('#chatTopBar > span').fadeOut(function(){
$(this).remove();
});
$('#submitForm').fadeOut(function(){
$('#loginForm').fadeIn();
});
$.tzPOST('logout');
return false;
});
// Checking whether the user is already logged (browser refresh)
$.tzGET('checkLogged',function(r){
if(r.logged){
chat.login(r.loggedAs.name,r.loggedAs.gravatar);
}
});
// Self executing timeout functions
(function getChatsTimeoutFunction(){
chat.getChats(getChatsTimeoutFunction);
})();
(function getUsersTimeoutFunction(){
chat.getUsers(getUsersTimeoutFunction);
})();
},
// The login method hides displays the
// user's login data and shows the submit form
login : function(name,gravatar){
chat.data.name = name;
chat.data.gravatar = gravatar;
$('#chatTopBar').html(chat.render('loginTopBar',chat.data));
$('#loginForm').fadeOut(function(){
$('#submitForm').fadeIn();
$('#chatText').focus();
});
},
// The render method generates the HTML markup
// that is needed by the other methods:
render : function(template,params){
// template=$('.line_holder').attr('id');
var arr = [];
switch(template){
case 'loginTopBar':
arr = [
'<span><img src="',params.gravatar,'" width="23" height="23" />',
'<span class="name">',params.name,
'</span>خروج</span>'];
break;
case 'chatLine':
arr = [
'<div class="chat chat-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />','</span><span class="author">',params.author,
':</span><span class="text">',params.text,'</span><span class="time">',params.time,'</span></div>'];
break;
case 'user':
arr = [
'<div class="user" title="',params.name,'"><img src="',
params.gravatar,'" width="30" height="30" onload="this.style.visibility=\'visible\'" /></div>'
];
break;
}
// A single array join is faster than
// multiple concatenations
return arr.join('');
},
// The addChatLine method ads a chat entry to the page
addChatLine : function(params){
var line_holder=$('.line_holder').attr('id');
// All times are displayed in the user's timezone
var d = new Date();
if(params.time) {
// PHP returns the time in UTC (GMT). We use it to feed the date
// object and later output it in the user's timezone. JavaScript
// internally converts it for us.
d.setUTCHours(params.time.hours,params.time.minutes);
}
params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
(d.getMinutes() < 10 ? '0':'') + d.getMinutes();
var markup = chat.render('chatLine',params),
exists = $("#"+line_holder + " .chat-"+params.id);
if(exists.length){
exists.remove();
}
if(!chat.data.lastID){
// If this is the first chat, remove the
// paragraph saying there aren't any:
$('#'+line_holder+' p').remove();
}
// If this isn't a temporary chat:
if(params.id.toString().charAt(0) != 't'){
var previous = $('#'+line_holder+' .chat-'+(+params.id - 1));
if(previous.length){
previous.after(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
// As we added new content, we need to
// reinitialise the jScrollPane plugin:
chat.data.jspAPI.reinitialise();
chat.data.jspAPI.scrollToBottom(true);
},
// This method requests the latest chats
// (since lastID), and adds them to the page.
getChats : function(callback){
$.tzGET('getChats',{lastID: chat.data.lastID},function(r){
for(var i=0;i<r.chats.length;i++){
chat.addChatLine(r.chats[i]);
}
if(r.chats.length){
chat.data.noActivity = 0;
chat.data.lastID = r.chats[i-1].id;
}
else{
// If no chats were received, increment
// the noActivity counter.
chat.data.noActivity++;
}
if(!chat.data.lastID){
chat.data.jspAPI.getContentPane().html('<p class="noChats">لايوجد محادثات</p>');
}
// Setting a timeout for the next request,
// depending on the chat activity:
var nextRequest = 1000;
// 2 seconds
if(chat.data.noActivity > 3){
nextRequest = 2000;
}
if(chat.data.noActivity > 10){
nextRequest = 5000;
}
// 15 seconds
if(chat.data.noActivity > 20){
nextRequest = 15000;
}
setTimeout(callback,nextRequest);
});
},
// Requesting a list with all the users.
getUsers : function(callback){
$.tzGET('getUsers',function(r){
var users = [];
for(var i=0; i< r.users.length;i++){
if(r.users[i]){
users.push(chat.render('user',r.users[i]));
}
}
var message = '';
if(r.total<1){
message = 'No one is online';
}
else {
message = r.total+' '+(r.total == 1 ? 'person':'people')+' online';
}
users.push('<p class="count">'+message+'</p>');
$('#chatUsers').html(users.join(''));
setTimeout(callback,15000);
});
},
// This method displays an error message on the top of the page:
displayError : function(msg){
var elem = $('<div>',{
id : 'chatErrorMessage',
html : msg
});
elem.click(function(){
$(this).fadeOut(function(){
$(this).remove();
});
});
setTimeout(function(){
elem.click();
},5000);
elem.hide().appendTo('body').slideDown();
}
};
// Custom GET & POST wrappers:
$.tzPOST = function(action,data,callback){
$.post('php/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?action='+action,data,callback,'json');
}
// A custom jQuery method for placeholder text:
$.fn.defaultText = function(value){
var element = this.eq(0);
element.data('defaultText',value);
element.focus(function(){
if(element.val() == value){
element.val('').removeClass('defaultText');
}
}).blur(function(){
if(element.val() == '' || element.val() == value){
element.addClass('defaultText').val(value);
}
});
return element.blur();
}
ajax.php
<?php
session_start();
/* Database Configuration. Add your details below */
$dbOptions = array(
'db_host' => 'localhost',
'db_user' => 'root',
'db_pass' => '',
'db_name' => 'bitcoin'
);
/* Database Config End */
error_reporting(E_ALL ^ E_NOTICE);
require "classes/DB.class.php";
require "classes/Chat.class.php";
require "classes/ChatBase.class.php";
require "classes/ChatLine.class.php";
require "classes/ChatUser.class.php";
session_name('webchat');
session_start();
if(get_magic_quotes_gpc()){
// If magic quotes is enabled, strip the extra slashes
array_walk_recursive($_GET,create_function('&$v,$k','$v = stripslashes($v);'));
array_walk_recursive($_POST,create_function('&$v,$k','$v = stripslashes($v);'));
}
try{
// Connecting to the database
DB::init($dbOptions);
$response = array();
// Handling the supported actions:
switch($_GET['action']){
case 'getdid':
$response=Chat::getdid($_GET['did']);
break;
case 'login':
$response = Chat::login($_POST['name'],$_POST['email']);
break;
case 'checkLogged':
$response = Chat::checkLogged();
break;
case 'logout':
$response = Chat::logout();
break;
case 'submitChat':
$response = Chat::submitChat($_POST['chatText']);
break;
case 'getUsers':
$response = Chat::getUsers();
break;
case 'getChats':
$Chat2=new Chat;
$response = $Chat2->getChats($_GET['lastID']);
break;
default:
throw new Exception('Wrong action');
}
echo json_encode($response);
}
catch(Exception $e){
die(json_encode(array('error' => $e->getMessage())));
}
?>
chat.class.php:
<?php
/* The Chat class exploses public static methods, used by ajax.php */
class Chat {
public static function login($name,$email){
if(!$name || !$email){
throw new Exception('Fill in all the required fields.');
}
if(!filter_input(INPUT_POST,'email',FILTER_DEFAULT)){
throw new Exception('Your email is invalid.');
}
// Preparing the gravatar hash:
$gravatar = md5(strtolower(trim($email)));
//$gravatar = md5(uniqid());
$user = new ChatUser(array(
'name' => $name,
'gravatar' => $gravatar
));
// The save method returns a MySQLi object
if($user->save()->affected_rows != 1){
throw new Exception('اختار اسم مستعار اخر');
}
$_SESSION['user'] = array(
'name' => $name,
'gravatar' => $gravatar
);
return array(
'status' => 1,
'name' => $name,
'gravatar' => Chat::gravatarFromHash($gravatar)
);
}
public static function checkLogged(){
$response = array('logged' => false);
if($_SESSION['user']['name']){
$response['logged'] = true;
$response['loggedAs'] = array(
'name' => $_SESSION['user']['name'],
'gravatar' => Chat::gravatarFromHash($_SESSION['user']['gravatar'])
);
}
return $response;
}
public static function logout(){
DB::query("DELETE FROM webchat_users WHERE name = '".DB::esc($_SESSION['user']['name'])."'");
$_SESSION = array();
unset($_SESSION['user']['name']);
unset($_SESSION['user']['gravatar']);
return array('status' => 1);
}
public static function submitChat($chatText){
if(!$_SESSION['user']){
throw new Exception('You are not logged in');
}
if(!$chatText){
throw new Exception('You haven\' entered a chat message.');
}
$chat = new ChatLine(array(
'author' => $_SESSION['user']['name'],
'gravatar' => $_SESSION['user']['gravatar'],
'text' => $chatText
));
// The save method returns a MySQLi object
$insertID = $chat->save()->insert_id;
return array(
'status' => 1,
'insertID' => $insertID
);
}
public static function getUsers(){
if($_SESSION['user']['name']){
$user = new ChatUser(array('name' => $_SESSION['user']['name']));
$user->update();
}
// Deleting chats older than 5 minutes and users inactive for 30 seconds
DB::query("DELETE FROM webchat_lines WHERE ts < SUBTIME(NOW(),'0:30:0')");
DB::query("DELETE FROM webchat_users WHERE last_activity < SUBTIME(NOW(),'0:3:60')");
$result = DB::query('SELECT * FROM webchat_users ORDER BY name ASC LIMIT 18');
$users = array();
while($user = $result->fetch_object()){
$user->gravatar = Chat::gravatarFromHash($user->gravatar,30);
$users[] = $user;
}
return array(
'users' => $users,
'total' => DB::query('SELECT COUNT(*) as cnt FROM webchat_users')->fetch_object()->cnt
);
}
public function getChats($lastID) {
$lastID = (int)$lastID;
$didx= $_SESSION['dido'];
//$result = DB::query('SELECT * FROM webchat_lines WHERE id > '.$lastID.' and deal_did="'.$new.'" ORDER BY id ASC');
$result = DB::query('SELECT * FROM webchat_lines WHERE deal_did="'.$didx.'" ORDER BY id ASC');
$chats = array();
while($chat = $result->fetch_object()){
// Returning the GMT (UTC) time of the chat creation:
$chat->time = array(
'hours' => gmdate('H',strtotime($chat->ts)),
'minutes' => gmdate('i',strtotime($chat->ts))
);
$chat->gravatar = Chat::gravatarFromHash($chat->gravatar);
$chats[] = $chat;
}
return array('chats' => $chats);
}
public static function gravatarFromHash($hash, $size=23){
return 'http://www.gravatar.com/avatar/'.$hash.'?size='.$size.'&default='.
urlencode('http://www.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?size='.$size);
}
}
?>
In Javascript you can use window.location.pathname to figure out the name of the page.
Example: If you were on the homepage, window.location.pathname would return "/"
So if you want something on the homepage only, wrap the code in this:
if(window.location.pathname == '/') {
//DOE GOES HERE`enter code here`
}

Vuejs Ajax call aways fires error function

Hey Everyone so I am trying to make a vueapp that makes an ajax call to a php page. On that php page I am running a few mysql statements the most important of which is a insert statement. if that page ajax call is successful and the insert statement runs successfully I want to redirect a page. If the ajax call or the insert statement fails or the user exists I want to redirect them the same page just render the page diffrently based on the result. I've tried doing it with sessions however when i try to use the ajax error function it fires everytime even when its successful. I know this as I get an alert error. But than when it goes to the result.php page I get success. I dont understand. Any help would be great! Heres the code for the vueapp (signup.php)
<?php ob_start();
session_start();
include('head.php');
include('header.php');
?>
<div id="signUpFormContainer">
<div id="signUpForm">
<div class="inputDiv">
<p>Username*</p>
<input v-model="userName" placeholder="joseChang">
</div>
<div class="inputDiv">
<p>Password*</p>
<input type="password" v-model="password" placeholder="********">
</div>
<div class="inputDiv">
<p>Confirm Password*</p>
<input type="password" v-model="confirmPassword" placeholder="********">
</div>
<div class="inputDiv">
<p>First Name*</p>
<input v-model="firstName" placeholder="Jose">
</div>
<div class="inputDiv">
<p>Last Name*</p>
<input v-model="lastName" placeholder="Chang">
</div>
<div class="inputDiv">
<p>Email*</p>
<input v-model="email" placeholder="jchang#example.com">
</div>
<div class="inputButton">
<input v-on:click.prevent="makeAccount" id="addButton" type="button" value="Sign Up"></input>
</div>
</div>
</div>
<div id="footerContainer"></div>
<script>
var app = new Vue({
el: '#signUpForm',
data: {
userName: '',
password: '',
confirmPassword: '',
firstName: '',
lastName: '',
email: ''
},
computed: {
passwordsMatch: function() {
if(this.password == this.confirmPassword) {
return true;
} else {
return false;
}
},
passwordRequirementsMet: function() {
if(this.password.length >= 8) {
return true;
} else {
return false;
}
},
validEmail: function() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (!reg.test(this.email)) {
return false;
}
return true;
}
},
created: function() {
},
watch: {
},
methods: {
makeAccount: function() {
if(this.userName.length >= 8 && this.firstName != '' && this.lastName != '' && this.validEmail && this.passwordRequirementsMet && this.passwordsMatch) {
var jsonString = JSON.stringify({
userName: this.userName,
firstName: this.firstName,
lastName: this.lastName,
password: this.password,
email: this.email
});
$.ajax({
url: 'makeAccount.php',
dataType: 'json',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: jsonString,
error: function(){
alert('Error');
window.location.href='result.php';
},
success: function(data){
console.log(data);
alert('success');
window.location.href='result.php';
}.bind(this)
});
}
}
}
});
</script>
<?php include('foot.php');?>
?>
Heres the code for php page im making an ajax request to. (makeAccount.php)
<?php session_start();
$_SESSION['hitpage']=1;
require_once('database.php');
require_once('functions.php');
$requestBody = file_get_contents('php://input');
$requestJSON = json_decode($requestBody);
require_once 'lib/Braintree.php';
$gateway = new Braintree_Gateway([
'environment' => 'sandbox',
'merchantId' => '*****',
'publicKey' => '*****',
'privateKey' => '*****'
]);
$braintreeResponse = $gateway->customer()->create([
'firstName' => $requestJSON->firstName,
'lastName' => $requestJSON->lastName,
'email' => $requestJSON->email
]);
if ($braintreeResponse->success) {
echo(json_encode($braintreeResponse));
} else {
echo(json_encode($braintreeResponse));
}
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$googleResponse = get_data('https://script.google.com/macros/s/AKfycbzz8Oh3Jqt5tP4wGcNyM8jVhwaMEr6S5AJ-MWqFlhPN1rSzBdSr/exec?name='.urlencode(stripslashes($requestJSON->userName)));
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$googleResponseParsed = get_string_between($googleResponse, '<title>', '</title>');
echo($googleResponseParsed);
$username = $requestJSON->userName;
$username = mysqli_real_escape_string($mysqli, $username);
$firstname = $requestJSON->firstName;
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$lastname = $requestJSON->lastName;
$lastname = mysqli_real_escape_string($mysqli, $lastname);
$email = $requestJSON->email;
$email = mysqli_real_escape_string($mysqli, $email);
$cleanGoogleResponseParsed = $googleResponseParsed;
$cleanGoogleResponseParsed = mysqli_real_escape_string($mysqli, $cleanGoogleResponseParsed);
$customerid = $braintreeResponse->customer->id;
$customerid = mysqli_real_escape_string($mysqli, $customerid);
$password = $requestJSON->password;
$encryptedpassword=password_encrypt($password);
$selectcount="SELECT COUNT(*) as exist FROM user WHERE userName='$username'";
$countresult=mysqli_query($mysqli, $selectcount);
while($row=mysqli_fetch_assoc($countresult)){
$exists=$row['exist'];
}
if($exists==0){
$makeUserSQL = "INSERT INTO user (userName, firstName, lastName, email, driveFolderId, braintreeId, password)
VALUES ('".$username."','".$firstname."','".$lastname."','".$email."','".$cleanGoogleResponseParsed."','".$customerid."','".$encryptedpassword."')";
if ($mysqli->query($makeUserSQL) === TRUE) {
echo "New record created successfully";
$_SESSION['inserted']=1;
} else {
echo "Error: " . $makeUserSQL . "<br>" . $mysqli->error;
}
} else {$_SESSION['userexists']=1;}
$mysqli->close();
?>
Heres the code for result.php
<?php session_start();
if(isset($_SESSION['hitpage'])){$ajaxworked=1;} else{$ajaxworked=0;}
if(isset($_SESSION['inserted'])){$inserted=1;} else {$inserted=0;}
if(isset($_SESSION['userexists'])){$userexists=1;} else{$userexists=0;}
if($inserted==1 and $ajaxworked==1){echo 'Congrats you seccessfully created your account click here to go home';}
if($ajaxworked==0){echo 'Possible time out if error prosists please contact creative group click here to try again';}
if($inserted==0 and $ajaxworked==1 and $userexists==0){echo 'There was an error creating your account if error prosists please contact the creative group click here to try again';}
if($userexists==1){echo 'Sorry that user already exists click here to try again';}
session_destroy();
?>
After many tears and banging my head against the screen. Prayers to about every God under the sun and plenty of cussing I have finally found the problem. My JSON string was invalid

Ajax Call and Returned Response

I'm trying to add an address to a list in dotmailer (which for those not familiar is a service like mailchimp) I can get the address added but am struggling to get any sort of returned status via Ajax.
I've got the following in my form page in php
var emailEntered;
$(document).ready(function() {
$.fn.search = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
$("#email").search();
$("#sendButton").click(function() {
$(".error").hide();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#message").html('<span class="error">Enter your email address before submitting.</span>');
return false;
}
else if(!emailReg.test(emailaddressVal)) {
$("#message").html("<span class='error'>Please check your email address.</span>");
return false;
}
else {
emailEntered = escape($('#email').val());
}
});
$('#signup').submit(function() {
$("#message").html("<span class='error'>Adding your email address...</span>");
$.ajax({
url: 'dotmailerInput.php',
data: 'ajax=true&email=' + emailEntered,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
<form id="signup" action="dotmailer.php" method="get">
<input type="email" name="email" id="email" class="textinput" value="Enter" />
<input type="submit" id="sendButton" name="submit" class="textinput" value="" />
</form>
<div id="message"> </div>
In the dotmailer.php page that it is referencing I've got the following. I can see it gives me a response "adding your email address" but nothing else after this and the email as I said gets added correctly.
$email = $_GET['email'];
$username = ""; //apiusername
$password = ""; //api password
$addressbookid = ;
$AudienceType = "Unknown";
$OptInType = "Unknown";
$EmailType = "Html";
try {
$client = new SoapClient("http://apiconnector.com/api.asmx?WSDL");
$contact = array("Email" => $email,"AudienceType" => $AudienceType, "OptInType" => $OptInType, "EmailType" => $EmailType, "ID" => -1);
$dotParams = array("username" => $username, "password" => $password, "contact" => $contact, "addressbookId" => $addressbookid);
$result = $client->AddContactToAddressBook($dotParams);
return "Success";
}
catch (Exception $e) {
return "Error";
}
Any helps or tips on what to look at or where to go next would be greatly appreciated.
Chris
Try echo instead of return because you are at the top level in PHP and will do output using this (instead of return gibing a function a value).
echo "Success";
}
catch (Exception $e) {
echo "Error";

Categories