Can I write SQL update inside ajax code? - javascript

I have been working on an ajax code in which I need to update a SQL table. I am not sure if I could write SQL code inside ajax or not as I am completely new to AJAX. While I was trying, I was having issue i.e when I write code for SQL update inside the ajax code, it gives me an error saying "Uncaught Syntax Error: Missing catch or finally after try". Here is the code that I am working on:
$("#ktId").change(function(){
var cataid = $("#ktId option:selected").val();
var tktid = $(this).attr('tktid');
if (tktid != '') {
$.ajax({
async: false,
type : 'POST',
url : 'ajax/ticketload_test.asp',
data : { cataid: cataid, tktid: tktid },
success : function(responseData) {
try {
SQL = "UPDATE tbltkt SET ticketType = '& cataid &' WHERE id = '" & Request("tktid")& "'"
}
}
catch(e) {/*ignore*/}
}
});
} else {
alert("Please fill in the catagory!");
}
});
Background:
In classic ASP, I have to create and select the value from the drop-down list. So "#ktId" above mentioned is the id for the drop-down. After selecting an option from drop-down, I just need to update the table i.e tbltkt mentioned above. "ticketType" is the field or column for the options in the drop-down. So can anyone please mention or point out my mistake here. Can I use SQL update code in the ajax?

Please don't do that. Read about SQL injection here: SQL INJECTION
All your SQL code must be present ONLY in the server side or as a Stored Procedure. Just send your variables to the server and make the query in the server side. Please read about SQL Injection in order to avoid hacking.

It's not really safe. Maybe you should reconsider your architecture? However, your syntax error is because of extra brace after SQL. But still, any your SQL procedures won't work if you write it in callback

The main point here is that who should actually access the database is your application server (IIS if you're using ASP in the backend), which is in turn listening to your AJAX requests. So, the code that access your database may be in the server side, and not mixed with the javascript functions, what could lead to SQL injection attacks as described in another answer above.
So you should have to code some server handler to listen to your AJAX call on wich you put the parameters that this handler will use to construct the SQL query, launch it against the database server, and return a view (or JSON data) with the results.
Sorry but I cannot be more specfic if you don't give more details about the architecture of your application and the technologies you're using.

Related

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);
})

Real time insertion of data in mvc

I have a news project with comment feature. Any one who add a comment can see his comment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) comment on post1 , only user1 can see his comment immediately but all other users need to reload the page to see the comment of user1. How can I solve this problem ?
The code I am using to get the comment :
$(function () {
$("#AddComment").click(function () {
var CommentText = document.getElementById("CommetForm").innerHTML;
var UserName = document.getElementById("UserName").innerHTML;
var PostId = document.getElementById("PostId").innerHTML;
$.ajax({
url: '/PostComment/AddComment',
type: 'POST',
dataType: 'json',
cache: false,
data: { "PostId": PostId, "CommentText": OrignalCommentText },
success: function (data)
{
if (data == "P") // Commet Stored on database successfully
{
document.getElementById("PostComments-" + PostId).innerHTML +=
"<li>" +
"<div class='media'>" +
"<div class='media-body'>" +
"<a href='' class='comment-author'>"+UserName+"</a>" +
"<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
"</div>" +
"</div>" +
"</li>";
}
else // Some Error occur during storing database
{
document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";
}
}
});
});
});
And This code for storing comment in database :
private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();
[HttpPost]
public JsonResult AddComment(string PostId, string CommentText)
{
try
{
Users CurrentUser = (Users)Session["CurrentUser"];
PostComment postcomment = new PostComment();
CommentText = System.Uri.UnescapeDataString(CommentText);
postcomment.PostId = int.Parse(PostId);
postcomment.CommentFromId = CurrentUser.UserId;
postcomment.CommentText = CommentText;
postcomment.CommentDate = DateTime.Now;
db.PostComments.Add(postcomment);
db.SaveChanges();
return Json("P");
}
catch
{
return Json("F");
}
}
I suggest you use SignalR for this. http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr
TL;DR Use can use setInterval or Websockets to accomplish this. Below I explain how.
First of all, we need to understand what is behind this Publish/Subscribe pattern. Since you want to build a real-time application, you may create a function that asks to your server if some data was added since last time it was checked.
USING WindowTimers.setInterval()
Here is the simplest way to accomplish this in my point of view, assuming that's your first time and you never worked with websockets before. For instance, in your client-side project you create a function within a setInterval setInterval( checkNewData, time). Your method checkNewData() will make an ajax requisition to your server, asking if some data was added recently:
function checkNewData() {
// ajax call
// On response, if found some new comment, you will inject it in the DOM
}
Then, in your server-side method, get the timestamp of its call and verify in your database if there are some data. Something like this:
// Method written in PHP
public function ajax_checkNewData() {
$time = time();
// Asks to your model controller if has something new for us.
// SELECT comment FROM comments WHERE timestamp > $time
// Then return its response
}
You will use the response that came from your controller method ajax_checkNewData() to write on your comments-container.
USING WEBSOCKETS (beautiful way)
Now, there are another way to do this, using WebSockets. HTML5 WebSocket represents the first major upgrade in the history of web communications. Before WebSocket, all communication between web clients and servers relied only on HTTP. Now, dynamic data can flow freely over WebSocket connections that are persistent (always on), full duplex (simultaneously bi-directional) and blazingly fast. Amongst different libraries and frameworks, you can use socket.io. I believe this will solve your real-time application problem pretty good, but I am not sure how much of your project you will need to change to suit this solution.
Check it out the simple chat tutorial from SocketIo page and see for yourself if it fits to your needs. Its pretty neat and would be a good challenge to implement using it. Since its event-driven, I believe you wont have problems implementing it.
For further information check it out:
REFERENCES
Get Started: Chat application - http://socket.io/get-started/chat/
Websockets - http://en.wikipedia.org/wiki/WebSocket
WebSockets - https://developer.mozilla.org/en/docs/WebSockets
Good luck!
You could write a JavaScript code which makes ajax call to a servlet that checks for updates in the database.
Return a flag to the success function of the ajax call and If the state has changed or any comment added to the database, you can reload the page or refresh the consisting of the comments with the new comments.
It's not posting on other pages, because the user1 page is making an AJAX call, so it loads correctly. However, the other pages don't 'know' they are supposed to reload via AJAX. You need some kind of timed loop running that checks for any changes. Either of the above answers should work for it.
You could use SignalR for this, you can send realtime messages to the server, here is a sample to know how to implement SignalR in ASP.NET MVC
https://github.com/WaleedChayeb/SignalRChatApp

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.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

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