how retrieve data from database using ajax in laravel 4?
sorry I am new to ajax and this is just the code I started
html
<select id="bookstatus">
<option value="" disabled selected>Sort by Book Status</option>
<option value="1">For Rent</option>
<option value="2">For Barter</option>
</select>
js & ajax:
$('#bookstatus').on('change', function() {
var bs = document.getElementById("bookstatus");
var getbookstatus = bs.options[bs.selectedIndex].value;
$.ajax({
method: 'post',
url: 'discover',
data: {getbookstatus:getbookstatus},
success: function() {
}
});
});
routes:
Route::post('discover', 'BookController#getbook');
Route::get('discover', 'BookController#getbook');
my controller:
public function getbook(){
$bookstatus = Input::get('getbookstatus');
$getbook = DB::select("SELECT title FROM books WHERE forRent='$bookstatus' ");
im expecting that it will display books based on selected value
in view
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select id="bookstatus">
<option value="" disabled selected>Sort by Book Status</option>
<option value="1">For Rent</option>
<option value="2">For Barter</option>
</select>
<br><br>
<span ><strong>Show the books </strong></span>
<div id="result">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log('ready work');
$(document).on('change','#bookstatus',function(){
var getbookstatus=$(this).val();
console.log(getbookstatus);
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findbookstatus')!!}',
data:{'statusid':getbookstatus},
success:function(data){
console.log(data);
console.log(data.length);
op+='<ul>';
for(var i=0;i<data.length;i++){
op+='<li>'+data[i].title+'</li>';
}
op+='<ul>';
$('#result').html(op);
},
error:function(){
console.log('error');
}
});
});
});
</script>
</body>
</html>
in Route
Route::get('/discover','BookController#getbook');
Route::get('/findbookstatus','BookController#findbookstatus');
in Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class BookController extends Controller
{
public function getbook(){
return view('bookview');
}
public function findbookstatus(Request $request){
$getbook=DB::table('books')->select('title')->
where('forRent',$request->statusid)->take(100)->get();
return response()->json($getbook);
}
}
Database Connection
in case laravel 4.2 go to config/database.php
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
in case laravel 5.3 go to .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=root
DB_PASSWORD=
table structure 'books'
enter image description here
For details you may watch this video
https://www.youtube.com/watch?v=N5ctY9nPt9o&feature=youtu.be
Related
I use the samples (https://github.com/stripe-samples/checkout-single-subscription/tree/master/server/php) from Stripe to create a subscription. What I don't really understand, how can I pass metadata from my index.html over script.js to the create-checkout-session.php.
I thought I just add data attributes to the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Stripe</title>
<meta name="description" content="A demo of Stripe Payment Intents" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<script src="https://js.stripe.com/v3/"></script>
<script src="./script.js" defer></script>
</head>
<body>
<div class="sr-root">
<div class="sr-main" style="display: flex;">
<div class="sr-container">
<section class="container">
<button id="basic-plan-btn" data-partner="name" data-package="basic">USD 6.90</button>
</section>
<section class="container">
<button id="pro-plan-btn" data-partner="name" data-package="premium">USD 11.90</button>
</section>
</div>
</div>
</div>
</body>
</html>
then I have to read them somehow out in the script.js. But that I don't really figure out how.
// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function(priceId) {
return fetch("/fileadmin/restaurant/stripe/create-checkout-session.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
priceId: priceId,
partner: 'name',
package: 'premium'
})
}).then(function(result) {
return result.json();
});
};
// Handle any errors returned from Checkout
var handleResult = function(result) {
if (result.error) {
var displayError = document.getElementById("error-message");
displayError.textContent = result.error.message;
}
};
/* Get your Stripe publishable key to initialize Stripe.js */
fetch("/fileadmin/restaurant/stripe/config.php")
.then(function(result) {
return result.json();
})
.then(function(json) {
var publishableKey = json.publishableKey;
var basicPriceId = json.basicPrice;
var proPriceId = json.proPrice;
var stripe = Stripe(publishableKey);
// Setup event handler to create a Checkout Session when button is clicked
document
.getElementById("basic-plan-btn")
.addEventListener("click", function(evt) {
createCheckoutSession(basicPriceId).then(function(data) {
// Call Stripe.js method to redirect to the new Checkout page
stripe
.redirectToCheckout({
sessionId: data.sessionId
})
.then(handleResult);
});
});
// Setup event handler to create a Checkout Session when button is clicked
document
.getElementById("pro-plan-btn")
.addEventListener("click", function(evt) {
createCheckoutSession(proPriceId).then(function(data) {
// Call Stripe.js method to redirect to the new Checkout page
stripe
.redirectToCheckout({
sessionId: data.sessionId
})
.then(handleResult);
});
});
});
by that I receive them in the create-checkout-session.php
<?php
require_once 'shared.php';
$domain_url = $config['domain'];
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain_url . 'success.php?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain_url . 'canceled.php',
'payment_method_types' => ['card'],
'mode' => 'subscription',
'allow_promotion_codes' => true,
'line_items' => [[
'price' => $body->priceId,
'quantity' => 1,
]],
'subscription_data' => ['trial_period_days' => 60],
'metadata' => [
'partner' => $body->partner,
'package' => $body->package
],
]);
echo json_encode(['sessionId' => $checkout_session['id']]);
Thank You.
What you've done adding to the JSON body of the fetch call looks right to me. If you're trying to set the 'name' and 'premium' values dynamically from some input, then take a look at this previous answer for some approaches for getting input values.
I'm new to node. I need to make a dependent dropdown menu which gets the address data of the selected user from another dropdown menu in the same page..The proplem is that the hole page is updated not only the second dropdown menu.. I think it's the same problem as dynamically dropdown in nodejs mysql, but it didn't help me much.
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
<% address.forEach((address) => { %>
<option value="<%= address.addressId %>" > <%=address.addressName %> </option>
</select>
<% }) %>
my ajax request:
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
var add = $('#address').val();
$.ajax({
type:'GET',
data: {selectedId : item },
url:'/order/new',
success: function(result1){
$('#body').html(result1);
}
});
});
});
order.js
module.exports = {
addOrderPage: (req, res) => {
let query1 = "SELECT * FROM users";
getConnection().query(query1, (err, result1) => {
let query2 = "SELECT * FROM address WHERE userId = '" +req.query.selectedId + "'";
getConnection().query(query2, (err, rows, fields) => {
if (err) {
return res.status(500).send(err);
}
console,log(rows)
res.render('newOrder.ejs', {
address : rows,
users: result1
});
});
});
}
}
app.js
app.get('/order/new', addOrderPage)
Your success function has missing the data that is return from request update your success function
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
$.ajax({
type:'GET',
data: { selectedId: item },
url:'/users/address',
success: function(data){
console.log(data);
$('#address').empty();
$('address').append("<option disabled selected> Select Address..</option>");
$.each(data, function (index, addressObj) {
$('#address').append("<option value = '" + addressObj.id + "' > " + addressObj.first_name + ". </option > ");
});
}
});
});
And in your order.js you need create one call for users and one call is for usersaddress data:-
module.exports = {
addOrderPage: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM users";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.render('newOrder.ejs', {
players: result1,
});
});
},
getUserAddress: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM address WHERE userId = '" + selectedId + "'";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.send(result1);
});
}
}
neworder.js
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
</select>
And in your app.js or index.js you need to add its route
app.use("/users/address", order.getUserAddress);
Heres my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../resources/js/jquery-3.2.0.min.js"></script>
<script src="../resources/select2-4.0.3/dist/js/select2.min.js"></script>
<link href="../resources/select2-4.0.3/dist/css/select2.min.css" type="text/css" rel="stylesheet">
<script src="../resources/d3/d3.min.js"></script>
<script src="../resources/d3/d3.button.js"></script>
<script src="js/script.js"></script>
<link href="css/style.css" type="text/css" rel="stylesheet">
<title>Database Heat Map</title>
</head>
<body>
<div id="head">
<h1>Database Heat Map</h1>
<div>
<div>
<h3>Schema</h3>
<select class="js-example-basic-single" name="schema" id="schema">
<option></option>
</select>
</div>
<div>
<h3>Table</h3>
<select class="js-example-basic-single" name="table" id="table">
</select>
</div>
</div>
</div>
</body>
</html>
The way that my select boxes are set up is that the second select box populates depending on what is selected in the first. Each Schema in the first drop down has their own sets of unique tables.
Here's my JavaScript/Jquery:
$(document).ready(function () {//Load in json file using d3
getSchema();
$("#schema").change(function() {
var e = document.getElementById("schema");
var selectedSchema = e.options[e.selectedIndex].value;
console.log(selectedSchema)
if (selectedSchema != "") {
getTable(schema);
}
})
function getSchema() {
$.ajax({
url: "heatmap.py",
dataType: "json",
data: {get: "schema"},
success: function(results) {
console.log(results);
populateSchemaDropDown(results);
},
error: function() {
console.log("schema error");
}
})
}
function getTable(schema) {
$.ajax({
url: "heatmap.py",
dataType: "json",
data: {findTables: schema},
success: function(results) {
console.log(results);
},
error: function() {
console.log("table error")
}
})
}
function populateSchemaDropDown(schema) {
$('#schema').select2({
placeholder: "--Select One--",
allowClear: true,
data: schema,
dropdownAutoWidth: true
})
}
function populateTableDropDown(table) {
$("#table").select2({
placeholder: "--Select One--",
allowClear: true,
disabled: true
})
}
The first dropdown box populates just fine, but whenever I click an option, it logs the name of the option like it's supposed to but I keep getting an Uncaught RangeError: Maximum call stack size exceeded error from jquery
Here is the python file as well (ignore indent syntax, it's not pasting correctly):
def getSchema():
historicalRefreshStats = json.load(open(os.path.join(scriptDir, "historicalRefreshStats.json")))
schemas = []
for server in historicalRefreshStats:
currentServer = unicodedata.normalize('NFKD', server).encode('ascii', 'ignore')
for schema in historicalRefreshStats[currentServer]:
currentSchema = unicodedata.normalize('NFKD', schema).encode('ascii', 'ignore')
schemas.append(currentSchema)
return sorted(list(set(schemas)))
def getTables(schemaToFind):
historicalRefreshStats = json.load(open(os.path.join(scriptDir, "historicalRefreshStats.json")))
tables = []
for server in historicalRefreshStats:
currentServer = unicodedata.normalize('NFKD', server).encode('ascii', 'ignore')
for schema in historicalRefreshStats[currentServer]:
currentSchema = unicodedata.normalize('NFKD', schema).encode('ascii', 'ignore')
if schemaToFind == currentSchema:
for table in historicalRefreshStats[currentServer][currentSchema]:
tables.append(table)
return sorted(list(set(tables)))
form = cgi.FieldStorage()
if "get" in form:
schemas = getSchema()
print "Content-Type: text/json; charset=ISO-8859-1\n"
print json.dumps(schemas)
elif "findTables" in form:
schema = form["findTables"]
tables = getTables(schema)
print "Content-Type: text/json; charset=ISO-8859-1\n"
print json.dumps(tables)
else:
print "Content-Type: text/json; charset=ISO-8859-1\n"
print json.dumps("error")
Any help is appreciated! I don't think it's doing anything recursively and I checked to make sure it wasn't the python response that was triggering the error. But it must be recursive if I'm getting the error, right?
Your calling getTable(schema) but schema is not defined, it should be selectedSchema, you also don't need that much code things could be a lot shorter, "less code = less problems"
like the change function for example: https://fiddle.jshell.net/____mmc/znqxaa2h/
$("#schema").change(function() {
let selectedItem = $('#schema').select2('data')[0]
....
})
and the ajax call, you could embed the call in select2 https://select2.org/data-sources/ajax
I have a multiselect that I want to use as a search box so that the user can search by category, event type, location and keywords. It has the following structure:
<select name="search-term[]" multiple="multiple">
<optgroup label="Categories">
<option value="category_4">Internal</option>
<option value="category_2">Business</option>
<option value="category_5">External</option>
<option value="category_1">Science</option>
<option value="category_6">Sports and Social</option>
</optgroup>
<optgroup label="Event Types">
<option value="eventtype_2">Meeting</option>
<option value="eventtype_3">Social Activity</option>
<option value="eventtype_4">Sporting Activity</option>
<option value="eventtype_1">Symposium</option>
</optgroup>
<optgroup label="Locations">
<option value="location_2">Office 1</option>
<option value="location_3">Office 2</option>
<option value="location_1">Office 3</option>
</optgroup>
</select>
I have initialised select2 with the tags option set to true so like so:
$('select').select2({
tags : true,
createTag: function (params)
{
return {
id: 'keyword_' + params.term,
text: params.term,
newOption: true
}
}
});
This allows users to enter a new option if it doesn't exist and takes care of the keywords requirement. Any new tags are appended with keyword_ so that the server knows how to handle them when the form is submitted.
This is all working as I expected however the issue I've come across is if someone wants to search for a keyword that is called the same as one of the other options then they aren't able to create a new keyword tag it will only let them select the existing option. For example if I search Office 1 I may want to search for events that are located at office 1 or I may want to do a keyword search so that I am searching for events that have office 1 in the title. The problem is currently I'm only able to select the location option I'm not able to create a new tag. Does anyone know how I could achieve this?
I achieved this in the end by using an AJAX datasource which gives you much more control over what options are shown to the user. Here is my code:
$('select').select2({
ajax: {
url: "/server.php",
dataType: 'json',
type: "GET",
delay: 0,
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id,
children: item.children
}
})
};
},
cache: false
},
templateSelection: function(item)
{
return item.parent+': '+item.text;
}
});
Contents of server.php:
<?php
$term = !isset($_GET['term']) ? null : ucfirst($_GET['term']);
$categories = array('Meeting', 'Seminar', 'Sports and Social');
$locations = array('Cambridge', 'London', 'Northwich');
$matching_categories = array();
$matching_locations = array();
foreach($categories as $i => $cat) {
if(is_null($term) || stripos($cat, $term)!==false) {
$matching_categories[] = array(
'id' => 'category_'.$i,
'text' => $cat,
'parent' => 'Category'
);
}
}
foreach($locations as $i => $loc) {
if(is_null($term) || stripos($loc, $term)!==false) {
$matching_locations[] = array(
'id' => 'location_'.$i,
'text' => $loc,
'parent' => 'Location'
);
}
}
$options = array();
if(!empty($matching_categories)) {
$options[] = array(
'text' => 'Category',
'children' => $matching_categories
);
}
if(!empty($matching_locations)) {
$options[] = array(
'text' => 'Location',
'children' => $matching_locations
);
}
if(!is_null($term)) {
$options[] = array(
'text' => 'Keyword',
'children' => array(
array(
'id' => 'keyword_'.$term,
'text' => $term,
'parent' => 'Keyword'
)
)
);
}
echo json_encode($options);
I have the following code with an if statement depending if a user has saved an article or not. I'm simply trying to delete the article from the database using jquery. I unsure where im going wrong? help is much appreciated!
View:
<form action="{{URL::route('article-delete')}}" method="post" id="article_one_delete">
<div class="form-group">
<input type="hidden" name="first_desc" value="{{$firstrow->description}}" class="form-control">
</div>
<div class="form-group">
<input type="hidden" name="first_title" value="{{$firstrow->title1}}" class="form-control">
</div>
<button type ="button" id="Recodelete" class="btn btn-success btn-xs">UnSave</button>
{{Form::token()}}
</form>
Route:
Route::delete('/home/', array( 'as' => 'article-delete',
'uses' => 'HomeController#deletearticle'));
Controller:
public function deletearticle(){
$firsttitle = Input::get('first_title');
$articledelete = UserSaveArticle::where('user_id', Auth::id()
->where ('user_save_articles.chosen_title', $firsttitle))->delete();
return true;
JQuery:
$(document).ready(function(){
$('#Recodelete').on('click', function(){
var article_one_delete = $('#article_one_delete').serializeArray();
var url_d = $('#article_one_delete').attr('action');
$.get(url_d, article_one_delete, function(data){
console.log(data);
});
});
});
You should define right route for DELETE article, like this:
Route::delete('/article/{id}', ['as' => 'article-delete', 'uses' => 'HomeController#deleteArticle']);
In the HomeController $id variable (article ID) will be available as a method parameter:
function deleteArticle($id)
{
…
}
In PHP side you defined DELETE route, it means you should make DELETE request on JS side using the ajax method:
$.ajax({
url: '/article/' + articleId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});