Can't run server side script using jquery - javascript

Firstly, thanks so much in advance for any help you might be able to give me on this!
Right, what I want to do, is to call a php script to run server side, which takes in a single value (which will be an email) and write it to a text file.
This is the .php file that I want run. I haven't added any of the email functionality, but after hours of trying I can't even seem to get it to create a text file and directory. If I run it in the IDE, it runs perfectly, it creates the script and displays the "test me" text at the bottom. However, when It runs from the jquery call, all it does it read the text at the bottom of the file. This is where I call it in jquery:
$(document).ready(function()
{
$("#emailForm").submit(function()
{
alert("Beginning jquery");
$("#div1").load("handleEmailAddresses.php");
alert("Load called");
//$.post("handleEmailAddresses.php");
});
I've also tried the post function you can see commented out. Nothing works. Here is the php file that is called:
<html>
<?php
$dir = 'myDir';
if ( !file_exists($dir) )
{
mkdir ($dir, 0777);//This just gives me r/w access to the folder
}
file_put_contents ($dir.'/test.txt', 'Hello File');
?>
Test Text
</html>
Please help, its killing me! Thanks so much!

Try Ajax
$.ajax({
url : '/handleEmailAddresses.php',
});
and if you want to check also:
$.ajax({
url : '/handleEmailAddresses.php',
}).done(function() {
console.log('completed');
});

Use This Script and try
Jquery:
$(document).ready(function()
{
$("#emailForm").submit(function(e)
{
e.preventDefault();
alert("Beginning jquery");
$("#div1").load("handleEmailAddresses.php", function(response, status, xhr) {
if (status == "error")
{
var msg = "Sorry but there was an error: ";
alert(msg + xhr.status + " " + xhr.statusText);
}
else
{
alert("Load Compleated");
}
});
});
PHP :
<?php
$dir = 'myDir';
if ( !file_exists($dir) )
{
if (!mkdir($dir, 0)) {
echo('Failed to create folders...');
exit;
}
}
$r = file_put_contents ($dir.'/test.txt', 'Hello File');
if ($r)
echo "Success";
else
echo "Error";
?>

Related

JS $.post not loading PHP file

I copied the code from a YouTube tutorial, modified the database connection and SELECT items to connect to my existing DB, but I can't seem to get the JS to load the PHP file. In Chrome using the "inspect" tool, I can see that the JS file is loading, but when I click on GRAB on my HTML page, it doesn't do anything. Almost like the JS file is loading but not running.
Webserver folder structure:
ROOT FOLDER
test.html
-AJAX (folder)
name.php
-JS (folder)
global.js
-CONNECTIONS (folder)
dbase.php
HTML CODE
<!doctype html>
<html>
<head>
<title>AJAX Database</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id=name-submit" value="Grab">
<div id="name-data"></div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
Javascript File
$('input#name-submit').on('click', function() {
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
PHP File
First try to add a console.log('something') inside your javascript click function, right before the var name =... line, to see that your event is even firing. If not you need to register the event properly. Is the click function surrounded by
$(document).ready(function () {
$('input#name-submit').on('click', function() {
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
});
//try using submit event
$(document).ready(function () {
$('input#name-submit').on('submit', function(e) {
e.preventDefault();
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
});
I'm not sure why my PHP code was edited and removed from here, but I've ended up re-writing the whole PHP page. I added or die(mysql_error()); to my SELECT statement and found that it needed me to specify my database in the FROM. I have multiple databases on my server and even though the DB is specified in the connection string it needed it again in the SQL Statement. The next problem I resolved was removing the mysql_num_rows as this was just not working like the demo did.
ORIGINAL PHP
<?PHP
if (isset($_POST['name']) === true && empty ($POST['name']) === false) {
require '../db/connect.php';
$query =mysql_query("
SELECT 'names'.'location'
FROM 'names'
WHERE 'names'.'name' = '" . mysql_real-escape_string(trim($_POST['name'])) . "'
");
echo (mysql_num_rows($query) !== 0) ? mysql_result($query, 0, 'location') : 'Name not found';
}
?>
The original was far too complicated for what I wanted and also for me to problem solve it so I re-wrote it:
NEW PHP FILE
<?PHP
//I've intentionally left out the connection data..
$sql_select = mysql_query("
SELECT names.location
FROM database_name.names
WHERE names.name = '" . $_POST['name'] . "'
")
or die(mysql_error());
$sql_fetch = mysql_fetch_assoc($sql_select);
echo $sql_fetch['name'];
?>
Thanks to those that assisted. Appreciated...
I am aware of the deprecated tags in the PHP file, but when I was copying from a demo so I wanted to get it working before updating it with new tags.

Form submited two times (ajax with jquery)

i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});

Something's wrong when I use $.post

Having some strange issue that I've been looking at for a couple of days now, and even with Googling can't solve.
I have this piece of JS that is called when a button is pressed. I cab tell this function really is called because the alert("1") pops up. I also know for sure the rarray is populated.
<script type="text/javascript">
function process_match() {
var rarray = new Array();
$x = $("input[name=pair]:checked").val();
$left = $x.charAt(0);
$rite = $x.charAt($x.length-1);
$car1a = document.getElementById("car"+$left+"_"+$rite+"_1").value;
$car1b = document.getElementById("car"+$rite+"_"+$left+"_1").value;
.....
$hsb = document.getElementById("hs"+$rite+"_"+$left).value;
rarray[0] = $left;
rarray[1] = $rite;
rarray[2] = $car1a;
rarray[3] = $car1b;
.....
rarray[15] = $hsb;
alert("1");
$.post("./updpoule.php",
{'results': rarray},
function(data) {
alert("2");
}
);
}
</script>
Then, I have the following php file :
<?php
$f = fopen("/tmp/q", "w");
$array = $_POST['results'];
fwrite($f,"AAA");
fwrite($f, $array[0]);
fwrite($f, $array[1]);
fclose($f);
?>
I have seen this code all over as solutions to similar problems, but I can't get it to work.
If I run the code, the alert("1") pops up. After that nothing happens. No file /tmp/q is being created. BUT, if I debug the page, and set a breakpoint where the $.post is, and then step through, a file /tmp/q IS created, just not with the right content..
Any suggestions are more than welcome.
Thanks,
Hans
Try to return something from your php script.
For example, add this to the end of the file:
echo 'OK';
?>
And, in you JS:
$.post("./updpoule.php", {'results': rarray}, function(data) {
if (data === 'OK') {
alert('ok');
} else {
console.log(data);
alert('error');
}
});
If you'll get popup with error, check the console on the data you've got from php.

ajax responseText contains php source code

I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/

php inside javascript alternative

In the code below after user click in cancel button It will call the function botao_excluir(). Inside of this function I want to run the cancela_cielo() php function. But I know that is impossible to run PHP inside JavaScript. So Could someone please tell me a way to do this?
PHP
<?php
$id=$row['id_temp_transaction'];
if($row['status']!=9)
{
echo "<input type = \"button\" name=\"cancel\" value = \"Cancel\" onclick= \"botao_excluir()\" >";
}
?>
JavaScript
<script>
function botao_excluir()
{
var r=confirm("Press OK to confirm the cancel")
if (r==true)
{
<?php cancela_cielo($row['tid'], $row['numero_afiliacao'], $row['chave_utilizada']); ?>
alert("Transaction Canceled")
}
else
{
alert("Cancel aborted")
}
}
You can do this using ajax
this will send the request to page.php as example the request will be executed in php and the data will be returned.
function botao_excluir()
{
var r=confirm("Press OK to confirm the cancel")
if (r==true)
{
xhr = new XMLHttpRequest()
xhr.open("POST","page.php",false);
xhr.send();
// response will be assigned to data variable
data = xhr.responseText
alert("Transaction Canceled")
}
else
{
alert("Cancel aborted")
}
}
you can read more about ajax and php here
http://www.w3schools.com/php/php_ajax_php.asp

Categories

Resources