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.
Related
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;
});
I had this code inside the <div id="chtmsg"> on a page that shows a messenger...
PHP :
if($perguntas){
for($c=0;$c<count($perguntas);$c++){
$perguntas[$c]->tipo == 'F' ? $class = 'message_F' : $class = 'message_P';
$hora = substr($perguntas[$c]->hora, 0, 5);
echo "<li class=\"".$class."\"><p>".$perguntas[$c]->mensagem."</p><span>".$pergunta->databr($perguntas[$c]->data)." - ".$hora."</span></li>";
if($perguntas[$c]->tipo=='F' and $perguntas[$c]->status == 0){
$pergunta->marcaRespLida($perguntas[$c]->id);
}
}
}
It works very well. So, I wanted to load it with js to refresh all new messages only inside the div #chtmsg and then I created a file msg.php and with the <?php include("msg");?> it continues working good, but with js I needed to put the path...
HTML :
$(document).ready(function () {
setInterval(function() {
$.get(hostGlobal+'site/modulos/produto/msg.php', function (result) {
$('#chtmsg').html(result);
scTop();
});
}, 3000);
});
But its shows the error inside de div...
Notice: Undefined variable: perguntas in /Applications/XAMPP/xamppfiles/htdocs/sisconbr-sistema-novo/site/modulos/produto/msg.php on line 3
I tested other codes inside the msg.php file and works ok without variables...
Just a thought...
Your first line in PHP
if($perguntas){
Should perhaps check if defined like so
if(isset($perguntas)){
My suggestion explained in another answer here
For better code, You should preferably use:
if (isset($perguntas) && is_array($perguntas)){
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/
To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!
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";
?>