How to make an AJAX request in plsql - ajax

I am trying to call a stored procedure from another stored procedure that looks something similar to that of the below code:
create or replace procedure hello_world is
v_first_name VARCHAR2(30) := 'ABC';
v_LAST_name VARCHAR2(30) := 'XYZ';
BEGIN
htp.p('<HTML>');
htp.p('<HEAD>');
htp.p('<TITLE>Instructor Personal Info</TITLE>');
htp.p('</HEAD>');
htp.p('<BODY bgColor="#99CCCC">');
HTP.P('<input type="text" name = "TEXT" >');
HTP.P('<p id="demo"></p>');
htp.p('<script type="text/javascript">function myFunction() {/**Call the other stored procedure here passing the value from the the element "demo"**/');
htp.p('</script>');
HTP.P('<button type="button" onclick="myFunction()">Personal Info</button>');
HTP.p('<p>This example demonstrates how to assign an "onclick" event to a p element.</p>');
htp.p('<H1>Personal Info For '||v_first_name||' '||v_last_name||'</H1>');
htp.p('</BODY>');
htp.p('</HTML>');
END;
I Want to pass the value of the element "Demo" as a parameter.
Is this possible? and how can this be achieved?

Here is an example how to do a AJAX-Request.
I couldn't test it.
As you see you need to change the values on http.open witht the name of your procedure.
CREATE OR REPLACE PROCEDURE hello_world
IS
v_first_name VARCHAR2 (30) := 'ABC';
v_last_name VARCHAR2 (30) := 'XYZ';
BEGIN
HTP.p ('<HTML>');
HTP.p ('<HEAD>');
HTP.p ('<TITLE>Instructor Personal Info</TITLE>');
HTP.p ('</HEAD>');
HTP.p ('<BODY bgColor="#99CCCC">');
HTP.p ('<input type="text" name = "TEXT" >');
HTP.p ('<p id="demo"></p>');
HTP.p('<script type="text/javascript">function myFunction() {
var http;
var response;
var demo = document.getElementById("demo");
http = new XMLHttpRequest();
http.open("GET", "PROCEDURE_TO_CALL?param1="+ demo.value, false);
http.setRequestHeader("Cache-Control", "no-cache");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200){
response = http.responseText;
}
}
http.send();
}');
HTP.p ('</script>');
HTP.p('<button type="button" onclick="myFunction()">Personal Info</button>');
HTP.p('<p>This example demonstrates how to assign an "onclick" event to a p element.</p>');
HTP.p( '<H1>Personal Info For '
|| v_first_name
|| ' '
|| v_last_name
|| '</H1>');
HTP.p ('</BODY>');
HTP.p ('</HTML>');
END;

Related

Filtering the data on the basis of daterangepicker in laravel

I want to apply date range filter to my specific page .. There is just one date range picker which allows you to select a range from the calender and it shows in a single variable. i am getting the data in that variable but i dont know the exact way to filter my database data by splitting single variable value in two values ( from and to ) .
This is my input box --
<input type="text" class="form-control" name="daterange" value="01/01/2021 - 01/15/2021" />
Below is my specific script for daterange -
$(function() {
$('input[name="daterange"]').daterangepicker({
"startDate": "11/01/2021",
"endDate": "11/07/2021",
opens: 'left'
}, function(start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
axios.get('/fetchdata')
.then(response => {
data = this.form;
})
});
});
This is my web.php
Route::get('fetchdata', 'AccessoryController#fetch_data')->name('accessory.date.filter');
and this is my controller code where i need help , for now daterange picker is working. Its giving me correct selection in console. "New date range selected: 2021-11-04 to 2021-11-10 (predefined range: undefined)"
and my route is also working with return 'test' but i dont know how to get data at the back end.
public function fetch_data(Request $request)
{
//return 'test';
return $request->all(); // This returns nothing
$user = Auth::user();
$storesID = $user->storesID->pluck('id');
$stores = $user->stores;
return $request->daterange;
$accessory = AccessoryRequest::where('request_date', ">=", $request->startDate)->where('date', "<=", $request->endDate)->get(); //how can i filter
return $accessory;
return view('accessorydetails.index')
->with('stores', $stores)
->with('accessories', $accessories);
}
You do not put any parameters to the server:
axios.get('/fetchdata', {
params: {
startDate: start.format('YYYY-MM-DD'),
endDate: end.format('YYYY-MM-DD')
}
}).then(response => {
data = this.form;
});
Regarding AccessoryRequest, I guess you mean Accessory Eloquent object to work with the database
$accessory = AccessoryRequest::where('request_date', ">=", $request->startDate)->where('date', "<=", $request->endDate)->get(); //how can i filter
I am not sure how the name of the date field is, but idea is to do smth like
$accessory = AccessoryRequest::where('created_at', ">=", $request->get('startDate'))
->where('created_at', "<=", $request->get('endDate'))
->get();
In web.php --
Route::post('fetchdata', 'AccessoryController#fetch_data')->name('accessory.date.filter');
and in script file
$(function () {
$('input[name="daterange"]').daterangepicker({
"startDate": "11/01/2021",
"endDate": "11/07/2021"
}, function(start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
axios.post('/fetchdata/', {
startDate: start.format('YYYY-MM-DD'),
endDate: end.format('YYYY-MM-DD'),
}).then(response => {
$(location).attr('href', '/accessory')
//console.log(startDate);
});
});
});
Axios was not working with get method.

I am not sure if my Vue code is efficient

I am a beginner in Vue and I am wondering if I can get an insight from experienced developers here about my Vue codes. I just want to ask for help to know if my Vue approach is efficient and proper. (Project is running on Laravel)
The Case:
Let us say I have 2 tables in DB
(1) stores
(2) ad_accounts
Then we have 2 web pages to present these tables' data and execute CRUD functions with it
(1) store.blade.php
(2) adaccount.blade.php
Each page is running a Vue component
(1) Stores.vue
(2) AdAccounts.vue
I am using Vuex for store management.
Within store.js, I would have set of actions for CRUD for each vue component.
Now I realized that I have series of actions that actually does the same thing. For example, I have an action to add stores, and another action to add Ad accounts. Their only difference is that they are calling a different Laravel route.
So it seemed to me that my code was unnecessarily long and a bit expensive. To resolve, I decided to write my actions in a form of template. So this is what I did:
In store.js, I created an action for each CRUD function to be used as template
In Stores.vue and AdAccounts.vue, if I need to execute a CRUD function, I would use a method to call the corresponding action from store.js and provide the Laravel route as part of the action's payload
I have states and corresponding getters for returning these states in Stores.vue and AdAccounts.vue
Each action has a dedicated mutation that alters the approriate state
states and getters are mapped in each Vue component in order to access and use them
Is this approach efficient and proper? I have sample methods and actions below for reference.
Stores.vue
<template>
<div>
<form #submit.prevent="addData('stores/add')">
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</template>
<script>
export default {
methods: {
addData: function(url) {
this.payload.url = url
if(
this.payload.requestData.store_name == "" &&
this.payload.requestData.store_token == ""
) {
this.payload.isErr = true;
this.payload.errMsg = "ERROR: Could not continue due to some invalid or missing data. \nPlease check your entries and try again or contact your administrator.";
this.$store.dispatch('addData', this.payload)
}
else {
this.payload.isErr = false;
this.$store.dispatch('addData', this.payload)
this.readDataAll('stores/all', 'store');
}
this.cleanOnModalDismiss(this.$refs.addModal, this.refreshRequestData)
}
}
}
</script>
AdAccounts.vue
<template>
<div>
<form #submit.prevent="addData('ad_accounts/add')">
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</template>
<script>
export default {
methods: {
addData: function(url) {
this.payload.url = url
if(
this.payload.requestData.ad_id == "" &&
this.payload.requestData.ad_name == ""
) {
this.payload.isErr = true;
this.payload.errMsg = "ERROR: Could not continue due to some invalid or missing data. \nPlease check your entries and try again or contact your administrator.";
this.$store.dispatch('addData', this.payload)
}
else {
this.payload.isErr = false;
this.$store.dispatch('addData', this.payload)
this.readDataAll('ad_accounts/all', 'adaccounts');
}
this.cleanOnModalDismiss(this.$refs.addModal, this.refreshRequestData)
}
}
}
</script>
store.js
export default new Vuex.Store({
actions: {
addData (commit, payload) { // insert a record to DB
try {
if(payload.isErr == true) {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: payload.errMsg});
} else {
axios.post(payload.url, payload.requestData)
.then(response=>{
if(response.status == 200) {
var err_msg = "";
if(response.data.success !== null) {
response.data.messageType = "alert-info"
response.data.actionMessage = response.data.success
commit('ADD_DATA', response.data);
} else {
response.data.messageType = "alert-danger"
for(var i=0; i<response.data.error.length; i++) {
err_msg += response.data.error[i] + "\n"
}
response.data.actionMessage = err_msg
commit('ADD_DATA', response.data);
}
}
else {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: "ERROR: Connection status set to '" + response.headers.connection + "' due to error " + response.status + " " + response.statusText + ". \nPlease contact your administrator."});
}
})
}
} catch (error) {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: error})
}
}
}
}

ajax function database update not working

The following function is not working. Database is updated when sending data directly to php script using form action but when sent to php script through AJAX function the database is not updated but I receive success message.
the ajax
<script src="ajax.min.js" type="text/javascript"></script>
<script type="text/javascript">
function addRecord()
{
var first_first_name= $('#first_firstname').val();
var first_last_name = $('#first_lastname').val();
var team_name = $('#team_name').val();
if(team_name == ' '){
$('#propspectDiv').html('Enter A Valid Name');
$('#TeamName').addClass('error');
return;
}else{
$('#TeamName').removeClass('error');
$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Entering Team Name.<img src="images/processing.gif" />');
$.ajax({url : 'rpmh_open_update_prospects.php',
data:{
"team_name" : team_name,
"first_firstname" : first_first_name,
"first_lastname" : first_last_name,
},
success : function(data){
window.setTimeout(function()
{
$('#propspectDiv').html('Team Name Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
}
}
</script>
The php
$stmt = $mysqli->prepare("UPDATE mytable SET Team=? WHERE FirstName = ? AND LastName = ?");
$stmt->bind_param('sss', $team, $first, $last);
$team = $_POST['team_name'];
$first = $_POST['first_firstname'];
$last = $_POST['first_lastname'];
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$stmt->close();
Isn't GET the default type of your .ajax method ?
Since you use POST you should precise it if it's the case.
In JQuery you would add type: 'POST'

CanJS - Control Communication

I am learning CanJS now , so I want to try a very basic small demo. The demo is you will have different types of mobile recharge plans which displayed on the top (Radio buttons) and by choosing each plan the corresponding price options will be displayed in a table at the bottom.
For this demo I create two Model , 2 Control and 2 Template files , my question is how can two control communicate with each other? What is the standard way?
For now I am directly calling the control method through its instance , but I am not sure if it is right way to do. Also please explain Can.Route.
Output
http://jsfiddle.net/sabhab1/2mxfT/10/
Data
var CATEGORIES = [{id: 1 , name: "2G Internet Recharge"},
{id: 2 , name: "3G Internet Recharge"},
{id: 3 , name: "full talktime Recharge"},
{id: 4 , name: "Validity and talktime Recharge"},
{id: 5 , name: "National and international roaming"}];
var RECHARGEAMOUNTS =[{
id: 1 ,
values : [{amount: "Rs. 100" , benefit:"300 MB" ,validity:"30"},
{amount: "Rs. 200" , benefit:"1 GB" ,validity:"30"}]
},
{
id: 2 ,
values : [{amount: "Rs. 10" , benefit:"300 MB" ,validity:"30"},
{amount: "Rs. 99" , benefit:"100 GB" ,validity:"90"}]
},
{
id: 3 ,
values : [{amount: "Rs. 80" , benefit:"1 GB" ,validity:"50"},
{amount: "Rs. 99" , benefit:"100 GB" ,validity:"50"}]
},
{
id: 4 ,
values : [{amount: "Rs. 55" , benefit:"30 MB" ,validity:"10"},
{amount: "Rs. 200" , benefit:"1 GB" ,validity:"30"},
{amount: "Rs. 99" , benefit:"100 GB" ,validity:"90"}]
},
{
id: 5 ,
values : [{amount: "Rs. 880" , benefit:"100 MB" ,validity:"90"},
{amount: "Rs. 550" , benefit:"2 GB" ,validity:"30"},
{amount: "Rs. 1000" , benefit:"4 GB" ,validity:"90"},
{amount: "Rs. 1550" , benefit:"10 GB" ,validity:"90"}]
}
];
Model
//Model Category
CategoryModel = can.Model({
findAll : function(){
return $.Deferred().resolve(CATEGORIES);
}
},{});
//Model Category
ReachargeAmountModel = can.Model({
findAll : function(){
return $.Deferred().resolve(RECHARGEAMOUNTS);
},
findOne : function(params){
return $.Deferred().resolve(RECHARGEAMOUNTS[(+params.id)-1]);
}
},{});
Control
**// Can Control
var CategoryControl = can.Control({
// called when a new Todos() is created
init: function (element, options) {
// get all todos and render them with
// a template in the element's html
var el = this.element;
CategoryModel.findAll({}, function (values) {
el.html(can.view('categoriesEJS', values))
});
this.options.rchAmtCtrl = new RechargeAmountControl("#rechnageAmountView");
},
'input click' : function( el, ev ) {
var id = el.data('category').attr('id');
console.log(id);
this.options.rchAmtCtrl.update(id);
}
});
// Can Control
var RechargeAmountControl = can.Control({
// called when a new Todos() is created
init: function (element, options) {
// get all todos and render them with
// a template in the element's html
this.update(1);//this.update(id,this.element);
},
update : function(id){
var el = this.element;
ReachargeAmountModel.findOne({id: id}, function( rechargeAmount ){
// print out the todo name
//console.log(rechargeAmount.values[id].attr('benefit'));
el.html(can.view('RechnageAmountEJS', rechargeAmount.values));
});
}
});**
View
<form id='categoriesView'></form>
</p>
<table id='rechnageAmountView'></table>
<script type='text/ejs' id='RechnageAmountEJS'>
<tr>
<th>Recharge Amount</th>
<th>Benefits</th>
<th>Validity(Days)</th>
</tr>
<% this.each(function( rechargeAmount ) { %>
<tr>
<td>
<%= rechargeAmount.attr( 'amount' ) %>
</td>
<td>
<%= rechargeAmount.attr( 'benefit' ) %>
</td>
<td>
<%= rechargeAmount.attr( 'validity' ) %>
</td>
</tr>
<% }) %>
</script>
<script type='text/ejs' id='categoriesEJS'>
<% this.each(function( category ) { %>
<input type="radio"
name="category"
<%= category.attr('id') == 1 ? 'checked' : '' %>
value=<%= category.attr( 'name' ) %>
<%= (el) -> el.data('category',category) %>>
<%= category.attr( 'name' ) %>
</input>
<% }) %>
</script>
Main Call
new CategoryControl("#categoriesView");
There are several ways for doing this.
1. Calling methods directly
This is what you are doing and isn't necessarily wrong. To make things a little more flexible you could pass the class or instance of RechargeAmountControl when initializing CategoryControl instead of using it directly.
2. DOM events
Here it goes a little more into event oriented architecture. If you generally want to notify other Controls you can just trigger any kind of event and make them listen to it. Something like this: http://jsfiddle.net/2mxfT/11/
' rechargeAmountUpdated': function(element, event, id){
var el = this.element;
console.log(arguments);
ReachargeAmountModel.findOne({id: id}, function( rechargeAmount ){
// print out the todo name
//console.log(rechargeAmount.values[id].attr('benefit'));
el.html(can.view('RechnageAmountEJS', rechargeAmount.values));
});
}
3. Observables
Another option is to use Observables to maintain shared state. This is a great way to focus on the data and let live binding do all the rest. To make things more flexible, the state object should be passed during Control initialization (see http://jsfiddle.net/2mxfT/12/):
var state = new can.Observe();
new RechargeAmountControl("#rechnageAmountView", {
state: state
});
new CategoryControl("#categoriesView", {
state: state
});
state.attr('rechargeId', 1);
And then you can just listen to attribute changes in the RechargeAmountControl like this:
'{state} rechargeId': function(Construct, event, id){}
This handler will be called whenever you update your state Observe.
And this is also where can.route comes in. Basically can.route is an Observe that saves its state in the location hash. In the above example like #!&rechargeId=1 (unless you initialize a specific route like can.route(':rechargeId')). If the location hash changes the Observe will be updated and vice versa.

http 403 error with django and ajax

I'm working my way through 'Django 1.0 Web Site Development' and encountered a problem when using forms. The server complained about something concerning 'csrf'. I could solve it by adding {% csrf_token %} right after the form-tag. I already read the documentation at djangoproject.com but I have to admit that I don't fully understand what exactly is happening here. I don't use the middleware classes.
The real problem started when I got to ajax. I followed the instructions in the book to the letter but the server started complaining:
"POST /save/?ajax HTTP/1.1" 403 2332
Here is the code that might cause the trouble:
function bookmark_save() {
var item = $(this).parent();
var data = {
url: item.find("#id_url").val(),
title: item.find("#id_title").val(),
tags: item.find("#id_tags").val()
};
$.post("/save/?ajax", data, function (result) {
if (result != "failure") {
item.before($("li", result).get(0));
item.remove();
$("ul.bookmarks .edit").click(bookmark_edit);
}
else {
alert("Failed to validate bookmark before saving.");
}
});
return false;
}
'/save/&ajax' is being handled by
if ajax:
return render_to_response('bookmark_save_form.html', variables)
Here the bookmark_save_form.html:
<form id="save-form" method="post" action="/save/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="save" />
</form>
As far as I understand things, I have to pass a csrf_token with the POST request. But I don't have a clue how.
Any advise on this would be great.
I am currently working through this book as well and ran into the exact same problem, BTW. Not for the first time either! Essentially what is happening is that the csrf token is not being passed via the Ajax request. So, the short and simple answer is that you need to include the csrf token is your ajax call. This is accomplished via this code block: https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax
jQuery(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
I then included this as a .js file in my user_page.html. After that, I could make Ajax calls with impunity!
I pulled this from a project already done. This is a contact form template. Mind you this is for django. Also please refer to the django book http://www.djangobook.com/en/2.0/ . All my questions have been answered by this book. It goes over everything. This shows exactly how to put in the csrf token (in a template):
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact us</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">
{% csrf_token %}
<ul>
{{ form.as_ul }}
</ul>
<input type="submit" value="Submit">
</form>
</body>
Also, change your value to submit instead of save, and instead of /save/ for action use post.....that might make it work.
I am working through the book and just ran into the same problem. Here is the simplest solution, which has the benefit of not disabling Django's csrf protection or having to include decorators or fiddle with utilities like 'ensure_csrf_cookie'. It simply passes the token:
In the .js file you created to hold your custom jquery scripts, add the following pair to your 'data' var in in your bookmark_save() function:
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].val()
So the resulting bookmark_save function looks like this:
function bookmark_save() {
var item = $(this).parent();
var data = {
url: item.find("#id_url").val(),
title: item.find("#id_title").val(),
tags: item.find("#id_tags").val(),
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].val()
};
$.post("/save/?ajax", data, function (result) {
if (result != "failure") {
item.before($("li", result).get(0));
item.remove();
$("ul.bookmarks .edit").click(bookmark_edit);
}
else {
alert("Failed to validate bookmark before saving.");
}
});
return false;
}
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def my_view(request):
...
Create a Javascript file. I do not know how to format the code - sorry. Then load it after Jquery.
It is described here

Resources