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)){
Related
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.
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.
I have a page where I use jQuery load() method to display a table of results based on a post request of some fields. But I need this load() to display the table and also inform javascript if a condition is met in the PHP script, so probably I need a json response. I don't know if it's possible to use the complete() callback to achieve that. I only need a single variable to pass from my PHP script to javascript.
I'm using load() because I believe other ajax methods need to do the HTML template part from javascript, am I right?
Hope I made myself clear, thanks
UPDATE1:
Here is my js code:
$("#listaNegraView").load('procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()},
function(data){console.log(data);}
);
And here is PHP script:
case 'listaNegra':
$_POST['nombres'] = mb_convert_encoding($_POST['nombres'], 'Windows-1252', 'UTF-8');
$_POST['apellidoP'] = mb_convert_encoding($_POST['apellidoP'], 'Windows-1252', 'UTF-8');
$_POST['apellidoM'] = mb_convert_encoding($_POST['apellidoM'], 'Windows-1252', 'UTF-8');
$listaNegra = $personaDB->existsPersonaListaNegra($_POST);
$pct100 = false;
if(!empty($listaNegra) && is_array($listaNegra)){
foreach($listaNegra as &$persona){
$persona['match'] = '';
$porcentaje = 80;
if(strtolower($persona['nombres']) == strtolower($_POST['nombres'])){
$persona['match'] .= 'name';
$porcentaje += 10;
}
if($_POST['nacimiento'] == $persona['fecha_nacimiento']){
$persona['match'] .= 'date';
$porcentaje += 10;
}
$persona['porcentaje'] = $porcentaje;
if($porcentaje == 100)
$pct100 = true;
}
unset($persona);
}
include(ROOT.RUTA_TPL.'ventas/listanegra.tpl.php');
break;
UPDATE 2:
Specifically the condition I want to pass to jasvascript is variable $pct100
You are "directly" outputting HTML code so I think, as a quick workaround, you should write the $pct100 in a hidden field/dom element and then access it with the complete callback in your javascript code.
This is an example of what I am suggesting
$("#listaNegraView").load(
'procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()
},
function(data){
$('#where-to-put-html-code').html(data);
var pct100 = $('#where-to-put-html-code #hidden-field-id').val() == '1' ? true : false;
}
);
Answer added by the suggestion of the asker.
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!
I have a list of files made by my PHP code
if ($handle = opendir($director))
{
$path="images/files/nou/";
if(Files::is_empty_dir($director))
{
echo "<p>There are no script available.</p>";
}
else
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$size=Files::getSize($director."/".$file);
$exts=Files::getExtension($file);
$filex = str_replace(".".$exts,"",$file);
if(strlen($filex)>10)
{
$filex=substr($filex,0,6);
}
echo "<div class='file' title='".$file."'>".$filex."</div>";
There are functions defined in my own class Files.
Good. I want that on mouseover to show file information with this code
function getInfo($file)
{
$info="<div class='info_public'><table border=0 cellpadding=2><tr>";
$info.="<td>File : </td><td>".$file."</td></tr>";
$info.="<tr><td>Extension : </td><td>".Files::getExtension($file)."</td></tr>";
$info.="<tr><td>Size : </td><td>".Files::getSize($file)."</td></tr>";
return $info;
}
I want to show info dynamically with JQuery. I wrote this
$(".file").mouseover(function()
{
data=$(this).attr("title");
alert(data);
});
It alerts always first filename not what I crossed with mouse. But if I disable mouseover JQuery function, the title appears correctly for each file in part. If I use mouseover function, the selected value from title doesn't appear correctly, it shows first filename in alert no matter what file I crossed with mouse.
I called the alert function to see results before implementing $.ajax function to avoid bad responses.
What's the problem in my script ?
Thank you
Your jquery code works, so check something else, may be you need to onload() that script ?
http://jsfiddle.net/oceog/hJyRm/