How To Display a random row from database on button click? - javascript

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

Related

How to refresh specific div using Javascript/Jquery with the variables on it

I have a variable $salary which is dynamic. How can I refresh specific div every 5seconds.
index.html
<html>
<body>
<img src="<?php echo $filename.'.jpg'; ?>" />
<p id="salary"><?php echo $salary; ?></p>
</body>
</html>
Is there any javascript/jquery way to refresh #salary only. Please help..
You can execute an ajax call:
function ajaxCall() {
$.ajax({
method: 'POST',
url: 'path/to/asyncHalndler.php',
data: { ... },
success: function (data) {
if (data) {
$('#salary').html(data);
}
}
});
}
// Execute ajax call every 5 seconds
setInterval(function() {
ajaxCall();
},5000);
var salary = document.getElementById('salary');
Now, the value of your variable salary will be the DOM node where you would like to change the value. When you get new data, you can refresh text inside your p tag with salary id by adding salary.innerText = yourNewValue;
This is pure JavaScript way of updating that element with id.
It's better to use ajax way. But if u are looking for a very simple solution then jQuery .load will be the best
setInterval($("#salary").load("<url to get the value>"), 1000);
You will need an jquery ajax call for that.
first you should create php file get_salary.php where you send id from jquery ajax if you want to update the salary for unique id:
in get_salary.php you need to get salary from database so the code in this php file will be like that
$id = $_POST['ID']
$query = mysql_query("SELECT * FROM sallaries WHERE id='$id'") or die("Can't connect");
$fetch = mysql_fetch_array($query)
$salary = $fetch['salary']
echo $salary
after that you will need javascript file(e.g script.js) from where you will send the request and id to the get_salary.php and grab the data from it, after that you will be able to update salary in html, so code in javascript file will be like that:
function updateSalary(){}
var id=25;
$.ajax({
url: "get_salary.php",
type: 'POST',
//sending id
data:'id='+id,
success: function(result){
//updating html
$("#salary").html(result);
}
});
}
//setting interval to update in every second
setInterval(updateSalary, 1000)
so it will update your salary in the div

Execute PHP code on form submit without text input

I just want to know if it is possible to execute a PHP post request with ajax by click on a form submit button that does not have any text input. Say i have a form
<form action="connecting.php" id="connect" method="post" enctype="multipart/form-data">
<input type="submit" name="userconnect" id="userconnect" value="connect">
</form>
And i want to execute this block of php code on submit button
connecting.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['userconnect']))
{
$my_id = htmlspecialchars($_SESSION['log_id'], ENT_QUOTES, 'UTF-8');
$user_id = (int) htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8');
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$user_id') OR (user_two = '$my_id' AND user_one = '$user_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
echo "<script>alert('You are already connected to this user')</script>";
}
else
{
$usql = $db->prepare("INSERT INTO connect (user_one, user_two, hash) VALUES (:my_id, :user_id, :rand_num)");
$usql->bindValue(':my_id', $my_id, SQLITE3_INTEGER);
$usql->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
$usql->bindValue(':rand_num', $rand_num, SQLITE3_TEXT);
$uret = $usql->execute();
if (!$uret)
{
echo "Error connecting";
}
else
{
echo "Connection Sucessful";
}
}
}
This is the ajax request i am trying to use
$("#connect").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connecting.php",
data: $(this).serializeArray(), //the data is an issue cause of no text input in for
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
}
});
});
This doesn't work because there is no data in the form for ajax to send but all data are in the PHP file. How do i execute the php file with ajax. Is there any way?
You dont have to send a POST request to a PHP script in order for it to execute. You can send a normal GET to a URL that executes a PHP script and send you back the JSON data you are looking for. That way, you dont have to send data with the post request and you can still run your PHP script.
Edit*
Another thing you can do is add a hidden ID field or some random text and send that with the POST as data. You dont have to do anything with it, it could just be a time stamp, but it will send the POST request. This is of course overhead and not my kind of programming, but an option nonetheless.
Yes it is possible.... you need to harness a click event...
for example if you had a div element like so:
<div id='mybutton'>click me</div>
then you could use code like this to do literally whatever you want when the button is clicked.:
$('#mybutton').on('click',function(){
$.post...
});
BONUS INFO:
You could also hijack the form submit event like so:
$('#form#myform').on('submit',function(e){
e.preventDefault(); //stop before page is reloaded with post headers
$.post...
});
You don't actually need a form event though, you can just $.get to a php url and return the html or json it generates. just check out the jquery documentation on $.get()

Is it possible to load content of page without Refreshing the whole page

Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );

How do i send parameter in ajax function call in jquery

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

Create a loop to call php function and echo from that function on same html page in javascript

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).

Categories