JavaScript alert window after php script executed - javascript

here is may delete script - klient_usuwanie_script.php - It's working very well. BUT I would like it to present JavaScript alert when a record is deleted. So after the script deletes record it is a window with records shown - klient_usuwanie.php But I would like it to be this window with records but also with an alert saying "record deleted"
<?php
$sql = "DELETE FROM Klienci WHERE id= :del_klient";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
'del_klient' => $_GET['id']
));
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'');
?>
So to clear it up. I have a page where I see records to delete - klient_usuwanie.php with a button "delete". When I press delete the script klient_usuwanie_script.php (which is included above) deletes a record. After that it redirects to the page klient_usuwanie.php and I can see other records and I can delete them. BUT after I delete a record I would like an alert window which says "Record deleted" that's all.
When I comment out
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'');
and put
echo .$stmt->rowCount();
Than it shows me that one record was deleted but I would like it to be in an alert window and ideally alert to be shown on a redirected page.

You can redirect with query string like this:
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'&deleted=true');
And in klient_usuwanie.php, parse the query param and show alert with javascript like the following:
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("deleted") === "true") {
alert("Record deleted");
}
}

Add to header('Location:klient_usuwanie.php?msg='.urlencode($msg).'');
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'&skasowane=tak');
In the klient_usuwanie.php add someting like this:
if($_GET['skasowane']=="tak"){echo "<script>alert(\"I am an alert box!\");</script>";}

echo '<script type="text/javascript" language="Javascript">alert("Record Deleted Thats all")
</script>';

Suggestion for modern approach:
Disclaimer: This answer is more related to the intention than the exact request.
Why? Doing a full page reload for this sort of request is an outdated practice.
Nowadays, you'd more likely rely on AJAX calls for this sort of scenario.
A delete endpoint would take in a request with the ID and respond the correct HTTP code to indicate if operation was successful.
Restful HTTP endpoints can of course be written in PHP to respond with data instead of HTML.
Check out Swagger with good endpoint examples: https://editor.swagger.io
In your front-end, you could then implement the necessary JavaScript code to execute the AJAX request and manipulate the DOM as necessary.
Though many would use a Framework like Angular or React to standardise this workflow.
User Experience
This approach is far nicer to users as the browser does not need to reload the entire page again. As it only triggers one tiny HTTP request, it's much faster and the scroll location doesn't jump around either.
I've put up an example for the HTML on JS-Fiddle with jQuery to simplify the AJAX call:
https://jsfiddle.net/sny9hw73/3/
Example:
<div id="entry-<?=$id;?>" class="banner-message">
<p>My Entry with real request</p>
<button onClick="delete(<?=$id;?>);">Delete Entry</button>
</div>
<script>
function delete(id) {
$.ajax({
url: '/entry.php,
data: { 'entryId': id },
type: 'DELETE',
success: function(result) {
$('#entry-' + id).remove();
},
fail: alert('Delete Record No: ' + id + ' failed')
}
</script>
Note:
Alerts are also not always great. While simple, they stop code execution and don't render well in some scenarios. I.e.: inside webviews or on mobile devices.
They also cause fullscreen to exit.
A more professional approach is to have the notification played in the DOM.
Angular Material's Snackbar is neater in that sense.

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

How to use JS to display images from database

So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

Yii redirect from controller action after ajax call not working

I use the following buttons in my view file (don't pay attention to second one, but I just wanted to show you why I'm not using a normal form submit):
<?php echo CHtml::Button('Search Symptom(s)', array('id'=>'search')); ?>
<?php echo CHtml::Button('Add Another Symptom to Search', array('id'=>'addSymptom')); ?>
When the user clicks the buttons this javascript runs (it's inside a document.ready function)
$('#search').click(function()
{
//create new symptom in javascript
var newSymptom =
{
symptomCode: $('#symptomToBeSearchedCode').val(),
dateSymptomFirstSeen: $('#dateSymptomSeen').val(),
symptomTitle: $('#symptomToBeSearchedTitle').val()
};
//pass new symptom into symptomsList array
symptomsList.push(newSymptom);
//make ajax call to server
$.ajax({
type:'POST',
url: '/mysymptomsbook/index.php?r=symptomhistory/search',
data:{symptomsList: symptomsList} ,
dataType:'html'
});
});
symptomsList is an array with JS objects
This is the code in my controller action:
if(isset($_POST['symptomsList']))
{
foreach($_POST['symptomsList'] as $symptom)
{
//populate symptom search model attributes with user id, current date, and form input
$newSymptom = new Symptomhistory;
$newSymptom->setAttributes(array(
'user_id'=>Yii::app()->user->id,
'dateSearched'=>date('Y-m-d'),
'symptomCode'=>$symptom['symptomCode'],
'dateSymptomFirstSeen'=>$symptom['dateSymptomFirstSeen'],
'symptomTitle'=>$symptom['symptomTitle'],
));
//save search history
$newSymptom->save();
//add into the searched for symptoms code the latest code
array_push($symptomCodes, strval($symptom['symptomCode']));
}
$this->redirect(array('disease/index'));
}
I was planning on using redirect to send the $symptomCodes array to the other controlleraction (DiseasesController and actionIndex), but even without passing anything the redirect doesn't work. The models get saved to my database normally.
Anyone have any idea what is wrong? I'm thinking it has to do with Ajax since it's waiting for a response, but I want my controller to redirect instead. Any help as always, is greatly appreciated :)
I had similar problem, recommend you to look at this topic at official forum:
redirect not working when called via Ajax-Request
See the last answer in topic.

How to store HTML attributes that trigger javascript commands properly to mysql using ajax?

I have problems when saving html5 data from a page into mysql through an ajax request and trying to retrieve it back with ajax. HTML attributes that trigger some javascript such as
<onload> or <iframe> will be stored as <on<x>load> and <if<x>rame> in the database and thus screw up the page when loading it.
Here's a short description of what I am trying to accomplish: I want registered users to have the ability to highlight text on my site and get the highlighted text back after refreshing the page, relogging etc.
What I have done so far: I implemented a javascript highlight library on my server that allows users to highlight text. That works well.
By clicking a button, those data are then saved into mysql through jquery ajax post. See specific code here:
Javascript
$(document).ready(function() {
//saves highlighted data in var "highlighted"
$('#savehighlights').click(function() {
var highlighted = $('.tabcontent.content1').html();
//send data to server
$.ajax({
url: 'highlight.php',
type: 'POST',
data: {highlighted: highlighted},
dataType: 'html',
success: function(result) {
console.log(result);
}
});
});
Saving the data to mysql works generally, but it looks as if certain commands are disabled through the process (e.g. onload becomes on<x>load5). The data are stored in the database as longtext and utf8_bin. I also tried blob, but problem remains. I also tried different dataTypes with Ajax such as 'text' and 'script'. 'Text' causes the same problem and 'script doesn't work at all. I also tried the ajax .serialize function, but no luck either.
I really don't know what to do about it and I am not sure what is causing the problem, Ajax or mysql? I was searching the web for an answer, including many articles in stackoverflow (which normally always give me the answer), but this time I am stuck. Either I don't know enough about it to look for the right question, or I just don't have any luck this time. So, any help would be greatly appreciated.
I was requested to add some more information. Here it is:
I am actually doing this on my local server (localhost) with XAMP, so security issues should not be a problem, right? If it is of any help, I am doing this in a Tiki Wiki CMS. The php script that is called through ajax (highlight.php) is the following:
require_once ('tiki-setup.php');
include_once ('lib/highlights/highlightslib.php');
$highlighted = $_POST['highlighted'];
$highlightslib->save_highlights($user, $highlighted);
The highlightslib library is here:
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
class HighlightsLib extends TikiLib
{
function save_highlights($user, $highlighted) {
$saveHighlights = $this->table('tiki_user_highlights');
$saveHighlights->insert
(array(
'user' =>$user,
'highlightId' =>'',
'data' =>$highlighted,
'created' =>$this->now,
)
);
return true;
}
};
$highlightslib = new HighlightsLib;

Categories

Resources