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

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\" }";
?>

Related

I'm using AJAX to post an object from javascript to php within the same page and I'm getting the entire html page instead of the object

instead of getting the object as the responce data I'm getting the entire html page (the page I'm posting to) therefore I cannot retrieve the object in the php script
//this is an example of the object not the actual abject
var data={lat:"1.098", lng:"31", city:"durban"};
$.ajax({
type: "POST",
url: "/webapp/index.php/",
data: data,
async:true,
cache: false,
success: function(data)
{
alert(data.status);
console.log(data);
},
error: function (xhr, status, error) {
alert(status);
alert(xhr.responseText);
}
});
Since the server will consume <?php /*some PHP scripts */ but than return the following <!DOCTYPE html><html> etc... as response - you need to exit
index.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Handle POST requests here
echo "HELLO WORLD!";
exit; // <<< You need to exit here!
}
?>
<!DOCTYPE html>
<html lang="en">
<head><!-- head stuff --></head>
<body>
SOME FORM
<script>
// Some AJAX to "self" (index.php)
// success response: "HELLO WORLD!"
</script>
</body>
</html>
Or even shorter:
exit("HELLO WORLD!");

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 do I access variables from PHP file using Ajax and JSON? (data is not defined error)

I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue

file_put_contents with jquery reload?

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!

AJAX load page and reload/add after success

So I have a page which, when requested, updates my database. For example when I go to database_update.php it just updates the database and doesn't show anything.
Index.php shows user database content.
So I have function in JavaScript called update which must use AJAX to run this page and after the page loads (after all queries run successfully) it must load index.php and show updated page to the user (reload the page without refresh effect).
My code is like:
$.get('ajax_update_table.php', {
// The following is important because page saves to another table
// users nick which call update:
update: UserLogin
}, function (output) {
// The following is unimportant:
$(myDiv).html(output).show();
});
Two suggestions:
Return a "success" or "error" code from your database_update script. Returning a JSON string is very easy. For example:
echo '{"success":"success"}';
Use the $.ajax function. Then add the success, error, and complete parameters. You can call any javascript function(s) when the AJAX request is complete.
$.ajax({
url: 'update_database.php',
dataType: 'json',
success: function (data) {successFunction(data)},
error: function () { error(); },
complete: function () { complete(); }
});
function successFunction(data) {
if ('success' in data) {
// Do success stuff here.
} else {
// Show errors here
}
}
// .... etc
I might be missing something, but I'll try to answer your question.
I would setup a blank page that on loading it sends the index.php to a div on that page. For example, make a page titled blank.php.
blank.php would have the following:
function Index(){
$.ajax({
url:"index.php",
type: "GET",
success:function(result){
$("#web-content").html(result);
}
});
}
<script type="text/javascript">Index();</script>
<div id="web-content"></div>
You would then have your index execute the Index function to update the web-content div with the index.php data without reloading the blank.php page.
Got it to work!
my index.php
<html>
<head>
<script type="text/javascript" language="Javascript" SRC="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="Javascript">
function update_and_replace()
{
$.ajax({
url: 'ajax_update_table.php',
dataType: 'json',
success: function (data) {successFunction(data)},
error: function () { error(); },
complete: function () { complete(); }
});
}
function successFunction(data) {
if ('success' in data) {
$("#content").load("index.php");
}
}
</script>
</head>
<body>
<div id='content'>
Now is: <?php echo date("Y-m-d, H:i:s");?>
<br/><br/><br/><br/>
Aktualizuj
</div>
</body>
</html>
Ajax_update_table.php
<?php echo '{"success":"success"}'; ?>
Thank You all for your help.
I know that my English is bad but with your help I made it!

Categories