My scenario looks like this, I'm showing database paginated grid on the screen.
I want add a button to download CSV spreadsheet .
so I coded something like this:
$(function(){
var file_complete = false;
var final_sql = $('.initiate_download').val();
var orderby = $('#search_submit').data('orderby');
var $posturl = $url + "index.php/Spawner/launch_spawner";
$('#downloadModal').modal('hide');
$('.initiate_download').on("click", function(e) {
e.preventDefault();
$('#pleaseWait').html($html);
setTimeout(function() {
$.ajax({ // initiate download
url: $posturl,
type: "POST",
data: {
final_sql: final_sql,
orderby: orderby,
report: $report
},
success: function(data) {
var download_id = data;
// console.log(download_id);
check_download_status(download_id);
}
})
}, 2000);
})
});
<div class="row top-buffer">
<button id="search_submit" class="btn btn-primary initiate_download" type="submit" value="<?php echo $sql; ?>" data-orderby="<?php echo $orderby;?>" name="final_sql_lic" >Download List</button>
<span id="pleaseWait"> </span>
</div>
it works fine, but the problem is that you can view SQL with view page option, is there a way around it ?
What most people do is they don't embed the SQL on page, but instead expose URLs that handle the SQL stuff behind the scenes.
In your example, you might create a page like this:
http://website.com/api/csv?select=col1,col2,col3&orderBy=someColumn&where=someCondition
Then your php will take those parameters and generate the sql based off of those and run the query. Make sure you securely handle the input to avoid SQL injection (See http://bobby-tables.com/php.html).
The problem with your current scenario is that someone viewing your source will plainly see that you're passing SQL directly to your server, meaning they can generate their own SQL like: DROP TABLE table1, table2; or worse.
Related
I'm a beginner, and I want to know how to display a random row from database On BootstrapButton Click.
here's my code:
<h3 id="myHeader">Press the button below to display a name</h3>
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML =<?php $row["Name"] ?>;
}
</script>
<button type="button" class="btn btn-primary" onclick="displayResult()">Another One</button>
You'll have to create a PHP page which fetches a random item from a table and outputs the result
SELECT * FROM table ORDER BY RAND() LIMIT 1
Then, on button click, you want to create an Ajax request to the page and display the results. I would use JQuery for this
$.ajax({
url: "random.php",
success: function(response){
$('#myHeader').html(response);
}
})
You need to do a php script and fetch that row , and use ajax to get that response
$.ajax({
url: "path_to_your_file",
success: //your_Logic
})
Now you have send a request after opening your php script and wait for the response.
var your_request= new XMLHttpRequest();
your_request.open("GET","your_file.php="data_var_name_in_php="+data ...);
your_request.send();
your_request.onreadystatechange = function result() {
document.getElementById("myHeader").innerHTML = your_request.responseText;
}
I advise you to test your php script first to check what you can get as a response text on your local server.
See Ajax Documentation for more information : http://api.jquery.com/jquery.ajax/
You can connect to your database MySQL via JS using this library :
http://www.mysqljs.com/
and this is the code to connect :
MySql.Execute(
"mysql.yourhost.com",
"username",
"password",
"database",
"select * from Users",
function (data) {
console.log(data)
});
So basically this little box section displays like recent uploads and a little status that is red for pending and green for uploaded. Right now I made it so when I click on the first red box it will update all the red ticks to green for completed.
How can I make it so that when I click on a single red box, it will only update that tables row to green?
Each upload has an id automatically generated in the Database.
Here is a picture of the box: https://i.gyazo.com/af895f24a2f002df588ca1863f7216fa.png
I have to manually edit the table status to green in order for it to change or I click on 1 and it updates all. I want it to only be on the specific one clicked like displayed in the photo.
Here is another example of it but using a .gif for better demonstration: https://i.gyazo.com/3e974f1a536ba37e71fcb60fc7f19c54.gif
Javascript:
$("#updateStatus").click(function(){
window.location.href = 'connections/updateStatus.php';
});
PHP:
public function redtoGreen(){
$query2 = "UPDATE uploads SET status = 'green'";
$this->conn->query($query2);
header('Location: '.'../index.php');
}
You can achieve through AJAX, sending the ID or wherever you identify your DIV, the code will be something like this:
$("#updateStatus").click(function(){
var id = $(this).attr('id');
$.ajax({
method: 'GET',
url: "connections/updateStatus.php?id="+id
});
});
and at your server side
public function redtoGreen(){
$id = $_GET['id'];
$query2 = "UPDATE uploads SET status = 'green'";
$this->conn->query($query2);
header('Location: '.'../index.php');
}
to change of color, take a look https://jsfiddle.net/k0ye49oh/
You should use AJAX for that (although it works with redirecting back and forth too...).
Do something like this instead:
$("#updateStatus").click(function(){
$.ajax({
url: "connections/updateStatus.php"
});
});
For it to update only a specific row, you have to pass on the ID of the row. Your update query will just update all rows in the table to "green". You can pass the ID on as a parameter and read it in PHP with $id = $_POST["id"] if you posted it by:
$.ajax({url: "connections/updateStatus.php", method: "POST", data: { id: 4 }});
You can read and update it in PHP like:
public function redtoGreen(){
$id = intval($_POST["id"]);
$query2 = "UPDATE uploads SET status = 'green' WHERE id = $id";
$this->conn->query($query2);
}
Another remark: consider using prepared statements for this. SQL queries like this are not good style. You'd rather want something like:
public function redtoGreen(){
$id = $_POST["id"];
$stmt = $db->prepare ("UPDATE uploads SET status = 'green' WHERE id = ?");
$stmt->execute($id);
}
You can also build on the ajax query to change the row color without reloading, doing something like:
$.ajax({
url: "connections/updateStatus.php",
method: "POST",
data: { id: rowno },
success: function (result) {
$("#myrow-" + rowno).css('background-color', 'green');
}
});
However, seeing that you only have one button (#updateStatus) to update ALL rows I think you have several issues with your approach here. If you have the buttons on each row, you have conflicting IDs.
To get both the rowno and the correct button references, you can define your buttons like this:
<button class="updateStatus" data-rowno="1"></button>
When building the table, you will have to put the row number where the 1 is.
Then you can do the javascript part like this:
$(document).ready(function () {
$(".updateStatus").click(function () {
var el = $(this);
var rowno = el.data("rowno");
$.ajax({
url: "connections/updateStatus.php",
method: "POST",
data: { id: rowno },
success: function (result) {
$(el).parent().css('background-color', 'green');
}
});
});
});
Tested and works with HTML like
<table>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="1">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="2">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="3">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="4">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="5">Update</button></td></tr>
</table>
You need to update your SQL query to something like below. The current query will set every row for status to 'green' in the uploads table.
UPDATE uploads SET status = 'green' WHERE somecolumn = somevalue
That somevalue needs to be sent from your javascript function call, something like
updatestatus.php?var=somevalue
and use the var as $_GET['var'] on the php page.
Alright, so after some thinking I figured this out.
I thought about changing the html to have divs labeled like this: Hello1 and Hello2. Here is some HTML:
<html>
<div id = "Hello1">
</div>
<div id = "Hello2">
</div>
</html>
You would put the content for each clickable box that you have.
I recommend using Jose Rojas's Javascript.
Here is some PHP to update them accordingly.
With my example, you would just using the $_GET global value instead of a $_POST
<?php
$div = $_GET['div'];
redToGreen($div);
function redToGreen($div) {
$query = "UPDATE uploads SET status = 'green' WHERE div = '{$div}'";
try {
$stmt = $this->conn->prepare($query);
$stmt->execute();
header('Location: ../index.php');
} catch (PDOException $e) {
header('Location: ../pages-500.html');
}
}
?>
If you have any questions, feel free to comment, and I will respond.
I currently have a webpage that works great. I select my load number and a ajax query gets the information and puts the results in textboxs. The page is split, one part displays information, but when "print" is selected, it formats the results to print a bubble sheet.
Here is the problem. Instead of displaying the "On Screen" results in textboxs, I would rather just display as normal text.
The active page is located at this address
The retrieval code is quite long, here is a sample.
<script>
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#loads").change(function(){ /* TRIGGER THIS WHEN USER HAS SELECTED DATA FROM THE SELECT FIELD */
var loadnumber = $(this).val(); /* STORE THE SELECTED LOAD NUMBER TO THIS VARIABLE */
$.ajax({ /* START AJAX */
type: "POST", /* METHOD TO USE TO PASS THE DATA */
url: "actionprt.php", /* THE FILE WHERE WE WILL PASS THE DATA */
data: {"loadnumber": loadnumber}, /* THE DATA WE WILL PASS TO action.php */
dataType: 'json', /* DATA TYPE THAT WILL BE RETURNED FROM action.php */
success: function(result){
/* PUT CORRESPONDING RETURNED DATA FROM action.php TO THESE TEXTBOXES */
for (i = 1; i < 14; i++) {
$("#prtDescription" + i).val("");
$("#prtMethod" + i).val("");
$("#prtPONumber" + i).val("");
$("#prtGallons" + i).val("");
$("#prtAmount" + i).val("");
}
$("#NumberStops").val(result.NumberStops);
$("#ShipperName").val(result.CustomerName);
$("#prtship").val(result.CustomerName);
$("#ShipperAddr1").val(result.CustomerAddress);
$("#ShipperAddr2").val(result.CustomerAddress2);
$("#ShipperCity").val(result.CustomerCity);
$("#prtshipcity").val(result.CustomerCity);
$("#ShipperState").val(result.CustomerState);
$("#prtshipstate").val(result.CustomerState);
$Phone = result.CustomerPhone
$Phone = '(' + $Phone.substring(0,3) + ') ' + $Phone.substring(3,6) + '-' + $Phone.substring(6,10)
$("#ShipperPhone").val(result.CustomerPhone);
$("#ShipperContact").val(result.CustomerContact);
$("#PickupDate").val(result.PickupDate);
$("#prtdate").val(result.PickupDate);
$("#PickupTime").val(result.PickupTime);
$("#CustomerPO").val(result.CustomerPO);
$("#Weight").val(result.Weight);
$("#prtweight").val(result.Weight);
$("#Pieces").val(result.Pieces);
$("#prtpieces").val(result.Pieces);
$("#BLNumber").val(result.BLNumber);
$("#prtbol").val(result.BLNumber);
$("#TrailerNumber").val(result.TrailerNumber);
$("#prttrailer").val(result.TrailerNumber);
...
I tried document.write() but that cleared the page which is not what I am looking for. I want to keep my images and combobox selection box on the page so I can select other loads when needed rather then just one at a time.
Please help.... If you require more information to answer the question, please ask and I will post.
Why not just make a new div after your load selection and simply append all those results into it?
There are different options to use Ajax as per your Requirement. You can replace the Entire div with the new Data or with the Entire HTML or you can change the selected part alone. It is up-to you who have to choose the suitable method which will be easy for you.
These are the methods available:
Method 1:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(data) {
handleData(data);
}
});
}
This above method will replace the Ajax success with the data that is available after your process is completed.
Method 2:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(html) {
handleData(html);
}
});
}
The above function will replace the entire success div with the new HTML part.
Now i will illustrate it with a simple example of how to replace the div using PHP and HTML using AJAX.
Scenario: User Has to select the city and the City Details will load up in Ajax.
HTML:
<select name="city" onchange="selectcity(this.value)">
<option value="">Please Select</option>
<option value="1">USA</option>
<option value="2">Europe</option>
</select>
<div id="ajax_output">
</div>
While selecting the city it will load up the function by using onchange attribute in jQuery and the Ajax will be passed.
JS:
function selectcity(a) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&city="+a,
success:function(html) {
$('#ajax_output').html(html);
}
});
}
In the JS am getting the selected value using a since i have passed a parameter to the function and passing it to the Ajax Page.
Ajax Page:
Note: Ensure that if you are going to display the information form the DB you have to connect the DB file to the Ajax page.
<?php
$city_id = $_POST['city']; // Jquery Data that i am retriving on Ajax Page
$select="SELECT * FROM TABLENAME WHERE `city_id`='".$city_id."'";
$query = $con->query($select);
$count = $query->num_rows;
if($count==0)
{
echo 'No Data Found';
}
else
{
while($fetch = $query->fetch_assoc())
{
?>
<div class="col-sm-6">
<label>City</label>
<span><?php echo $fetch['city_name']; ?></span>
</div>
<div class="col-sm-6">
<label>Place</label>
<span><?php echo $fetch['place']; ?></span>
</div>
<?php
}
}
?>
Now in my example i am going to replace the #ajax_output div with the content that is going to come from the Ajax page.
As per the request made in the question i hope so this would be the easiest method so that PHP will execute faster when compared to the JS and the Errors will also be minimal when you use this method.
Hope so my explanations would be clear for you and if you face any hindrance in development let me share thoughts and i will provide you with a solution.
Happy Coding :)
I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});
I am trying to create a simple webapp sort of thing that will send push notifications to my clients on button click. Here is a sample page that i have created
I have a file named as sendPush.php
On button click i want to send a push notification which will be echoed as
Notifications sent:
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
I want to send notifis to all 147 users. Now here is my php code for button click
<script type="text/javascript">
function sendNotif()
{
alert('ok');
}
</script>
<div class="content">
<input type="button" value="Click to Send" onClick="sendNotif();">
<br />
<br />
<label for="push">Notifications sent: </label>
</div>
The problem here i am facing is, i have php function in same app named as sendNotification() that will send notification and echo the result. But I am not sure how can i make a loop of this php function in javascript inside javascript function
function sendNotif()
{
// LOOP HERE
}
If $clients is the list of my clients, how can i send notif to all in a loop using php function in same page as sendNotification($client)
MOdified
<script type="text/javascript">
var lastIdCount = 0;
function sendNotif()
{
var clients = "<?php echo $clients; ?>";
var getPath = "push.php?clientId=".concat(clients['lastIdCount']);
$.ajax({
type: "POST",
url: getPath,
task: "save",
data: {
ajax: "true",
},
dataType : 'json'
}).done(function( msg )
{
alert('ok');
if( msg.status=="1")
{
alert('okasdf');
lastIdCount++;
sendNotif();
}
else
{
alert("Error : "+msg.error);
}
});
}
</script>
In push.php
sample
$resp = array();
$resp['error'] = 'Invalid Request';
$resp['status'] = '0';
$resp['data'] = '0';
You can try first to get all clients you want to send notification and use them ID's for setInterval or setTimeout functions which would repeat your queries. Probably you should
get_clients.php
<?php
$clients_array = array(1,2,6,15,29); /// let's say ID's you got from SQL or w/e you need.
echo json_encode($clients_array); // [1,2,6,15,29]
?>
send_for_client.php
<?php
$id = isset($_POST['id'])?$_POST['id']:false;
if($id){
// do some code you need
echo "Notification sent for id: ".$id;
}
?>
index.html
...
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(window).load(function(){
$("#send").click(function(){
$.post('get_clients.php',{},function(cid){
obj = JSON.parse(cid);
var cids = obj;
/// cids is array of clients. so, you can do like:
var i = 0;
var interval = setInterval(function(){
if(cids.length > i){
$.post('send_for_client.php',{id:cids[i]},function(resp){
$("#result").append(resp+"<br />");
i++;
});
} else {
clearInterval(interval);
}
},100);
});
});
});
</script>
</head>
<body>
<input id="send" type="submit" name="button" value="Send notifications" />
<div id="result">
</div>
</body>
...
I'm not tested this think, however it should work or simply show idea how you could try to find a solution for your problem. Have in mind this code can have mistakes so.. don't be lazy to check them out, not even do copy/paste :)
I hope it helped even a bit.
javascript and php are run in 2 different places. Your javascript runs in a browser while your php runs on the server. You cant really mix those two.
The way you probably want to do this is, on button click capture the click with javascript and send ajax request to your php script sitting on the server. Than have the php perform push notifications. Once php script is done, return result back to javascript to show it to the user.
You should also use javascript library like jquery which makes things much easier (especially the ajax call).