file_put_contents with jquery reload? - javascript

I currently have a problem with php and javascript. Here is the thing : I'm trying to edit every few second a text file stored on the server, with the text the client wrote in a textarea (which id is 'area1')
The PHP :
<span id="write">
<?php
if(isset($_POST['text']))
{
file_put_contents('file.txt', $_POST['text']);
}
?>
</span>
The Javascript :
window.onload = function(){
t = setInterval(load, 2000);
function load()
{
$.ajax({
type: "POST",
url: "test.php",
data: {
text: $('#area1').val()
},
dataType: "text",
success: function(data) {
$('#write').load('test.php #write');
}
});
}
}
Nevertheless, nothing is ever written in file.txt, even if we enter the isset condition (that I tested).
Why isn't it working ? Can't we use jquery load with file_put_contents ? Or maybe it is a silly mistake that I can't see...
Thank you !

Have you tried using $.post? It is simpler and clearer.
Below is the full working code.
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<form>
<textarea id="area1"></textarea>
<textarea id="write"></textarea>
</form>
<script>
$(document).ready(function(){
t = setInterval(load, 2000);
function load()
{
$.post( "test.php", { text: $('#area1').val() })
.done(function( data ) {
$('#write').load('test.php #write');
});
}
});
</script>
</body>
</html>
And also make sure your php script has a privilege to add files.
Use (sudo) chown apache *folder* or similar.
Good luck!

Related

Javascript and php using ajax : why is the php not called?

From a javascript, I'm trying to call a php script which, at its turn, will generate a text file.
To this end, I'm using an ajax script. However, I notice that my text file is never created. I believe that the php is never called.
My javascript :
$.ajax({
type: "POST",
url: "php/test.php",
dataType: "json",
success : function(code_html, statut){
},
error : function(resultat, statut, erreur){
},
complete : function(resultat, statut){
}
});
My php (test.php) :
<?php
file_put_contents('test2a.txt', 'I am a test');
?>
Any idea what I'm missing here ?
Your ajax and php code look good.
Add some debugging lines to help troubleshoot.
When you run this code, click the button to do the post. You should then see some console messages stating either success for failure from the ajax.
I believe this is a working sample of what you are trying to do, you can use whatever version of jQuery that you want.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="btnDoThePost">Do The Post</button>
<!-- Jquery JS file -->
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<!-- Custom JS file -->
<script type="text/javascript" src="script.js"></script>
</body>
</html>
script.js
function callTestPHP() {
$.ajax({
type: "POST",
url: "php/test.php",
dataType: "json",
success : function(code_html, statut){
console.log("test.php: Sucess!");
console.log(JSON.stringify(code_html));
},
error : function(resultat, statut, erreur){
console.log("test.php: Error!");
console.log(JSON.stringify(resultat));
},
complete : function(resultat, statut){
console.log("test.php: Complete!");
console.log(JSON.stringify(resultat));
}
});
}
$(document).ready(function () {
$("#btnDoThePost").click(function (){
callTestPHP();
});
});
The php file should return some JSON for the ajax to parse.
test.php
// write to file
file_put_contents('test2a.txt', 'I am a test');
// return something for ajax to work with
echo "{ \"data\": \"Success\" }";
?>

JavaScript and PHP code not working

I have simple code with html, JavaScript and PHP. I am trying to pass a variable from HTML to PHP through ajax.
A text box appears on screen with button, user inputs in the text field and clicks the button. The field text should appear before the field. But in my case, nothing happens when clicking the button. I am posting my code below. These are the three files I have made:
index.html
<!doctype html>
<html lang="en">
<body>
<input id="name" type="text" /> <input id="button" type="button" value="Load" />
<div id="content"></div>
<script type="text/javascript" src="ajax.js"></script>
</body>
</html>
ajax.js
$('#button').click(function() {
document.write("this is javascript");
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: name,
success: function(data) {
$('#content').html(data);
}
});
});
page.php
<?php
if(isset($_GET['name'])) {
echo "lllllllllllllllll";
echo $name=$_GET['name'];
}
?>
Add CDN as mentioned above. Also make sure you load the jquery CDN or jquery.lib.js before including external js file, ajax.js in index.html.
There is an issue in your $.ajax code:
$.ajax({
url: 'page.php',
data: name,
success: function(data) {
$('#content').html(data);
}
});
change this to:
$.ajax(
{
type:'GET',
url: 'page.php',
data:"name=test"
},
success: function(data) {
$('#content').html(data);
}
);
only add before axaj.js
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
add this in your javascript ajax: type : 'GET'.
In your php code :
$name=$_GET['name'];
echo $name;

How to upload a HTML variable to a PHP file using AJAX

On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?

Echoing to the screen using AJAX PHP

I'm trying to write a short ajax code to echo the word 'hello' to the screen, but so far I'm not having any luck. If anyone know what I'm doing wrong, please correct me, and let me know. Thank you.
test6.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax() {
$.ajax({
type: "POST",
url: 'testing.php',
data:{action:'call_this'},
error: function(xhr,status,error){alert(error);},
success:function(html) {
alert(html);
}
});
}
</script>
echo hello
testing.php
<?php
if($_POST['action'] == 'call_this') {
echo "hello";
}
?>
I made some little changes to your code, like adding quotes for 'action', and creating a button because <A HREF has some issues with click event (buttons don't have those issues), here it is, now it works to me, let me know if it works to you too :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : {'action':'call_this'},
url : 'testing.php',
success: function ( data ) {
document.getElementById( "my_div" ).innerHTML = data;
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
echo hello
<br/><br/>
<button onclick="myAjax()">echo hello</button>
<br/><br/>
<div id="my_div"></div>
</body>
</html>
You have two problems. First, you have a syntax error. You need a comma after error:
function myAjax() {
$.ajax({
type: "POST",
url: 'testing.php',
data:{action:'call_this'},
error: function(xhr,status,error){alert(error);} /* this comma --> */ ,
success:function(html) {
alert(html);
}
});
}
Second, since you are using an anchor (<a>) tag, when you click on the tag it follows the link. You have to prevent that from happening. You can:
Not use an <a> tag
Put a href to something like # or javascript:void(0)
Make the function it calls return false
Use event.preventDefault
See it on JSFiddle
Edit:
On a side note, you may prefer to just use JavaScript to bind the event handler. This way you get a further separation of JS and HTML, which is typically preferred. Something like this should work:
$("#sendAjax").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/echo/html/',
data:{html:'call_this'},
error: function(xhr,status,error){alert(error);},
success:function(html) {
console.log(html);
$("#result").text(html);
}
});
});
Then in your HTML you don't need the onclick handler:
echo hello
See it on JSFiddle

javascript(ajax) and php working together?

I have a problem that my Js file is not recognizing a php variable built by ajax.
Here is an example:
index.php:
<script src="js.js">
</script>
<?
include('build.php');
<div id="brand">
<?
echo $brandinput;
?>
</div>
//....more code
?>
build.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function(data){
$("#result").html(data);
}
});
</script>
<?php $brandinput='<div id="result"></div>';
?>
js.js:
$(document).ready(function(){
//dosomething with div's in index.php
}
So, I'll try to explain this in the easiest way. My index.php includes a build.php which as you can see calls ajax to retrieve data from another server. This data is located in a php variable ($brandinput) which will contain many <div>,<input>,... etc. Then index.php echo $brandinput, showing all the content of the variable. But I have a js.js which change appearances in div's, input's, etc.. and is this js which is not recognizing the content of the variable $brandinput.
I'd like to know if you have more ideas or what am I doing wrong...
All the code is working well, I tested many times (except for what I said before)
The ajax call work well and Index.php displays $braninput correctly.
p.s. $brandinput is something like this:
<div id='BlackBerry'><img src='..\/images\/supporteddevices\/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
and yeah it works well too.
Actually this is how it supposed to be working, what you need to do is to wait for the ajax request to finish first before executing the functions in js.js
try this way
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
//dosomething with div's in index.php
}
});
});
or (assuming js.js is loaded after the script within build.php, or js.js has to be loaded after it)
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
}
});
});
// in js.js
$(document).ready(function () {
promise.then(function (data) {
//dosomething with div's in index.php
});
});
P.S
$brandinput just hold the string whatever assigned to, and will never be changed with ajax request, where ajax success handler just manipulate the rendered DOM directly in the client side.
You can try moving your <script> tag to after your php codes like this:
<? include('build.php'); ?>
<div id="brand">
<? echo $brandinput; ?>
</div>
<script src="js.js"></script>
//....more code
On a slightly different note, you should consider avoid embedding/intermixing PHP codes with HTML and Javascript. Take a look at this post for better ways way "passing data from PHP to Javascript".

Categories