I have a page with 2 columns (Side and Middle)
on the side column, I have a form with a date and a button (View Summary Report).
When the user selects the date and clicks the button, it must fetch the data from the MySQL DB and display the results in the middle column.
When I do a call action to the get_summary_sheet, it displays the info on a new page. This confirms that it is working fine. BUT, I don't want to display it on a new page. I want to display it in the middle column once the user clicks the button.
I was doing research and exploring options to use the onclick function.
Here is my side column:
<div class="column side">
Select Date:
<br>
<input type="date" id="select_summarydate" name="select_summarydate" required><br>
<button onclick="myFunction()">Display Report</button>
</div>
Below is a sample of the code in the PHP file:
$yourDate = $_GET['select_summarydate'];
$sqlpole="select count(*) as totalpole from user where MeterType = 'Pole Mounted' AND Category = 'Inspection' AND Date = '".$yourDate."%'";
$resultpole=mysqli_query($con,$sqlpole);
$datapole=mysqli_fetch_assoc($resultpole);
I need to call the results to the middle column and display it in the table:
<div class="column middle">
* display results of function in php file
</div>
Below is a snippet of the JS code:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script language="javascript">
function myFunction() {
// function below will run get_summary_sheet and should display in middle column
$.ajax({
type: "GET",
url: "get_summary_sheet.php" ,
???????,
???????
});
</script>
What code must go into the Javascript function?
function myFunction() {
var select_summarydate = $('#select_summarydate').val()
$.ajax({
type: "GET",
url: "get_summary_sheet.php" ,
data: {
select_summarydate : select_summarydate
},
success: function(resp){
$('.middle').html(resp)
}
});
}
this is a complete ajax function with sending data and displaying the fetched data in html
your php code will look like below
$yourDate = $_GET['select_summarydate'];
$sqlpole="select count(*) as totalpole from user where MeterType = 'Pole Mounted' AND Category = 'Inspection' AND Date = '".$yourDate."%'";
$resultpole=mysqli_query($con,$sqlpole);
while ($single = $resultpole->fetch_assoc()) {
echo $single['firstcolumn'].' '.$single['secondcolumn']
.'<br>';
}
Related
Am having a issue while counting clicks for viewed numbers. Its working but when i refresh the page then also its updating the database and on click its not updating or inserting.
What i want is that when a user clicks on button, it shows the phone numbers and insert the database in increment.
Code below:
<script type='text/javascript'>
$(document).ready(function(e) {
$('#viewNumber').click(function(showNumber){
document.getElementById('showNumber').style.display = 'block';
document.getElementById('viewNumber').style.display = 'none';
<?php
$countcheck=0;
$checkcounter="SELECT * FROM seo_viewnumber_count WHERE seo_user_id='".$user_id."'";
$resultcheckcounter= mysql_query($checkcounter);
while($rowcheckcounter= mysql_fetch_array($resultcheckcounter))
{
$clickcount= $rowcheckcounter['seo_viewmob_count'] + 1;
$updatecounter="UPDATE viewnumber_count SET seo_viewmob_count='".$clickcount."' WHERE seo_user_id='".$user_id."'";
$resultupdatecounter= mysql_query($updatecounter);
$countcheck++;
}
if($countcheck==0)
{
$insertcounter="INSERT INTO viewnumber_count (seo_user_id, seo_viewmob_count) VALUES ('".$user_id."', '1')";
$resultinsertcounter= mysql_query($insertcounter);
}
?>
});
});
</script>
<button name="viewnumber" id="viewNumber" onclick="showNumber()" class="btn">View Number</button>
<ul id="showNumber" style="display:none;">
<li> 123456</li>
<li> 88888</li>
</ul>
Create a different PHP file for your following code:
<?php
$countcheck=0;
$checkcounter="SELECT * FROM seo_viewnumber_count WHERE seo_user_id='".$user_id."'";
$resultcheckcounter= mysql_query($checkcounter);
while($rowcheckcounter= mysql_fetch_array($resultcheckcounter))
{
$clickcount= $rowcheckcounter['seo_viewmob_count'] + 1;
$updatecounter="UPDATE viewnumber_count SET seo_viewmob_count='".$clickcount."' WHERE seo_user_id='".$user_id."'";
$resultupdatecounter= mysql_query($updatecounter);
$countcheck++;
}
if($countcheck==0)
{
$insertcounter="INSERT INTO viewnumber_count (seo_user_id, seo_viewmob_count) VALUES ('".$user_id."', '1')";
$resultinsertcounter= mysql_query($insertcounter);
}
Then, call that PHP file by AJAX from your client side code when any click will happen by user on button.
Sample jQuery code for making AJAX call:
$.ajax({
method: "GET",
url: "server.php",
})
.done(function( msg ) {
alert( "Counter incremented: ");
});
I am new to jquery and am trying to make a live search from my existing search page where you have to press enter.
This is the code I have made so far.
$( document ).ready(function() {
$('#searchhh').on("input", function() {
var searchquery = this.value;
$( "#searchform" ).submit();
});
});
This gets the input of the form and searches it every key stoke. The problem is the text that the user types resets every time the form submits. I tried to post the search value as a get variable and display it as the search bars value and auto focus into the the search bar every time the page reloads, this puts the typing bar at the beginning of the form before what the user has typed.
I feel like I am approaching this the wrong way please help. :)
You need to post your form via ajax. Here's a simple fiddle to demonstrate this:
http://jsfiddle.net/e76d09vw/
HTML:
<form id="searchform" method="post" action="some_url_here">
<input type="text" name="search" placeholder="Search..." />
</form>
Results:<br>
<div id="results"></div>
JS:
$('#searchform').on("keyup", "input", function() {
var form_data = $("#searchform").serialize();
var form_url = $("#searchform").attr("action");
var form_method = $("#searchform").attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnOutput){
// Your search results are outputted here
$("#results").html(returnOutput);
}
});
});
I have a form on my website which passes its values to some JavaScript which then passes the information to a PHP page to update the database. When the form is submitted all of the values are added to the database except the two fields which are text areas.
If I remove the JavaScript and add a simple form action to directly pass the variables to the PHP page then all of the information is added to the database including the two text area fields and so it seems the problem must be in theform and the JavaScript, otherwise the two fields wouldn't get added to the database regardless.
Below is my form and my JavaScript. ( Top keep it simple I have only included the two elements of the form which have the problems as it is a long form, if this is the wrong approach then please let me know.)
<form action="" method="post" class="save">
<label class="col-sm-3 control-label">Notes</label>
<textarea name="notes" rows="10" class="form-control"></textarea>
<input type="submit" name="submit" class="save" value="Save This Job" id="blue"/>
</form>
And now the JavaScript
$(document).ready(function(){
$('form.save').submit(function () {
var ref_number = $(this).find("[name='ref_number']").val();
var job_title = $(this).find("[name='job_title']").val();
var start_date = $(this).find("[name='start_date']").val();
var closing_date = $(this).find("[name='closing_date']").val();
var category = $(this).find("[name='category']").val();
var location = $(this).find("[name='location']").val();
var salary = $(this).find("[name='salary']").val();
var client = $(this).find("[name='client']").val();
var job_description = $(this).find("[name='job_description']").val();
var license = $(this).find("[name='license']").val();
var notes = $(this).find("[name='notes']").val();
// ...
$.ajax({
type: "POST",
url: "save.php",
data: {
ref_number : ref_number,
job_title : job_title,
start_date : start_date,
closing_date : closing_date,
category : category,
location : location,
salary : salary,
client : client,
job_description : job_description,
license : license,
notes : notes,
},
success: function(){
new PNotify({
title: 'Job Posted',
text: '
type: 'success',
shadow: true
});
}
});
this.reset();
return false;
});
});
So here is a simplified version of the PHP which I keep changing, as I said above if I send the variables direct to the PHP page all of the information is added to the mysql database, no problems, but when using the JavaScript the job description and notes fields do not get added.
$ref_number = $_POST['ref_number'];
$job_title = $_POST['job_title'];
$start_date = $_POST['start_date'];
$closing_date = $_POST['closing_date'];
$category = $_POST['category'];
$location = $_POST['location'];
$salary = $_POST['salary'];
$client = $_POST['client'];
$job_description = $_POST['job_description'];
$license = $_POST['license'];
$posted_by = $_POST['posted_by'];
$site_id = $_POST['site_id'];
$notes = $_POST['notes'];
mysql_query("INSERT INTO joborders
(ref_number, job_title, start_date, closing_date, category, location, salary, client_name, job_description, license_required, site_id, posted_by, status, notes, posted_date) VALUES('$ref_number', '$job_title', '$start_date', '$closing_date', '$category', '$location', '$salary', '$client', '$job_description', '$license', '$site_id', '$posted_by', 'open', '$notes', NOW()) ")
or die(mysql_error());
So i found the problem, at the bottom of the page was this piece of code, which i hadn't noticed before even though i have looked at it a dozen times. As soon as i removed it, it worked, so now i just need to work out if i can incorporate it on to the existing code so i can still use the tnymce
tinymce.init({
selector: "textarea"
});
OK so the problem turned out to be because there was this piece of code on the page
tinymce.init({
selector: "textarea"
});
So i changed this to reference the class of the text are in the form, like this.
tinymce.init({
selector: "textarea.form-control",
});
And now all of the form fields post to the database.
Thanks for all your suggestions and comments, much appreciated.
I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.
However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.
I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.
Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().
What I would like to be able to do is then loop over the notes and render a table with several cells and rows.
Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.
I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
alert(data)
json = jQuery.parseJSON(data);
},
error : function() {
alert("Error");
}
});
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</select><input type="submit" name="sub" value="Choose Subject"/>
<BR />
</FORM>
This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:
<table id="books">
<tr>
<th>Chapter</th>
<th>Summary</th>
</tr>
</table>
You could do something like:
$(function(){
$('#choose_subject').submit(function () {
var subject_id = $(this).val();
$.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
console.log(data);
$.each(data.chapters, function (index, chapter) {
$('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
})
});
return false;
})
})
This supposes JSON like:
{
"notes": [
"Note 1",
"Note 2"
],
"chapters": [
{
"title": "First chapter",
"summary": "Some content"
},
{
"title": "Second chapter",
"summary": "More content"
}
]
}
Other notes:
If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} ) works the same and it's easier to read.
You can use $.get instead of $.json if you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSON instead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
It's usually more convenient to use console.log rather than alert when you're testing. Actually, it's usually a bad idea in general to ever use alert.
I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.
var subject_id = $(this).val();
$.ajax('subject_ajax', {
type: 'get',
data: { subject_id: subject_id },
dataType: 'html',
success : function(html) {
// Insert the html into the page here using ".html(html)"
// or a similar method.
},
error: function() {
alert("Error");
}
});
When calling .ajax():
The "type" setting defaults to "get", but I prefer to explicitly set it.
Use the "data" setting for the ajax call to specify the URL parameter.
Always specify the "dataType" setting.
I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.
$(document).ready(function(){
$('#subject_id').change(function() {
$(this.form).submit();
});
$('#choose_subject').submit(function(event) {
event.preventDefault();
var subject_id = $('#subject_id').val();
if (subject_id) {
$.ajax(...);
}
});
});
This way your submit button should work in case it is clicked.
There are a few things you need to look at:
1) Is your SimpleTemplate library included?
2) Have you compiled your template via compileTemplate()?
Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.
I'm not sure that you want to update the same element that you're defining your template in.
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
var template_data = JSON.parse(data);
var template = $('#subject_id').toString(); // reference to your template
var precompiledTemplate = compileTemplate(template);
var result = precompiledTemplate(template_data);
$('#subject_id').append(result);
},
error : function() {
alert("Error");
}
});
})
})
You might also try moving your template out of the element you're trying to update like this:
<script type="text/template" id="subject-select-template">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>
Then just create a blank select element like so:
<select id="select_id"></select>
Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)
Also, check out this demo example if you haven't yet:
https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html
I have the following html code:
<div>
<form id="ChartsForm">
<div id="optionsheader">
<p>Choose your page:</p>
<div id="dateoptions">
<p>Until date: <input type="date" name="until_date" value="Until date"></p>
<p>Since date: <input type="date" name="since_date" value="Since date"></p>
</div>
</div>
<select name="accmenu" id="accmenu" style="width:300px; float:left; clear:both;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<div class="insightsoptions">
<p>Choose your insights:</p>
<input id="newLikes" class="insightsbuttons" type="submit" name="submit" value="Daily new likes">
<input id="unlikes" class="insightsbuttons" type="submit" name="submit" value="Daily unlikes">
</div>
<div class="insightsgraphs">
<div id="dailyNewLikes"></div>
<div id="dailyUnlikes"></div>
</div>
</form>
</div>
which has a form with the id=ChartForm that contain two date inputs until_date and since_date, one select accmenu and two submit inputs with the values Daily new likes and Daily unlikes. I use the following Jquery function:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").attr("class","insightsbuttons");
});
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setSize(960, 320);
myChart.setAxisNameX('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setAxisNameY('');
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
$("#dailyUnlikes").html(response);
}});
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
});
});
for the application flow in the following manner: every time I click on one of the input submit buttons the script will make only one Ajax GET request to a specific php file that send me back a response with which I create a Chart in a hidden div with the id=dailyNewLikes or id=dailyUnlikes by case (for testing purposes I work for the moment only on the first button). The button it will change his background color into green and the div it will be shown. I use $("#newLikes").on('click', function(){ for change back and forth the background color and the display time of the div. (from green and display:block to red and display:none, you get the point I hope :D). Also I use $('#accmenu').change(function() { to change all buttons to red and hide the respective div in case an option from the select is changed. My problem is that after I refresh the page (Ctrl+R) choose since and until date, click on the first button (it change to green and the div is shown, also the toggle is working fine) and then click on the second button which works fine on the first click (is becoming green and div is shown) but on the second click I have an issue: the script is making another Ajax GET request (a wrong URL one) and the page is refreshed. Ex. of a good reguest URL:
http://localhost/smd/unlikes.php?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701
and an ex. of a wrong request URL:
http://localhost/smd/?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701&submit=Daily+unlikes#_=_
Like it can be seen (it doesn't need in the first to make this extra request) the php file is not present and also a new submit parameters is added. This also happen if I change from the select with another option. What am I do wrong? I really need to know, not just to have my code "fixed". It bugging me for a little while. Any feedback is more than welcomed. P.S. Also, how can I start the .one function only if both date inputs has been choosen? Something like how could help me?
var until = $('#dateoptions input[name="until_date"]').val();
var since = $('#dateoptions input[name="since_date"]').val();
if (until == "" || since == "") {
alert('Until date or Since date missing!');
return;
}
it will work that way? Sorry for the long question...
i think you should make your question a little shorter and just point what you need and what errors are you getting ..anyways...going through your code i see you have two click event for same button at the end for $("#unlikes").one and $("#unlikes").on(..and no return false in other function.
try adding return false
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
my guess is that , since you have two click event..when it gets clicked ..these event will fire and since you are missing return false in second click function...the form gets submitted hence refreshing the form.
however its better if put your codes in single click function than creating two seperate click event.