Using php and javascript to put random number in txt file - javascript

I have a text input field with a button that generates a random number between 1 and 20 and displays within the text field. The problem I am having, is taking that random number that it generates and saving it into a .txt file. The file chat.txt is stored in the same directory as the rest of these files. Not sure I am going about this the right way. The following is the code. Any ideas would be helpful.
chat.php:
<div id="pageWrap">
<form action="roll.php" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<button type="button" name="button" onclick="myFunction()">Roll</button>
<script>
function myFunction()
{
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
}
</script>
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
roll.php:
<?php
if(isset($_POST['button']))
{
$roll = $_POST['roll'];
$file = fopen("chat.txt");
fwrite($file,$roll);
fclose($file);
print_r(error_get_last());
}
?>

If you are interested in your way of generating random number on client end with javascript:
on html:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="pageWrap">
<form action="page.php" id="rollBox" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<button type="submit" name="submit" >Roll</button>
<script>
$(document).ready(function () {
$('#rollBox').submit(function(e) {
var x=document.getElementById("demo");
x.value=Math.floor((Math.random()*20)+1);
e.preventDefault();
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {}
});
return false;
});
});
function myFunction()
{
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
document.getElementById("rollBox").submit();
}
</script>
</form>
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
on php change this
<?php
if(isset($_POST['submit']))//on submit
{
//echo 'here';
$roll = $_POST['roll'];
$file = fopen("chat.txt","w");//no mode selected
fwrite($file,$roll);
fclose($file);
print_r(error_get_last());
}
?>
This works and generates the chat.txt

The random number is only generated on the client side: you're not sending it to the server yet. You're starting a form (name=rollbox), which you not sending back to the server (also you seem to be missing a </form>. Either submit the form, or use AJAX to send the information to the back-end.

Why don't you just generate the random number in PHP, and then put it in the file with file_put_contents()like this?
<?php
$roll = rand(1,20);
file_put_contents("chat.txt",$roll);
?>

You have some issues with the HTML of your top FORM.
Try replace it with the following code:
<form action="roll.php" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<input type="submit" name="button" onclick="myFunction();" value="Roll">
</form>

Related

jQuery Ajax data to same PHP page not working as INTENDED?

I have 22.php that both form and PHP script reside.
Problems;
1) when I submit, result shows below. But duplicates the form.
2) Further entering in the top (above) form, changes the result accordingly.
3) When I enter in the bottom form, then also the result changes accordingly and disappear the bottom from.
What I have tried so far as solutions;
1) removed totally - url: '',
2) replaced to the same page - url: '22.php',
3) replaced to this - var yourData = $(this).serialize();
4) Placed the PHP script just soon after body tag
None of above solve! Please help!
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
Just place PHP code top and put exit();. Here is your full code:
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
exit;
}
?>
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>

Cannot pass value to Codeigniter controller using ajax

I am having a trouble while sending a value from an input element to Codeigniter controller by using ajax.
Since I have to use WYSIWYG editor (summernote), thus I can just receive the input inside a <script>. However when I press the submit button, it just reloads the current page rather than the one in the controller.
Here is my code:
PHP view
<section id="mainContent">
<form method="post">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit" onclick="myFunction()">
</form>
</section>
<script type="text/javascript">
function myFunction() {
var markupStr = $('#textbox').summernote('code');
alert(markupStr);
$.ajax({
type : 'POST',
url : "<?= site_url().'cintern/save'; ?>",
async : false,
data : {'iDes': markupStr},
success : function(data){
alert("Success!");
}
});
return false;
};
</script>
PHP controller
public function save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $this->input->post('iDes');
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}
Please help! Thank you in advance.
You should use onsubmit of <form> tag instead.
<section id="mainContent">
<form method="post" onsubmit="myFunction()">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
The reason is, if you handle the onclick of your <input type="submit">, you can't intercept request of <form> tag after submit data.
I hope this can help you.
Since you are using JQuery for the ajax I suggest you use it to capture the submit also.
Remove the inline onclick assignment. Give the form an id attribute.
<section id="mainContent">
<form method="post" id="target">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
Turn myfunction() into a 'submit' event handler
<script type="text/javascript">
$("#target").submit(function (event) {
var markupStr = $('#textbox').summernote('code');
//stop the normal submit from happening
event.preventDefault();
$.ajax({
type: 'POST',
url: "<?= site_url().'cintern/save'; ?>",
async: false,
data: {'iDes': markupStr},
success: function (data) {
//do stuff with data then redirect to 'after_save'
console.log(data.results, data.otherstuff);
window.location.href = "http://example.com/cintern/after_save";
}
});
});
</script>
Controller:
public function save()
{
$data = $this->input->post(NULL, TRUE);
// $data is now a semi-sanitized version of $_POST
$_SESSION['iDes'] = $data['iDes'];
//do other stuff with $data
echo json_encode(['results' => "success", 'otherstuff' => $foo]);
}
public function after_save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $session_data['iDes'];
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}

How to use ajax to load default values into form

<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
How would I use the default values array and load the default values when I click insert default data using ajax? I created a click fucntion for insertdefault but am stuck there.
Here are two ways of doing that using the response of the ajax in json or set default values with the link.
$(document).ready(function(){
$('#InsertDefault').click(function(){
$('#name').val('Jane');
$('#postal').val('L5B4G6');
$('#phone').val('9055751212');
$('#address').val('135 Fennel Street');
});
});
Or:
$(document).ready(function(){
var jsonObjFromAjax = {
"name":"Jane",
"postal":"L5B4G6",
"phone":"9055751212",
"address":"135 Fennel Street"
};
$('#name').val(jsonObjFromAjax.name);
$('#postal').val(jsonObjFromAjax.postal);
$('#phone').val(jsonObjFromAjax.phone);
$('#address').val(jsonObjFromAjax.address);
});
Hope that helps!
The script prints the form and the data when requested, you would need to print only the data when requested, with an if, or a separate file.
And for the AJAX part, if you have no problem using jQuery:
$.getJSON("your-file.php?act=default", function (data) {
$.each(data, function (key, val) {
$("#"+key).val(val);
});
});
First generally you load default values if they exist with PHP
<input type = "text" value="<?php if (isset($var)){ echo $var ; } else { echo ''; }">
If you want to load them with JS(jquery)
$("input").each(function(i,v){
var name = $(this).attr('name');
for(i=0; i < result.length; i++) {
if ( result[i]['name'] == name ){
$(this).val(name);
break;
}
}
});
Untested of the top of my head

How to check the login using jquery post?

I am trying to create a login test application using jquery post, php ..
It is reading the value but not sending the data to server.php and returning the data.
HTML CODE
<div class="contact-form pad-25">
<div class="subpage-title">
<h5>Please Login</h5>
</div>
<div>
<div class="row">
<div class="col-md-4">
<input class="form-control" placeholder="Name" type="text" id="fname" name="firstname">
<input class="form-control" type="password" placeholder="Pass" type="text" id="pass" name="password" style="display:none">
</div>
</div>
<a class="btn btn-flat flat-color btn-rounded" id="next_name">NEXT</a>
<button class="btn btn-flat flat-color btn-rounded" type="submit" id="submit" style="display:none">Submit</button>
<div>
<!-- row-fluid -->
</div>
//SCRIPT
<script type="text/javascript">
$(document).ready(function(){
$("#next_name").click(function(){
$("#fname").hide('slow');
$("#pass").show('fast');
$("#next_name").hide();
$("#submit").show();
$("#submit").click(function(){
var r=confirm("Login Confirmaition!!")
if(r==true)
{
//alert("asd");
var pass=$("#pass").val();
var fname=$("#fname").val();
alert(pass);
alert(fname);
$.post('server.php', {fname:fname, pass:pass, type:'passwordcheck'}, function(msg){
alert(msg);
});
}
});
});
});
</script>
SERVER SIDE CODE
I tried to dump the data but the application is not reaching the server.php at all
<?php
//echo "asdasd";
$type=$_POST['type'];
$fname=$_POST['fname'];
$pass=$_POST['pass'];
//var_dump($fname);
$data = '{"name":"Pramit", "password":"Pramit123"}';
if($type=='passwordcheck'){
$phpdata = json_decode($data);
if($phpdata->name == $fname && $phpdata->password == $pass)
{
echo "success";
}
else
{
echo "fail";
}
}
?>
In your script, you have an error.
<script type="text/javascript">
$(document).ready(function(){
$("#next_name").click(function(){
$("#fname").hide('slow');
$("#pass").show('fast');
$("#next_name").hide();
$("#submit").show();
$("#submit").click(function(){
var r=confirm("Login Confirmaition!!")
if(r==true)
{
pass=$("#pass").val();
fname=$("#fname").val();
//$.post('/server.php', {fname:fname, pass:pass, type:'passwordcheck'}, function(msg){
$.post('http://localhost/server.php', {fname:$fname, pass:$pass, type:'passwordcheck'}, function(msg){
alert(msg);
});
}
});
});
});
</script>
If you are in the same server where are you doing the request, you haven't got to insert the server, but if you put the server, i recommend you to put at least the protocol, because that request is doing on http://localhost/localhost/server.php, thats why you can't see the receive in the server part.
Remember too that in Javascript, variables are written like that:
var variable1;
variable = variable1;
Never put the variables like PHP, using the $ symbol
Tell me if that is useful to you :D
You are calling wrong url you must add http:// in your post url like,
$.post('http://localhost/server.php'...

mysql_num_rows returned with ajax

i need to pass two dates to a mysql query through ajax.
i have two date inputs.
this is the index.php that has the input
<div id="input">
<td><input type="date" name="date_start"></td>
<td><input type="date" name="date_end"></td>
<input type="button" class="button" value="Get Value">
</div>
<div id="count_display">
</div>
this is the getresult.php file that has the working query
$date_start=$_GET['date_start'];
$date_end=$_GET['date_end'];
$select="select * from tblreport where (date(date_added) between '$date_start' AND '$date_end');";
$res = mysql_query($select);
$rec_count = mysql_num_rows($res);
echo "There are <font color='red' size='3'>".$rec_count."</font> matching records found.";
i want to display the resulting echo from the getresult.php inside the <div id="count_display"> in the index.php file through an ajax method which will display the result in real time without refreshing/reloading the page.
the result will be very similar to this example on this page: http://www.w3schools.com/php/php_ajax_database.asp but all i need is the count of rows returned by the query.
You can do it easily using jquery. Here is your code
<script src="js/jquery-1.6.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".button").click(function()
{
var date_start = $("#date_start").val();
if($("#date_start").val()=='') date_start="";
var date_end = $("#date_end").val();
if($("#date_end").val()=='') date_end="";
var dataString = 'date_start='+ date_start + '&date_end=' + date_end;
$.ajax({
type: "POST",
url: "getresult.php",
data: dataString,
success: function(msg){
$('#count_display').html(msg);
}
}); //END $.ajax
});
});
</script>
<div id="input">
<td><input type="date" name="date_start" id="date_start"></td>
<td><input type="date" name="date_end" id="date_end"></td>
<input type="button" class="button" value="Get Value">
</div>
<div id="count_display">
</div>
Try this:
<script language='javascript'>
$(document).ready(function() {
$.get('getresult.php')
.success(function(result) {
var data = $.parseJSON(result);
var div = document.getElementById("count_display");
div.innerHTML = data.message;
});
});
</script>
Note, you need to include the current jquery api from jquery.com.
In PHP:
$message = "There are <font color='red' size='3'>".$rec_count."</font> matching records found.";
echo json_encode( array( "message"=>$message ) );

Categories

Resources