I need an interval of 3 seconds to execute each mysql_query - mysql

I'm doing a simple chat and everything is working well, but everybody can flood the chat sending how many messages they want to...
PHP:
<div id="chat_panel"></div>
<br />
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input type="text" autocomplete="off" maxlength="50" placeholder="Type your message..." id="message" size="87%" checked="yes"></td>
<td><input type="button" id="message" onClick="sendMessage()" value="Send"></td>
</tr>
</table>
JAVASCRIPT:
function sendMessage() {
var message = $('#message').val();
$.post('postMessage.php', { message: message } , function() { } );
}
postMessage.PHP:
session_start();
include ("chats/connect.php");
$timname = $_SESSION['username'];
if (isset($_POST['message'])) {
mysql_query("INSERT INTO chat VALUES ('', '".$timname."', '".$_POST['message']."', '".time()."', NOW(), '');");
}
I need to set a interval to send each message like 3 seconds...
Any information will be helpful!

Try Jquery to refresh specific page. Try something like below code
setup.js
var autorefresh=setInterval(
function()
{
$("query.php").load('query.php');
e.preventDefault();
},3000);
query.php
session_start();
include ("chats/connect.php");
$timname = $_SESSION['username'];
if (isset($_POST['message'])) {
mysql_query("INSERT INTO chat VALUES ('', '".$timname."', '".$_POST['message']."', '".time()."', NOW(), '');");
}
Here 3000 in setup.js is time in miliseconds you want to refresh.

Related

How do I display the content fetched from database(using the jsp file) on my html page using ajax?

I have a HTML file named Track.html, it contains a text box. We enter a 10 digit number and click the button to search. After validation an AJAX function is called, which sends the number to a jsp file and the input number is searched in the database, if the value is found in the database, the output should be displayed in another text box on the same HTML page(without changing the URL). But the problem is that it is not working.
To check that my jsp file is working properly, I did the following:
I'm using a form tag so in its action attribute I mentioned the jsp file and not calling the AJAX function, so after searching the input number it redirects to a new page and displays the corresponding content fetched from the database, but I want the content to be displayed on the same page.
Here is the HTML part:
<fieldset>
<form method="post">
<table cellpadding="10" cellspacing="10">
<tr>
<td><strong>Consignment Number</strong></td>
<td><input type="text" id="cons" name="cons" autofocus="true"
placeholder="Enter the 10 digit Consignment Number"
</td>
</tr>
<tr>
<td align="center"><button onclick="search()
<span>Search</span></button></td>
<td><span><input type="reset"></span></td>
</tr>
</table>
</form>
</fieldset>
<br>
<fieldset>
<table cellpadding="10" cellspacing="10">
<tr>
<td><strong>Your Package is at:</strong></td>
<td><input type="text" id="result"></td>
</tr>
</table>
</fieldset>
Here is the AJAX function:
function search() {
if (validate()) {
var cnum = document.getElementById('cons').value;
var obj1 = new XMLHttpRequest();
obj1.onreadystatechange = function () {
if ((obj1.readyState == 4) && (obj1.status == 200)) {
document.getElementById("result").value = obj1.responseText;
}
}
obj1.open("get", "Trace.jsp?cn=" + cnum, true);
obj1.send();
}
Here is the jsp code:
<%#page import="java.sql.*"%>
<%
try
{
int conum=Integer.valueOf(request.getParameter("cn"));
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/postal_info","root","*******");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from trace;");
while(rs.next())
{
int c=rs.getInt(3);
if(conum==c)
{
out.println(rs.getString(6));
}
}
}
catch(Exception e)
{
out.println(e);
}
%>

How to post table data without refreshing my view after removing a record?

I am writing a movie app that allows you to rent movies (similar to Redbox). I have a CheckOut cart view containing a table. Each table row has a remove button which uses AJAX to delete element in the view and also update the SQL database that the app works with. After removing any items from the cart, the user should be able to click 'purchase' and process the items that were left in the cart, all without needing to refresh the page.
I have an Order model containing a list of OrderDetails. Each OrderDetails item has information about a movie. It is data from OrderDetails list that the table is populated with.
The issue comes in when I remove items from cart and try to post the form with the values in the table. My CheckOut HttpPost controller method receives the model, but the OrderDetail list still has the item count it originally had before I removed items from cart. Logically, there is no data bound to the properties since I deleted the hidden tags I had in each record.
Because the list contains elements I don't need, processing the list results in garbage data going into the database.
I tried to simply remove the garbage elements within my CheckOut HttpPost method before it begins processing the list. This worked great but I don't want to have to remove anything in the CheckOut method after posting the form. I'm expecting the list to not contain the elements.
CheckOut POST method:
[HttpPost]
public IActionResult CheckOut(Order order)
{
if (ModelState.IsValid == false)
{
return View("CheckOut", order);
}
foreach (var orderDetailObj in order.OrderDetailsList)
{
_checkOutService.StoreMoviesInOrder(GetConnectionString(), order.OrderId, orderDetailObj);
}
return RedirectToAction("PurchaseSummary", new { Id = order.OrderId });
}
CheckOut.cshtml view:
#model MovieContract.Order
...
#for (int i = 0; i < Model.OrderDetailsList.Count; i++)
{
<tr>
<td>
<input type="button" name="btnRemove" class="removeButton" value="Remove" onclick="Remove(this, '#Model.CartId', #Model.OrderDetailsList[i].Movie.FilmId)" />
</td>
<td hidden>
<input asp-for="#Model.OrderDetailsList[i].Movie.AddedToCart" value="#Model.OrderDetailsList[i].Movie.AddedToCart" hidden />
</td>
<td hidden>
<input asp-for="#Model.OrderDetailsList[i].Movie.FilmId" value="#Model.OrderDetailsList[i].Movie.FilmId" hidden />
</td>
<td>
<input asp-for="#Model.OrderDetailsList[i].Movie.FilmName" value="#Model.OrderDetailsList[i].Movie.FilmName" hidden />
#Model.OrderDetailsList[i].Movie.FilmName
</td>
<td>
<input asp-for="#Model.OrderDetailsList[i].Movie.GenreName" value="#Model.OrderDetailsList[i].Movie.GenreName" hidden />
#Model.OrderDetailsList[i].Movie.GenreName
</td>
<td>
<input asp-for="#Model.OrderDetailsList[i].Movie.PricePerDay" value="#Model.OrderDetailsList[i].Movie.PricePerDay" class="pricePerDay" hidden />
#Html.DisplayFor(modelItem => #Model.OrderDetailsList[i].Movie.PricePerDay)
</td>
<td hidden>
<input asp-for="#Model.OrderDetailsList[i].Movie.AmountOnHand" value="#Model.OrderDetailsList[i].Movie.AmountOnHand" hidden />
</td>
</tr>
}
As for AJAX, I simply have an AJAX function that calls a post controller method. The method deletes the appropriate item from the database and returns NoContent();. Upon success, AJAX deletes the desired row from the view.
I expect that by the time I reach the CheckOut HttpPost method, the parameter object's list property will contain less elements if I had decided to remove any from the cart. I don't want to have to refresh the whole page to rebuild my model each time I remove an item from the cart.
Here is a working demo :
View
#model AjaxDeleteItem.Models.Order
<div>
<form method="post" asp-action="CheckOut">
<table class="table" id="table">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.OrderDetailsList.Count; i++)
{
<tr class="count">
<td>
<input type="button" name="btnRemove" class="removeButton" value="Remove" onclick="Remove(this, #Model.OrderDetailsList[i].Id)" />
</td>
<td >
<input class="FilmId" asp-for="#Model.OrderDetailsList[i].Movie.FilmId" value="#Model.OrderDetailsList[i].Movie.FilmId" />
</td>
<td >
<input class="FilmName" asp-for="#Model.OrderDetailsList[i].Movie.FilmName" value="#Model.OrderDetailsList[i].Movie.FilmName" />
</td >
<td>
<input class="GenreName" asp-for="#Model.OrderDetailsList[i].Movie.GenreName" value="#Model.OrderDetailsList[i].Movie.GenreName" />
</td>
<td>
<input class="PricePerDay" asp-for="#Model.OrderDetailsList[i].Movie.PricePerDay" value="#Model.OrderDetailsList[i].Movie.PricePerDay" />
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Submit"/>
</form>
</div>
#section Scripts
{
<script>
function Remove(obj,id) {
$.ajax({
type: "post",
url: "/orders/deleteorderitem?id="+id,
success: function () {
$(obj).closest('tr').remove();
var count = $(" tbody tr").length;
var i = 0;
$("tbody tr").each(function () {
var row = $(this);
if (i < count)
{
row.find("input[class=FilmId]").attr("name", "OrderDetailsList[" + i + "].Movie.FilmId");
row.find("input[class=FilmName]").attr("name", "OrderDetailsList[" + i + "].Movie.FilmName");
row.find("input[class=GenreName]").attr("name", "OrderDetailsList[" + i + "].Movie.GenreName");
row.find("input[class=PricePerDay]").attr("name", "OrderDetailsList[" + i + "].Movie.PricePerDay");
i++;
}
});
},
error: function () {
alert("Fail to delete");
}
});
}
</script>
}
2.Controller:
[HttpPost]
public async Task<IActionResult> DeleteOrderItem(int id)
{
var orderdetail = await _context.OrderDetails.FindAsync(id);
_context.OrderDetails.Remove(orderdetail);
await _context.SaveChangesAsync();
return NoContent();
}
[HttpPost]
public IActionResult CheckOut(Order order)
{
if (ModelState.IsValid == false)
{
return View("Details", order.CartId);
}
//the stuff you want
}
3. Result :

How to navigate through html tab with casperjs

i need your experience in casperjs!
I am trying to access a web page (which is not an issue) and to navigate through a html tab.
When i access the page it is by default always showing the first tab "General" but i need to switch to "Options" tab so that i can access one field that i am interested to modify the value!
Sorry, can't post images yet!
Html code:
<b> <b>
<table class="commonfont" cellpadding="0" cellspacing="0" background="/tab_between.png" border="0">
<tbody>
<tr>
<td><input name="" src="/tab_sel_left.png" border="0" type="image"></td>
<td align="center" background="/tab_sel_bg.png">
General
</td>
<td><input name="" src="/tab_sel_right.png" border="0" type="image"></td>
<td width="1"></td>
<td><input name="" src="/tab_unsel_left.png" border="0" type="image"></td>
<td align="center" background="/tab_unsel_bg.png">
Options
</td>
<td><input name="" src="/tab_unsel_right.png" border="0" type="image"></td>
<td width="1"></td>
</tr>
</tbody>
</table>
...
</b></b>
My casper.js file looks like this:
...
casper.then(function() {
test.assertTextExists("DB", "Login into DB 2");
this.click('a#changeThis1_link');
});
casper.then(function() {
test.assertTextExists("Options", "DB Options");
this.click('a#menu1itemUnSel[tabindex="4"]');
});
casper.then(function() {
test.assertTextExists("Change", "DB -Change -Step 1/2");
this.fill('form[name="dbActionForm"]', {
'generalParams.poolSize': '1',
}, false);
this.click('input[name="Apply"]');
});
...
I just can't figure out what should this line look like:
this.click('a#menu1itemUnSel[tabindex="4"]');
since this isn't working!!!
Execution printout:
modifying DB pool size:
Test file: /target.js
# DB modify
PASS DB has the correct title
PASS login form is found
PASS Login into DB
PASS Login into DB 1
PASS Login into DB 2
PASS DB Options
FAIL Cannot dispatch mousedown event on nonexistent selector: a#menu1itemUnSel[tabindex="4"]
# type: uncaughtError
# error: Cannot dispatch mousedown event on nonexistent selector: a#menu1itemUnSel[tabindex="4"]
# CasperError: Cannot dispatch mousedown event on nonexistent selector: a#menu1itemUnSel[tabindex="4"]
# at mouseEvent (/casper.js:1323)
# at click (/casper.js:428)
# at /target.js:34
# at runStep (/casper.js:1523)
# at checkStep (/casper.js:368)
# stack: not provided
Any clue what i am doing wrong and how can i overcome this issue?
Thanks for your time
Some updates and more information:
After Fanch information, I changed the casperjs to:
...
casper.then(function() {
test.assertTextExists("DB", "Login into DB 2");
this.click('a#changeThis1_link');
});
casper.then(function() {
test.assertTextExists("Options", "DB Options");
this.click('a.menu1itemUnSel[tabindex="4"]');
});
casper.then(function() {
test.assertTextExists("Change", "DB -Change -Step 1/2");
this.fill('form[name="dbActionForm"]', {
'generalParams.poolSize': '1',
}, false);
this.click('input[name="Apply"]');
});
...
This a.menu1itemUnSel[tabindex="4"] solved my error about changing the tab but i still have the issue with reading/changing the field generalParams.poolSize.
I even added then waitForSelector/waitForText but still get the error: Errors encountered while filling form: form not found
See casperjs:
...
casper.then(function() {
test.assertTextExists("Options", "DB Options");
this.click('a.menu1itemUnSel[tabindex="4"]');
});
casper.waitForSelector("a#dve_menu_datarepositories", function() {
this.echo("1.Loading form");
});
casper.waitForText("50", function() { //the field that i want to change has text '50'
this.echo("2.Loading form");
});
casper.then(function() {
test.assertTextExists("Change", "DB -Change -Step 1/2");
this.fill('form[name="dbActionForm"]', {
'generalParams.poolSize': '1',
}, false);
this.click('input[name="Apply"]');
});
...
Thanks again
Sorry i was away for a while, here is some html part of the page:
<a name="topofpage">
<form autocomplete="off" enctype="application/x-www-form-urlencoded" action="/db.do" method="post" name="dbActionForm">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr height="100%">
<td valign="top" height="100%"></td>
<td valign="top" height="100%" background="/menu3_sel_right1.png"></td>
<td class="commonfont" width="100%" valign="top" background="/menu3_sel_right1.png" align="left">
<b>
<b>
<table class="commonfont" border="0" cellspacing="0" cellpadding="0" onkeypress="return onWizardPageKeyPress(event);">
<tbody>
<tr id="generalParams.poolSize_TR" class="formpagefieldname" style="display:table-row;">
<td>
<a id="generalParams.poolSize_changeA" style="visibility:hidden;" title="Undo Change" onclick="revertSingleChange('generalParams.poolSize', false); dependantsRunOnLoad(document.body); return false;" href="javascript:;"></a>
</td>
<td>
<input type="text" onblur="if (!this.disabled) {onChangeProperty(this, false);} " onpropertychanged="if (!this.disabled) {onChangeProperty(this, false);} " onkeyup="if (!this.disabled) { onChangeProperty(this, false); }" tabindex="2" title="10" size="30" value="50" name="generalParams.poolSize"></input>
</td>
</tr>
</tbody>
</table>
</b>
</b>
I still have the problem filling in the form!
FAIL Errors encountered while filling form: form not found
# type: uncaughtError
# error: Errors encountered while filling form: form not found
Any clue more?
Thanks for your time!!!
Use this :
this.click('a.menu1itemUnSel[tabindex="4"]');
-> # = div, . = class

How to identify buttons created using a loop. Please assist

Following is the code, where the button Generate Key is getting created dynamically. For each record I get from the table, I create a button against it on the page. I want to capture which button was clicked and then use the values in that row to manipulate something.
<table border="1" width="100%" cellpadding="0" cellspacing="0">
<tr>
<th>File ID</th>
<th>Generate Key</th>
</tr>
<%
Connection con = DbConnector.getConnection();
PreparedStatement pstm = null;
String sql = "select u.uniquserid, t.filename, t.status, t.cloud, t.date_, t.report, t.FileID from transaction t join user u on u.userid = t.user order by t.date_ desc;";
pstm = con.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
while (rs.next()) { %>
<tr>
<td><%=rs.getString(7)%></td>
<% if (rs.getString(3).contains("s")) {%>
<%request.getSession().setAttribute("PassFID", rs.getString(7));%>
<td><input type="button" value='Generate Key' onclick=""></input></td>
<%} else {%>
<td></td>
<%}%>
</tr>
<%}%>
</table>
Use jquery to do your task.
Change your html code to these lines of code.
<form method="post" action="#" name="Form" id="Form" >
<input type="button" value="one" id="One"/>
<input type="button" value="two" id="Two"/>
</form>
And add these lines in your script
$('input:button').click(function() {
alert($(this).val());
var value=$(this).val();
var url='hello?good=';
url+=value;
$("#Form").attr("action",url);
$("#Form").submit();
});
You can use jquery 1.7.1 and above. Hope this helps you. Happy Coding :)

Drop-down list using mysql when query not found

I built a simple input drop-down list, using <select> which populates from a mysql database.
It works fine, but if the result from the query is not found then the drop-down list just shrinks and doesn't say anything.
I want it to say something like: "Name not found". I've searched everywhere but I can't seem to find the way.
This is my code:
<?php
if ( $myquery = $mysqli->prepare("SELECT name, idname FROM db WHERE
name LIKE '%".$name."%'") ) {
$myquery->execute();
$myquery->store_result();
$myquery->bind_result( $nompac, $idpac ) ;
}
<form name="form1" method="post" action="example.php">
<table >
<tr>
<td>Name: </td>
<td>
<select name="chosen_name">
<?php
while ( $myquery->fetch() ) {
echo "<strong><option value=".$idpac.">".$nompac."</option></strong>";
}
?>
</select>
</td>
<td><input type="submit" name="Submit" value="Go" class="button"/></td>
</tr>
</table>
</form>
I would like to add an IF statement, saying something like "if $myquery didn't find any results, then $nompac ="name not found". So I wrote this right after the WHILE statement:
if ( $nompac = "" ) {
$nompac = "Name not found";
$idpac = "0";
}
But it just ignores the code as if I didn't write anything :(
Ok I added the code as suggested by Mister Melancholy. Now looks like this:
<form name="form1" method="post" action="example.php">
<table >
<tr>
<td>Name: </td>
<td>
<select name="chosen_name">
<?php
if ( empty( $myquery ) ) {
echo "<strong><option value=''>Name not found</option></strong>";
} else {
while ( $myquery->fetch() ) {
echo "<strong><option value=".$idpac.">".$nompac."</option></strong>";
}
}
?>
</select>
</td>
<td><input type="submit" name="Submit" value="Go" class="button"/></td>
</tr>
</table>
</form>
But still doesn't work if the query doesn't find the name. What am I doing wrong? :-s
I added !empty instead of empty, and I was very happy it seemed to work but it turned out to be that even though the query founded the right name, it echoed "Name not found" every time, so back to square one :(
You need a way to tell if $myquery is empty before you begin your while loop. Something like this should do the trick:
if ( empty( $myquery ) ) {
echo "<strong><option value=''>Name not found</option></strong>";
} else {
while ( $myquery->fetch() ) {
echo "<strong><option value='".$idpac."'>".$nompac."</option></strong>";
}
}
Since I had no further answers in here, I had to ask on another forum and they came up with the solution!
Just to let you know, I used:
if ( $myquery->num_rows==0 ) {
and this works like a charm!