Autocompleting a form in PHP/Javascript - javascript

I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)

https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.

Related

php - Display Events with Form Submit (FullCalendar)

Good day!
I am working on a small personal project with FullCalendar. So in the code below, I have written a function that displays the events when the user searches for that event when a keyword is entered. (e.g. "meeting")
function load($pdo)
{
try {
if (isset($_POST['search'])) {
//run sql connection and query
$term = $_POST['term'];
$data = array();
$sql = "SELECT * FROM events WHERE keyword LIKE '%$term%'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
//output events data from db in array using foreach loop
foreach ($result as $row) {
$description = $row['description'];
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $description);
if (($row['allDay'] == '1') == 1) {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
} else {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
}
}
//echo and convert array to JSON representation
echo json_encode($data);
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//execute load function
load($pdo);
The results are echoed in a json_encoded function and are loaded from jQuery.
$(document).ready(function () {
var calendar = $("#calendar").fullCalendar({
displayEventTime: false,
editable: false,
header: {
left: "prev,next today",
center: "title",
right: "listMonth, month,agendaWeek,agendaDay",
},
eventRender: function (event, element, view) {
$(element).tooltip({
title: event.description,
});
},
events: "load.php",
});
});
After submitting the form/hitting the submit button, the events are not returned or displayed. Is there something I'm missing in my code, or am I missing a procedure?
I hope I described my issue to your best of understanding and I hope to learn from this and better improve my code in the future.

How to add an AJAX action - Elgg

I'm trying to create an AJAX action in elgg. I have followed this Elgg tutorial: Ajax: Performing actions, but I'm getting nothing so far, apart from the fail error:
Sorry, Ajax only!
The other error is that the page reloads, instead of persisting the data asynchronously.
What am I getting wrong? Thank you all in advance.
Below is my code:
form: views/default/forms/service_comments/add.php
<?php
$url_confirm = elgg_add_action_tokens_to_url("action/service_comments/add?guid={$guid}");
$params_confirm = array(
'href' => $url_confirm,
'text' => elgg_view_icon('upload'),
'is_action' => true,
'is_trusted' => true,
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
?>
<div class="update-options">
<?= $confirm ?>
</div>
start.php
elgg_register_action("service_comments/add", __DIR__ . "/actions/service_comments/add.php");
action file: actions/service_comments/add.php
<?php
elgg_ajax_gatekeeper();
$arg1 = (int)get_input('arg1');
$arg2 = (int)get_input('arg2');
// will be rendered client-side
system_message('We did it!');
echo json_encode([
'sum' => $arg1 + $arg2,
'product' => $arg1 * $arg2,
]);
Javascript : views/js/service_comments/add.js
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
You have written ajax procedure but not invoking it. Instead you are directly calling it . by making it link.
$params_confirm = array(
'href' => '#',
'text' => elgg_view_icon('upload'),
'onclick' => "myajax_function()",
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
Then move your JS code inside a function.
function myajax_function(){
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
}

MySQL data into FullCalendar

EDIT 2
I have the array at the correct format but nothing added to calendar:
EDIT
I want to get data from mysql and display it on fullcalendar. I have this PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('global.php');
//Json and PHP header
header('Content-Type: application/json');
$eventss = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
$search_date = "SELECT * FROM appointment INNER JOIN patient ON appointment.patient_id = patient.id WHERE appointment.id_logged = :id_logged";
$search_date_stmt = $conn->prepare($search_date);
$search_date_stmt->bindValue(':id_logged', $id_logged);
$search_date_stmt->execute();
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
foreach($search_date_stmt_fetch as $row)
{
$events[] = array( 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($event);
?>
The array that should be returned to fullcalendar so it can display it should be like:
'id'=>'value', 'title'=>'my title', 'start'=>...etc
But what the array I am seeing in the XHR is like:
Here is fullcalendar script (no errors at the console):
<script>
(function ($) {
$(document).ready(function() {
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: 'fullcalendar/get-events.php',
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
});
})(jQuery);
</script>
I think you have problem with array you are using and you dont have ID for event, it supposee patient id to b I made some changes on your code please try it .
foreach($search_date_stmt_fetch as $row)
{
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',strtotime($row['date_app'])), 'end' => date('Y-m-d',strtotime($row['date_app'])), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
You are mixing $event, $events and $eventss (unused).
It should read :
foreach($search_date_stmt_fetch as $row) {
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
it depends on version of full calendar , there are two version v2 , v1
the required properties for the event object is title,start
if you are working with version v2, u need to convert the date to Moment, the version v2 is completely working on moment objects.
after getting the data from server, we can convert it like this
in js file:
$.map(data, function (me) {
me.title = me.title, // this is required
me.start = moment(me.start).format(); // this is required
me.end = moment(me.end).format();
}
$('#calendar').fullCalendar('addEventSource', data);

Jquery UI Autocomplete in codeigniter using table oracle

views.php
<div class="input-group">
<input class="form-control" id="nomor_cari" maxlength="16" placeholder="No. CM / No. KTP">
script autocomplete
$('#nomor_cari').autocomplete({
source: get_no,
dataType: 'JSON'
});
function get_no
<?php
function get_no($q)
{
$this->db->select('NO_MEDREC');
$this->db->like('NO_MEDREC', $q);
$query = $this->db->get('PASIEN_IRJ');
if($query->num_rows > 0)
{
foreach ($query->result_array() as $row)
{
$row_set[] = htmlentities(ucfirst($row['NO_MEDREC']));
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($row_set));
}
echo $query->row();
}?>
but autocomplete didn't show anything.
if i use local variable , autocomplete works like it should be.
<script> var availableNumber = [
"0000000002",
"0000000020",
"0000000200",
"0000002000"
];
/<script>
and changes autocomplete to
$('#nomor_cari').autocomplete({
source: availableNumber,
dataType: 'JSON'
});
what did i missed? (im sure .js are loaded because when using local var , it works like charm)
just in case needed , here's my autoload
$autoload['libraries'] = array('database', 'email', 'session');
$autoload['helper'] = array('url', 'template', 'message', 'misc');
I think issue is in "source". Please try to use json like this
$('#nomor_cari').autocomplete({
source: function (request, response) {
$.getJSON("ful_url/get_no?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
});

Stripe AJAX PHP and JavaScript

The below is my code I'm using for my Stripe Subscription Payments, because the site I'm implementing this into is AngularJS I want to keep the site from Refreshing so I'm opting for this AJAX option.
I have commented out a piece of the PHP which is
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));
If I exclude this, the payment goes through once and I'm unsure how this application is able to process the charge if there is no call for it in the PHP file.
If I include the above snippet then the charge goes through twice.
My config.php only has require_once('Stripe.php'); along with my API keys.
So I'm hoping someone could explain why the charge goes through without the charge code piece in there if my code is actually okay for me to continue with.
HTML
<button id="proBtn">Subscribe</button>
JavaScript
Stripe.setPublishableKey('HIDDEN');
$('#proBtn').click(function(){
var token = function(res){
var $input = $('<input type="hidden" name="stripeToken" />').val(res.id);
var tokenId = $input.val();
var email = res.email;
setTimeout(function(){
$.ajax({
url:'/assets/lib/charge.php',
cache: false,
data:{ stripeEmail : email, stripeToken:tokenId, stripePlan: 'pro' },
type:'POST'
})
.done(function(data){
// If Payment Success
console.log(data);
$('#proBtn').html('Thank You').addClass('disabled');
})
.error(function(){
$('#proBtn').html('Error, Unable to Process Payment').addClass('disabled');
});
},500);
//$('form:first-child').append($input).submit();
};
StripeCheckout.open({
key: 'HIDDEN', // Your Key
address: false,
amount: 500,
currency: 'gbp',
name: 'Pro Account',
description: '',
panelLabel: 'Checkout',
allowRememberMe: false,
token: token
});
return false;
});
charge.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/assets/lib/config.php');
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$plan = $_POST['stripePlan'];
if ( $plan == 'pro' ) {
$amount = 500;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'pro';
}
if ( $plan == 'team' ) {
$amount = 2000;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'team';
}
Stripe_Plan::retrieve("pro");
Stripe_Plan::retrieve("team");
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => $plan
));
try {
/*
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));*/
echo 'success';
} catch(Stripe_CardError $e) {
echo "The card has been declined";
echo $token;
}
print_r($token);
echo '<br/>';
print_r($email);
echo '<br/>';
echo $customer->id;
echo '<h1>Successfully charged '.$amountFormat.'!</h1>';
?>
When you create a customer in Stripe it automatically charges them if you pass in a plan. You're basically saying create this customer and sign them up for this plan. That's why you are charging them twice.
Here's a link to the Customer API:
https://stripe.com/docs/api#create_customer

Categories

Resources