Error message when data not inserted in oracle apex - javascript

I have an insert query in oracle apex, sometimes the data are not inserted because of different reasons (for example writing a text in number field). is there a way to display an error message that check if data is inserted in the database or not?

This is how this can be done for a page process of type pl/sql. Example is on the sample dept table.
Create 2 page hidden page items: P48_SUCCESS_MESSAGE and P48_ERROR_MESSAGE
In the page process that does the update use the following code
DECLARE
e_invalid_insert exception;
BEGIN
INSERT INTO dept(dname, loc) VALUES (:P48_DNAME,:P48_LOC);
:P48_SUCCESS_MESSAGE := 'Insert succesful';
EXCEPTION WHEN OTHERS THEN
-- below code will also show database error, adjust for your requirements
:P48_ERROR_MESSAGE := 'Insert failed:' ||SQLERRM;
RAISE e_invalid_insert;
END;
For the attribute "Success Message" of the page process put &P48_SUCCESS_MESSAGE., For the attribute "Error Message" of the page process put &P48_ERROR_MESSAGE.
Check the help text for "Error Message" and "Success Message" for available substitution strings.
Note, you state sometimes the data are not inserted because of different reasons (for example writing a text in number field). As a developer you can put in validations to ensure that the data is correct before the insert process is executed. If a validation fails, the insert statement will not be executed (and it should not be executed).

Related

How to submit a form and execute javascript simultaneously

As a follow-up to my last question, I have run into another problem. I am making a project on google homepage replica. The aim is to show search results the same as google and store the search history on a database. To show results, I have used this javascript:-
const q = document.getElementById('form_search');
const google = 'https://www.google.com/search?q=';
const site = '';
function google_search(event) {
event.preventDefault();
const url = google + site + '+' + q.value;
const win = window.open(url, '_self');
win.focus();
}
document.getElementById("s-btn").addEventListener("click", google_search)
To create my form, I have used the following HTML code:-
<form method="POST" name="form_search" action="form.php">
<input type="text" id="form_search" name="form_search" placeholder="Search Google or type URL">
The terms from the search bar are to be sent to a PHP file with the post method. I have 2 buttons. Let's name them button1 and button2. The javascript uses the id of button1 while button2 has no javascript and is simply a submit button.
The problem is that when I search using button1, the search results show up but no data is added to my database. But when I search using button2, no results show up( obviously because there is no js for it) but the search term is added to my database. If I reverse the id in javascript, the outcome is also reversed. I need help with making sure that when I search with button1, it shows results and also saves the data in the database. If you need additional code, I will provide it. Please keep your answers limited to javascript, PHP, or HTML solutions. I have no experience with Ajax and JQuery. Any help is appreciated.
Tony since there is limited code available so go with what you had stated in your question.
It is a design pattern issue not so much as so the event issue.
Copy pasting from Wikipedia "software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system."
So here is how things play out at present;
forms gets submitted to specific URL i.e. based on action attribute
Requested page gets Query sting in php and lets you play around with it
then from there on .....
3. either you get results from database and return response
4. or you put search request into database and return success response
Problem statement
if its 3 then search request is not added to database if its 4 then results in response to search request are not returned.
Solution
you need to combine both 3 and 4 in to one processing block and will always run regardless of the search query is.
So our design pattern could use mysql transaction so whole bunch of queries would run a single operation example
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
slightly more safe version
try {
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
} catch (\Throwable $e) {
// An exception has been thrown must rollback the transaction
$db->rollback();
echo 'oho server could not process request';
}
We have effectively combined two query operation into one always recording into database and always searching in database.

JQuery Fetch data from MySQL and store into Variable

I am continuing to work on my multi stage bootstrap form, and I have hit a roadblock trying to pull info from my DB.
The main page is PHP and is named quote_tool.php
I have the following functional requirements:
The data must come from the MySQL database.
The user should only receive data that they requested (i.e. a row from the db with info about user license should only be grabbed if the user checked a radio button to include user licenses on the form).
The information needs to be called from the DB without refreshing/reloading the page.
Currently I have a table in my DB with the following columns:
There are 3 different products in that table right now. The user can select a radio to say they want to include endpoints, and then there are 3 check boxes to allow the user to input a quantity for which endpoint(s) they want to include.
The input field looks like this:
<label for="device-9102" class="form-partner-label"><input type="checkbox" class="quote-chkbox" id="9102-chk"> 9102 IP Phone</label>
<input type="text" name="9102-quantity" class="form-endpoint-qty form-control" id="form-partner-9102" readonly value="0">
When the user checks the box and input a value this value is dynamically updated on the summary page as well in the following field:
<input type="text" readonly name="sum-9102-qty" class="summary-field sum-qty" id="sum-9102-qty">
There is also 2 other fields on the summary page regarding this product.
MSRP
Part Number
MSRP is a hidden field that will be used for additional calculations, but Part Number is visible on the summary page.
When the user inputs the value for the endpoint quantity I need to call the DB and pull the MSRP and Part Number from the refEndpoints table.
I am currently building a function to call the DB when the user hits the "Next" button on the form, and that looks like this:
//Call DB to fetch part number and msrp of 9102
$('#form-partner-9102').change(function()){
var quantity_9102 = $('#form-partner-9102').val();
if(quantity_9102 !== 0) {
}
});
This is the point that I am stuck at. I am not sure how to call the DB and place the values of the part number and the MSRP in the correct input fields on the summary page.
jQuery runs on the client side so it cannot connect to MySQL directly, however your question is tagged php, which runs on the server side and thus can connect to your database. First you will need to setup a PHP file that can respond to HTTP POST requests and return JSON. Here is a great answer that shows you how to do this: Returning JSON from PHP to JavaScript?
Once set up (and you will need to workout what parameters this PHP file takes in and how it converts this into a query so that it can respond) you can now setup some simple JavaScript to call this PHP file (lets call it query.php). Code that does this might look like this:
$.post('/query.php', {quantity: $('#form-partner-9102').val()}, function(resp) {
$('#PartNumber').html(resp.PartNumber);
});
Some important things to keep in mind are to always be sure to use prepared statements when taking user input and turning it into a query (don't just build a SELECT statement by joining strings). Also be sure to look at your event binding, you can probably write one generic handler for your inputs that takes the partner ID as a data-* attribute making your code smaller and easier to maintain.

Simple online web game crash eventually

Background:
I am making a simple game in PHP, JavaScript and HTML for the web. A player control movements of a box on the screen, and see others fly around with their boxes.
I have the following files, that I upload to my domain via a hosting company:
index.html: a file with some buttons (eg. to start the game) and frames (for putting boxes in).
server.php: PHP script that receives messages from client, performs reads/writes to a database, echoes (using echo) boxes from database to the client. Does not echo the box of the player the message came from.
database.txt: a JSON text file containing data of players and the next free ID number. When empty it looks like this: {"players":[], "id": 1}. players contain objects with values such as ID, position and rotation.
script.js: JavaScript file with script to send/receive messages, display data from messages etc. Linked to index.html. Moves your box.
A screenshot, two players in movement:
Problem: The game crashes, always. Sooner or later. This is what happens:
Client recevies player data from server.php, everything is fine. This could be for 10 seconds or up to some minutes.
The data starts to falter, the message sometimes is null instead of actual data.
The data recevied is always null. The database file is now {"players":null,"id":5}. (The "id" could be any number, does not have to be 5).
Picture of data flow, printing of players from database. Two players. Before this screenshot lots of rows with valid data. Then as seen two null messages. Then after a while null forever.
I am not completely sure where the problem is, but I am guessing it has to do with my read/write in server.php. I feels like a lot of player movement makes the program more likely to crash. Also how often the program sends data affetcs.
Code Piece 1: This is code from server.php, that writes to the database. I have some sort of semaphore (the flock( ... ) ) to prevent clients from reading/writing at the same time (causing errors). I have an other function, read, which is very similar to this. Possible problems here:
The semaphore is incorrect.
The mode for fopen() is incorrect. See PHP docs. The mode w is for write. The tag b is for "If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data ...".
Something weird happening because I use read() in my writing function?
Code:
// Write $val to $obj in database JSON
function write($obj,$val){
$content = read();
$json = json_decode($content);
$json->{$obj} = $val; // eg. $json->{'id'} = 5;
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
if(flock($myfile, LOCK_EX|LOCK_NB)) {
fwrite($myfile,json_encode($json));
flock($myfile, LOCK_UN);
}
fclose($myfile);
}
Code Piece 2: This is my code to send data. It is called via a setInterval(). In script.js:
// Send message to server.php, call callback with answer
function communicate(messageFunc,callback){
var message = messageFunc();
if (window.XMLHttpRequest) {
var xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange= function() {
if (this.readyState==4 && this.status==200) {
callback(this.responseText);
}
}
xmlhttp.open("GET","server.php?msg="+message,true);
xmlhttp.send();
}
This is my code to receive data, in server.php: $receive = $_GET["msg"].
My current work of solving
This is what I have done so far, but nothing has changed:
Added mode b to fopen().
Added flock() to read/write functions in server.php.
Much reworking on script.js, I would say it looks/works very clean.
Check memory_get_peak_usage(), and check with the hosting company for memory limits. Should be no problem at all.
Looked at PHP garbage collecting and gc_enable() (I don't know why that would change anything).
Lots of testing, looking at the data flow.
Crying.
Conclusion: Is this type of application what PHP is for? What do you think is wrong? If you want more code/info I provide. Thank you very much.
Here is the root of your problem:
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
Note the behavior of the w open mode (emphasis mine):
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
This happens before you lock the file. What's happening is that between this fopen() call and the following flock() call, the file's content is zero length, and a reader is coming along during that time and reading the empty file.
Why doesn't this cause an error in PHP when you parse the empty string as JSON? Because json_decode() is defective, and returns null when the input is not valid JSON rather than throwing an exception. Nevermind that the string "null" is valid JSON -- json_decode() gives you no way to differentiate between the cases of valid input representing the null value and invalid input. If json_decode() actually threw an exception or triggered a PHP error (don't ask me why two error-signalling mechanisms are necessary in PHP), you would have a fantastic point to start debugging to figure out why the file is empty, and you might have solved this problem by now!
... sigh ...
PHP's "design" gives me headaches. But I digress.
To fix this whole problem, change the open mode to "cb" and ftruncate($myfile, 0) after you successfully acquire the lock.
Note the behavior of the c mode, which actually specifically mentions the approach you are using (emphasis mine):
Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).

I am unable to set back data to ckeditor instance which I fetched from it and stored in database?

I have a Django web app which has various instances of ck-editor instances on a web page.By using on blur event I am saving whole of data of the instance in the database -
{% for editor in editors %}
CKEDITOR.appendTo("{{editor.ck_id}}" ,
{
on: {
blur: function(event){
var data = event.editor.getData();
console.log("data of {{editor.ck_id}} is " + data);
var request = $.ajax({
url: "/editor/save/",
type: "GET",
data: {
content : data,
content_id : "{{editor.ck_id}}"
},
dataType: "html"
});
}
}
}
// "{{editor.data}}"
);
CKEDITOR.instances['{{editor.ck_id}}'].insertHtml("{{editor.data}}");
Here ck_id and data are the two database fields of ckeditors.Now suppose I write this on one instance of ckeditor -
Tony Stark
When I lose focus on that instance then on blur event is fired and I use 'getData()' to get the html data of that instance.
<p>Tony Stark</p>
is saved into the database.On the python interpreter now when I fetch editor's data it shows -
<p>Tony Stark</p>
which is obvious.
Now When I re start the server and set the data of every ck-editor instance again then this exception is raised -
Uncaught SyntaxError: Unexpected token ILLEGAL
I know why this is happening - due to this -
CKEDITOR.instances['ck_1'].insertHtml("<p>Tony Stark</p>
");
The data which I sent by fetching from database was -
<p>Tony Stark</p>
and it somehow got converted to above mentioned text with illegal tokens.I have tried to use setData() but with no result. Do I need to encode/decode this HTML or something?
Now my question is how to again reset data to a ck-editor instance which I fetched from it and stored in database. I have posted this question on several forums but many people have got no clue of what I am asking?
Is there anyone here who has tried to do same thing and have succeeded in it?
Thanks
PS: Adrian Ghiuta solution seems to be working but there is just problem. When the editor is loaded first time then in google chrome's debugger inserted line is seen as -
"<p>Tony Stark</p>"
which is rendered due to line "{{editor.data|safe}}".But when I change my editor's content to just
Tony
then in database
<p>Tony</p>
is being saved but when I restart the server it does not render and throws this error
Unexpected ILLEGAL TOKEN
due to this -
"<p>Tony</p>
"
Here ending double quotes are in the next line.But during initial data loading it was on the same line.Might this be causing be any problem?
Because my chrome console shows error at that position.
I will add some images to show the condition.
Initial loading -
Initial console -
Editor after editing -
Error being shown after restarting server and reloading editors -
Console -
You can see how error is thrown at line where double quotes are at the next line.Do I to escape html or something?
Sorry for my naivety but I do not have much command over HTML.

get running count (in Cognos Javascript)

How can I get the number of rows that will be returned by a sql for a Report Studio report at run time in Javascript? The purpose is to terminate the report as it exceeded the row limitation and notify the user an alert message to re-enter prompts that would reduce the volume of data. Doing so the users will be able to run the report with new prompts without having to re-run the report.
I could find couple of options to limit the maximum rows returned but all they do is terminate the report with an error.
I can suggest another solution. Without Javascript.
Create condition block based on row count.
Add a Query Item with value
Count([Your field]) for report
Add Singleton with your query and this new Query Item.
Set Query property for Page to your main query.
Set Processing property for your main query to "Limited local"
Add Conditional Block with new variable e.g. boolean. Value
[Your query].[Your new field] > 1000
Put you report on a "No" page of conditional block, and a message about row limitation on a "Yes" page.
This solution will work even if you use Excel output.
You can try to add HTML Item to row. Source Type = Report Expression
Put inside
'<script language="javascript">
if ('+number2string (RowNumber ())+'>500){
//Put here code that stops page loading
}
</script>'
But, I don't know how to stop load Cognos page. Usual ways don't work.
You can hide or erase a part of report (whole List), but Cognos load all data anyway.

Categories