In my response, I have a function that load a model-data of point (Google point) and serialize it, sending to the client when finish.
The code looks like:
IList<PuntoMappa> punti = new List<PuntoMappa>();
foreach (Ricettivito Struttura in StruttureFinali)
{
PuntoMappa punto = new PuntoMappa();
punto.Titolo = Struttura.Titolo;
punto.Lat = Struttura.Geo.Latitudine;
punto.Lng = Struttura.Geo.Longitudine;
punto.Categoria = Struttura.Categoria;
punti.Add(punto);
}
}
m_strPunti = jsonSerializer.Serialize(punti);
if (m_strPunti == "")
{
m_strPunti = "{ }";
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "puntiLocalizzati", "var puntiLocalizzati = " + m_strPunti + ";", true);
the problem is that I have 200/300 object inside StruttureFinali, and it took somethings like 10 seconds to load this function and serialize it.
The webpage won't show until all functions in the .cs on the WebForm is finished.
Is there a way to load this content asynch? So display the code normally, and return "this function" asynch? Client side I can manage the whole operation with ready/load events.
P.S.
StruttureFinali is a List<Ricettivito>.ToList();
Related
Im trying to get SSE working. I have a simple web with two buttons. Each one send a POST request to the server that adds a message to a list.
When the eventsource is listening, the server checks the list once each second and sends all the available messages to the client, at the same time that it marks them as readed so they won't be sent again to that client.
It kind of works but does all sorts of weird stuff:
Sometimes the button POST requests are delayed for no apparent reason and then sent all at once.
Sometimes the EventSource restarts itself making a GET request to the server.
Sometimes the server generates an exception when calling Response.Flush() after spamming the buttons: "The remote host closed the connection. The error code is 0x800704CD"
After pressing the buttons a few times, when I try to reload the page, it stays "loading" forever.
After starting the EventSource in javascript it generates a GET request that stays open and after that, any POST request that the buttons send is never sent until the event source GET request ends. Once the EventSource connection ends, all POST requests from the buttons are sent.
I know a lot of things from this code can be improved but I simplified it a lot by leaving just the essential for it to "work".
Also note that:
NotificationSystem.GetNotifications() gets all messages available for the user in a thread safe way.
NotificationSystem.AddNotification() adds the messages.
So here is the server code:
public void GetNotifs() {
try {
Response.ContentType = "text/event-stream";
while(true) {
List<string> Notifs = NotificationSystem.GetNotifications( GetUserId() );
if(Notifs != null && Notifs.Count > 0) {
foreach(var Text in Notifs) {
Response.Write( string.Format( "data: {0}\n\n", Text ) );
}
Response.Flush();
}
Thread.Sleep( 1000 );
}
} catch(Exception ex) {
Response.Close();
}
}
public ActionResult AddButton1() {
NotificationSystem.AddNotification( GetUserId(), "BTN1 (" + GetUserId() + ")" );
return Json( "OK" );
}
public ActionResult AddButton2() {
NotificationSystem.AddNotification( GetUserId(), "BTN2 (" + GetUserId() + ")" );
return Json( "OK" );
}
And the client JS code:
var urlMessages = "/Notifs/GetNotifs";
var urlButton1 = "/Notifs/AddButton1";
var urlButton2 = "/Notifs/AddButton2";
function PushBtn1() {
$.post(urlButton1);
}
function PushBtn2() {
$.post(urlButton2);
}
var myEventSource;
$(document).ready(function () {
myEventSource = new EventSource(urlMessages);
myEventSource.onmessage = function (e) {
console.log(e.data);
$('#EventLog').append("<li>Received: " + e.data + "<li>");
}
});
I everyone, I want to know how to upload a File in HTML5, without Input file, or at least without clicking on it. If there is a way to put it in without clicks and searching fo it, I would like to hear about it.
The thing is, in HTML5 I have a table, when is clicked it opens a modal with info, that info is sent by AJAX to a .jsp file, where I create a PDF using the info, in a certain path. I want to use the same file to upload it with a WCF service, but all what I could do was to create it, and then to look for it with an input file, but I want to use it with out the input file.
Here is some of my code...
The JSP File where I create the PDF file:
<%
String idP = request.getParameter("idP");
String nombreP = request.getParameter("NombreP");
String nombreC = request.getParameter("NombreC");
String presupuesto = request.getParameter("Presupuesto");
String avance = request.getParameter("Avacne");
String empleado = request.getParameter("Empleado");
String constructora = request.getParameter("Constructora");
String idC = request.getParameter("idC");
String idE = request.getParameter("idE");
String idT = request.getParameter("idT");
Font GreenFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0, 0, 255, 0));
Font yellowFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(255, 0, 255, 0));
String path = "E:" + File.separator + "Reportes" + File.separator + "Reporte " + nombreP + ".pdf";
Document document = new Document();
File file = new File(path);
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getPath()));
document.open();
Paragraph chapterTitle = new Paragraph(nombreP, yellowFont);
Chapter chapter1 = new Chapter(chapterTitle, 1);
chapter1.setNumberDepth(0);
document.add(chapter1);
document.add(new Paragraph("Nombre cliente:" + nombreC));
document.add(new Paragraph("Presupuesto: $" + presupuesto));
document.add(new Paragraph("Avance del proyecto: %" + avance));
document.add(new Paragraph("Nombre del empleado: " + empleado));
document.add(new Paragraph("Constructora: " + constructora));
document.add(new Paragraph("Id_Proyecto: " + idP));
document.add(new Paragraph("Id_Constructora: " + idC));
document.add(new Paragraph("Id_Empleado: " + idE));
document.add(new Paragraph("Id_Tipo: " + idT));
document.addAuthor("Erick Adahir");
document.addCreationDate();
document.addCreator("LorCyC");
document.addTitle("AVAVAGO");
document.addSubject("Un simple ejemplo");
document.close();
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
%>
The function that calls the JSP:
function agregarEventoDoubleClickEnTablaProyecto()
{
$('#tablaProyecto td').dblclick(function ()
{
var $this = $(this);
var row = $this.closest("tr"); //Hacemos referencia al registro padre de la celda
//alert(row.find('td:eq(0)').text());
//row.find('td:firs').text();
alert("PDF");
$.ajax({
url: "Proyecto/creaPDF.jsp",
data: {
idP: id,
NombreP: row.find('td:eq(1)').text(),
NombreC: row.find('td:eq(2)').text(),
Presupuesto: row.find('td:eq(3)').text(),
Avance: row.find('td:eq(4)').text(),
Tipo: row.find('td:eq(5)').text(),
Empleado: row.find('td:eq(6)').text(),
Constructora: row.find('td:eq(7)').text(),
idC: row.find('td:eq(8)').text(),
idE: row.find('td:eq(9)').text(),
idT: row.find('td:eq(10)').text()
}
}).done(function (data) {
alert("nice...");
});
$('#areaDatosProyecto').modal({
show: 'true'
});
});
}
And finally, the function that uploads the File using Input File:
function subir() {
var archivo = document.getElementById("btnFile").files[0];
alert(archivo);
var fr = new FileReader();
fr.onload = function () {
var bString = this.result;
var objUp = {
elemento: {
NombreOriginal: "nombre",
Documento: bString.split("base64,")[1]
}
};
$.ajax({
url: "http://localhost:84/Uploader/ServicioUploader.svc/ArchivarDocumento",
data: JSON.stringify(objUp),
dataType: "json",
type: "POST",
contentType: "application/json; charset=UTF-8",
success: function (data) {
var id = data.d;
alert(id);
},
error: function (xnr, status, error) {
alert("XNR: " + xnr + ", STATUS: " + status + ", ERROR: " + error);
}
});
};
fr.readAsDataURL(archivo);
}
Hope someone can lend me a hand! Thanks!
You are creating the file inside a JSP.
Which means that it should be created on the path (E:/Reportes/Reporte/[your filename].pdf) where your server is hosted.
You can write the code for upload right there in your JSP itself (where the file object is being created).
I dont see a point of two AJAX calls.
I am not 100% sure I understand what you're trying to do, but If I am understanding your issue correctly, it sounds like you are creating this PDF "server side" on your own system, and saving it to disk, and then on the same system loading up a "client side" web app where you have an upload control (i.e. file selector) where the user selects the PDF that is then uploaded to another server, but you are trying to avoid needing the user to manually select the file to upload in the final step.
If this is your case, unfortunately you cannot do that because it is a security risk, any modern browser will not allow you to programmatically upload a file from a user's hard drive without their manual selection of the file.
SO, not to try and be negative, but it sounds like you may be going about this the wrong way. Why don't you create AND upload the PDF from your server-side (JSP) code? It seems like adding in the client-side web app here is unnecessary. Since you already know WHERE to send the PDF (your URL looks hard-coded there) and you apparently control the server side code, it seems the simplest solution would be to just open an HTTPUrlConnection (or use whatever library you may like) to send the raw bytes of the PDF to it's final destination.
So basically, I got a php file where I create a script in the header.
In this script, I take the value of two textbox with document.getElementByID and I concatenate them in a variable. But now, in the same script, I want to send that var to a php section to use it.
I tried the ajax way, but since the php and the javascript is in the same file, it make an error.
Here is what the script section looks like :
IN FILE.PHP
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
<?php
$parameter = command; <----- obviously not working, but that's basically what im looking for
$output = exec("someExecutable.exe $parameter");
(...)
?>
}
</script>
EDIT 1
So here it is, I tried to use ajax this time, but this isn't working, seems like i miss something. Here is the server.php:
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
$output_array = preg_split("/[\n]+/", $output);
print_r($parameter);
?>
And here is my ajax call in my client.php (in a js script):
var command = "find";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
var ajax = new XMLHttpRequest;
ajax.open("POST", "server.php", true);
ajax.send(command);
var output_array = ajax.responseText;
alert(output_array);
For some reason, it doesn't go farther then the ajax.open step. On the debugger console of IE10, i got this error : SCRIPT438: Object doesn't support property or method 'open' .
You are trying to run a serverside script in your ClientSide script,
that's never going to work.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
If you want to do something with the data from text_1 and text_2, you should create a php file that can handle a post/get request via AJAX or a simple submit, featuring the data from those elements, and make it return or do whatever it is you want it to end up doing.
You can't use javascript variable (client) from php (server). To do that, you must call ajax.
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
//AJAX call to a php file on server
//below is example
var ajax = window.XMLHttpRequest;
ajax.open("POST", "yourhost.com/execute.php", true);
ajax.send(command);
}
</script>
And this is execute.php on server
<?php
$parameter = $_POST['command'];
$output = exec("someExecutable.exe $parameter");
(...)
?>
Alright... I pretty much changed and tested many things and I found out that the problem was the async property of the .send command. I was checking the value of the respondText too fast. Putting the third property of .open to false made the communication sync, so I receive the infos properly. I got another problem right now, but its not the same thing, so I will do another post.
I am currently doing an unpaid internship in C# and Asp.net. My employer has asked me to write out a javascript function so as to tell the user if they are sure if they want to delete a record from the database before deleting it.
After some research I was able to write out the Javascript function to tell the user if they are sure they want to delete this record before actually deleting it from the database.
The javascript function works. However now I have the problem of how do I call the backend C# function which will actually delete the record from the database from the front end javascript function which I have just written?
Here is my code:
Javascript function:
function watchdelete()
{
if (confirm("Are you Sure You want to delete this Manufacturer?") == true)
{
__doPostBack('btnDelete_Click','');//"PageMethods.btnDelete_Click();
}
else { }
}
Front end part which calls the javascript client side code attached to the delete button:
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick=" return watchdelete()" OnClick="btnDelete_Click1" />
Back End C# function which I want to invoke in order to delete the record from the database:
(Please note I will be happy as long as I call this function and it executes, you need not worry
about its internal workings too much. Thank you)
protected void btnDelete_Click(object sender, EventArgs e)
{
String com, command, findmodel;
if (txtManufactureName.Text != "") // If the manufacturer name is not null
{
if (txtManufactureName.Text == grdManufact.SelectedRow.Cells[1].Text) // And the manufacturer name must not be
{ // Changed from selected one
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
try
{
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
conn.Open(); // Connect to database
String moderated = (checkBoxModerated.Checked) ? "true" : "false";
findmodel = "SELECT * From VehicleModels WHERE ManufacturerID = '" + txtManID.Text + "';";
com = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
command = "DELETE From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
SqlDataAdapter finder = new SqlDataAdapter(findmodel, conn);
DataTable dat = new DataTable();
int nummods = finder.Fill(dat);
if (nummods == 0)
{
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
int number = adpt.Fill(dt); // try to find record to delete
if (number == 0) // If there is no such record to delete
{ // Indicate this to user with error message
txtMessage.Text = "Sorry, there is no such record to delete";
}
else
{ // Otherwise delete the record
using (SqlCommand sequelCommand = new SqlCommand(command, conn))
{
sequelCommand.ExecuteNonQuery();
txtMessage.Text = "Manufacturer Deleted Successfully";
txtManufactureName.Text = ""; // Reset manufacturer name
txtDescription.Text = ""; // Reset Description
checkBoxModerated.Checked = false; // clear moderated checkbox
}
}
}
else
{
txtMessage.Text = "Sorry. You must delete associated models first.";
}
conn.Close(); // Close the database connection. Disconnect.
}
BindGrid(); // Bind Manufacturer Grid again to redisplay new status.
}
catch (SystemException ex)
{
txtMessage.Text = string.Format("An error occurred: {0}", ex.Message);
}
}
else
{
txtMessage.Text = "Sorry. You cant change the manufacturer name before deleting";
}
}
else
{ // Otherwise give error message if manufacturer name missing
txtMessage.Text = "Please enter a manufacturer name to delete";
}
}
Any ideas will be appreciated.
Let's simplified your validation function to:
function confirmDelete(){
return confirm("Are you Sure You want to delete this Manufacturer?");
}
Then your button with OnClientClick attribute will be something like
OnClientClick=" return confirmDelete()"
As long as your validation function returns false .NET will not submit your code the server.
To give people an understanding of how to call backend functions from client side Javascript I would like to put the answer here in my own words -> Simple plain English:
Step
1. Write your Javascript function and place it on the client side and enable scripts whatever, not going into too much detail here. See the code snippet below for an example
<script type = "text/javascript" >
function watchdelete()
{
return confirm("Are you Sure You want to delete this Manufacturer?");
}
Write your button or control front end code and ensure that your OnClientClick = the name of the javascript function you want to call plus the word return in front of it as in the example asp
code shown in the original post.
Ensure you fire up the backend C# function as per usual for example by double clicking on the button or control in design view of Visual Studio 2012 or 2013 or whatever so as to automatically build its backend function in the code behind page and code your backend function for what you want it to do obviously.
When you have done step 3 correctly you should have OnClick= whatever your backend C# function was.
Test your application. Once your front end javascript returns true it should automatically fire up
your backend function as long as you have put a return statement as per the front end code shown in the original post or similar.
Life can be simple if only you want it to be. The choice is yours.
I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});