im try to store random number after click on button and store in database table field name 'f_id'. when i click on button, the new random number is generated but its not store in database table field name 'f_id'.. my code is..
my jquery code ////
<script language="javascript" type="text/javascript">
jQuery(document).ready(function($){
$(".random").click(function(){
var number =Math.floor(Math.random() * 100000);
console.log(number);
});
});
</script>
and my html code ////
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<a class="random action btn btn-success btn-sm" href="#" >random number</a>
</body>
</html>
plzz tell me i have created database already but not store this value number on database table..
php code...
<?php
function mytable($number){
$result = mysqli_query( $this->conn,"INSERT INTO school(f_id) VALUES ('$number')");
return $result;
}
?>
mytable($number);
how to connect jquery var number in php code mytable under variable number... plzz solved
You need to call your PHP function using ajax (https://api.jquery.com/jquery.post/) and send your random number.
You can then access it via $_POST['number'] on the server side.
$.post( "mytable.php", function({number: number}) {
});
Php:
function mytable($number)
$result = mysqli_query( $this->conn,"INSERT INTO school(f_id) VALUES ('$number')");
return $result;
}
mytable($_POST['number']);
You need to call your php backend script. This could be done like this:
<script language="javascript" type="text/javascript">
jQuery(document).ready(function($){
$(".random").click(function(){
var number =Math.floor(Math.random() * 100000);
console.log(number);
window.location.href='http://path.to/your_script.php?rnd=' + number
});
});
</script>
And in your_script.php:
<?php
function mytable($number){
$number=intval($number);
$result = mysqli_query( $this->conn,"INSERT INTO school(f_id) VALUES ('$number')");
return $result;
}
if(mytable($_GET['rnd'])) {
echo "It works";
}
else echo "Something went wrong";
I but putting a random number as id is "probably not" recommended...
Related
I want to write a web page and use jquery to GET a small amount of data from php at the server, but in the same file, when i click a button. I want to send ?nm=bill and answer with 'bob'. i press the button but it doesn't seem to arrive at the server. I get the contents of the file i am sending the query to. I clear the browser, firefox, history before i press the button. Here is the code.
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("a_foo.php?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET"){
var_dump($_SERVER["REQUEST_METHOD"]);
if ($_SERVER['QUERY_STRING']) {
echo "bob";
}
}
?>
</body>
</html>
but in the same file
So all of the code shown is in one file? If that's the case then any request to that file is going to receive the entire response.
I get the contents of the file i am sending the query to.
That's expected behavior. The very first thing this file does is emit all of the HTML at the start. Then it executes some PHP and conditionally emits a single value at the end.
Putting these things into separate files would be the ideal approach. One file is the UI, the other file is the service that handles the AJAX request and returns just the expected data.
But if you really want them to be in the same file then you'd need to conditionally return all of that HTML. Since the only difference between the requests at this time is whether or not a query string is present then your whole PHP file would look something like:
<?php
if ($_SERVER['QUERY_STRING']) {
echo "bob";
} else {
/>
<!-- ALL of your other HTML goes here -->
<?php
}
?>
As you can probably imagine, this structure gets pretty ugly and difficult to maintain pretty fast. Which is why the preferred approach is to separate these things into their own files. Each PHP file would do just the one thing it needs to do, rather than having one big PHP file which conditionally does multiple different things.
The current target of request is a_foo.php i fix it and show bob if the get nm is bill else show html
<?php
$_nm = $_GET["nm"];
if($_nm == "bill"){
echo "bob";
}
else
{
?>
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
</body>
</html>
<?php
}
?>
I have two files, one for HTML and jQuery and other is for PHP.
I am getting response from PHP page, but I am not able to display in a HTML text box.
Here is my code:
<script type="text/javascript">
function fill_amt()
{
var sname=$("#sname").val();
$.post("try_insert.php",{sname:sname,cmd2:"fill_amt"},function(data){
$("#tot_amt").html(data);
});
}
</script>
Here is my HTML code:
<input type="text" id="tot_amt" name="tot_amt">
Here is my PHP code
$sql = mysql_query("select total_fee from admission where first_name='".$sname."'")or die(mysql_query());
$val=mysql_fetch_row($sql);
$tot=$val;
echo json_encode($tot);
Use:
$("#tot_amt").val(data);
instead of
$("#tot_amt").html(data);
Also format your json data correctly.
Your JS code should be
<script type="text/javascript">
function fill_amt()
{
var sname=$("#sname").val();
$.post("try_insert.php",{sname:sname,cmd2:"fill_amt"},function(data){
var json=JSON.parse(data); // parsing data form JSON string and convert it into object
$("#tot_amt").val(json.total);
});
}
</script>
PHP code should be
$sql = mysql_query("select total_fee from admission where first_name='".$sname."'")or die(mysql_query());
$val=mysql_fetch_assoc($sql);
$tot=$val['total'];
echo json_encode(array("total"=>$tot)); // give response as json string
I'm looking for the easiest way to add a simple like button to my site. Basically, a button that, when clicked - changes to a new graphic (letting you know you clicked it), can't be clicked again, and sends to a php script so the server knows what you liked.
I thought a good technique might be putting a like button inside an iframe so you can click it and the php page could just echo 'thanks for liking this' - but the problem is the iframe has to have a source. I don't want a ton of external files loading into each page. Is there any way I could just have an iframe tag and put HTML inside it without it being external?
Hopefully this makes sense. I do not know your server structure, so its hard for me to build a complete example but this should get you off your feet!
File: Index.php
// query the database and check to see if there is a record for this content piece and ip address
// select count() from statistics where contentId='1' and ip='0.0.0.0' limit 1;
$contentLiked = false;
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="site.js"></script>
</head>
<body>
<? if(!$contentLiked): ?>
like
<? else: ?>
unlike
<? endif ?>
</body>
</html>
File: site.js
$(document).ready(function() {
$('.likeButton').click(function() {
var contentId = $(this).attr('rel');
var link = this;
if(!$(link).hasClass('liked')) {
$.post("like.php", { Id: contentId }).done(function(data) {
if(data) {
$(link).addClass('liked');
$(link).html('liked');
}
});
}
});
});
File: like.php
<?
$contentId = $_POST['Id'];
$timestamp = time();
$usersIP = $_SERVER['REMOTE_ADDR'];
// php code to update the database
// insert: contentId, timestamp, ip address
// if injected then echo / print true;
echo 'true';
?>
You should use jquery animate. It allows you to create an animation on a HTML element that you choose with jquery.
With Jquery, using the 'click' event, you can use the animate effect, and have something like this:
$("#my-button").click(function(){
$(this).animate({
height: 'toggle'
}, 500, function(){
$(this).animate({
height: 'toggle'
}, 500);
});
});
Please see the following example of doing that
So what I am doing is trying to create a 'favorite' system. I want the user to click a button and the code on the page will submit a value into a MySQL Database. Does this need to the page need to reload if the only thing I am doing is submit and value. I am not pulling any information from the database on the button's click. Thank you:)
A great way to avoid the complexities of Ajax and cross-browser compatibility is to use Jquery!
In your non-reloading page, you can put this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script text="text/javascript">
$(function() {
$('#button_id').click(function() { //in place of "button_id" you need to put your button's id
submitInformation("some information you want to send");
});
});
function submitInformation(data1)
{
$.post(
"handle.php", //this is the name and location of your php page
{
"input_var_one":data1,
}
);
}
</script>
and in your handler php page (in this case called "handle.php")
<?php
$inData1 = $_POST['input_var_one'];
//after your mysql_connect and mysql_select_db
$query = "INSERT INTO `yourtablename` VALUES ('var1 whatever you want', '$inData1')";
mysql_query($query);
?>
Jquery handles the Ajax request for you!
If you do not use AJAX, the information must be sent to the server in order to get to a mysql database table and processed by php and that surely requires page reload.
you can use:
<script type="text/javascript">
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
function onthatbuttonclick(something)
{
window.xhr.open('GET', "somephp.php?click="+something, false);
window.xhr.send(null);
alert(window.xhr.responseText);
}
var somevar = "user 01";
</script>
<input type="button" onclick="onthatbuttonclick(somevar);" />
and in php:
<?php
// some query required code
// and yes... i does require some safety measures:
$val = mysql_real_escape_string($_GET['click']);
mysql_query("INSERT INTO `tabel` (`click`) VALUES ('".$val."')");
echo 'you cliked a button.';
?>
you should now see an alert box with the text: "you clicked a button.".
I have a Flash movie that is embeded in a PHP page. The PHP page displays a value to the user (the number of images they have uploaded). When the user uploads a new image I want the value on the PHP page to reflect the change without refreshing the page.
This value is retrieved from database using MySQL. So heres what Ive done so far -
On the PHP page where I want to show the value I have a div
<div id="content_info"><script type="text/javascript" src="getInfo.php?group= <?php echo($groupid); ?> "></script></div>
This calls an external PHP file that queries the database and outputs the result like this
Header("content-type: application/x-javascript");
//do the query with PHP and get $number and then output
echo "document.write(\" (".$number.")\")";
When the page loads for the first time the correct number shows in the div and so all works fine. The next step is to call something to update the contents of this div when the value changes. So I will set up externalInterface in flash to call a javascript function to do this.
This is where Im stuck, I want to be able to do something like this -
function ReplaceContentInContainer(id) {
var container = document.getElementById(id);
container.innerHTML = getInfo.php?type=new&group= <?php echo($groupid) ?>;
}
and call this by
ReplaceContentInContainer(content_info)
I realise this isnt going to work but can anyone show me how to get this result?
many thanks
group= <?php echo($groupid); ?> will be executed only when PHP creates the page. You should store that value inside a variable in the javascript. See if this works.
<div id="scriptDiv">
<script type="text/javascript">
<!-- store the group id -->
var groupID = <?php echo($groupid); ?>;
function getGroupID()
{
return groupID;
}
function updateValue(value)
{
document.getElementById("content_info").innerHTML = value;
}
</script>
<div id="content_info">
<!-- for initial value -->
<script type="text/javascript"
src="getInfo.php?group= <?php echo($groupid); ?> ">
</script>
</div>
</div>
Now you can use flash's URLLoader:
var ldr:URLLoader = new URLLoader();
var gid:String = ExternalInterface.call("getGroupID");
var req:URLRequest = new URLRequest("getInfo.php");
req.data = {type:"new", group:gid};
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);
ldr.load(req);
private function onLoad(e:Event):void
{
var data:String = URLLoader(e.target).data;
ExternalInterface.call("updateValue", data);
}
private function onError(e:IOErrorEvent):void
{
trace("ioError");
}