So here i am trying to call a function that passes 2 values as parameters (added dynamically using php). The damn thing doesn't seem to work no matter what i try. Can any of you guys point out what i'm doing wrong? Here is the code:
// HTML/PHP
$pid = $row['postID'];
$pt = $row['postTitle'];
//There arrays are working great.
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
// JS
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
The quotes on "delpost are wrong. delpost is a function so onclick"<?php echo delpost($pid,$pt); ?>" should work.
Delete // Does not call delpost Delete // BUT if i remove the second parameter, it works! How?
first delete is not working because when you are passing two value on a function one value is blank that why its not working
<?
$pid = 1;
$pt = 2;
//There arrays are working great.
?>
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
alert(id);
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
Delete
I tried your code directly and it worked, but i also have added another way of writing it:
<?php
$pid = 42;
$pt = 'Awesometitle 2000';
?>
Delete
Delete 2
<script>
function delpost(id, title) {
console.log(id);
console.log(title);
}
</script>
Both variations should print 42 and "Awesometitle 2000" in your console.
Related
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 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)){
Just like the title above: how to concatenate two strings in JQuery?
This is my code so far:
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= "#" .$_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if (serviceName != "") {
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
As you can see in my above code, in variable name serviceID, I am concatenating hashtag and my GET value and I try to put it on ALERT and the result is correct, but when I assign it to .addClass it’s not working.
Any alternatives and solution is much appreciated.
I guess you meant that the PHP code should be evaluated before arriving to the client, therefore your code syntax is correct, but check out the following looks cleaner and also not polluting the global JavaScript scope (that's what the var ... is for):
var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;
but, since your code syntax is correct, you should verify that you actually have an element with serviceId as the id when your are executing it
if (($(serviceId)||[]).length) {
alert('your element with the id:'+serviceClass+' exists');
}
else {
alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
i hope this one solve the issue:
<script>
$(document).ready(function(){
serviceName = '<? echo "./".$_GET["services"].".php";?>';
serviceID = '<? echo "#" .$_GET["services"]; ?>';
serviceClass ='<? echo $_GET["services"]; ?>';
console.log(serviceID);
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
</script>
also check the console in your browser (firebug or chrome developer tools) to see the output ,fit your criteria
Try as but not sure, My change is append "#" Id in jquery
<script>
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= $_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$("#"+serviceID).addClass("it");
}
});
</script>
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!
Stuck on a jquery/javascript function that is attempting to .load a set PHP script but passing get variable parameters. As an aside this is set to happen automatically after 5 seconds. New to posting here but have read a lot of posts and can't seem to find exactly what I am doing wrong.
This function works:
function LoadMyPhpScript()
{
$('#MyDiv').load('hello.php');
}
setTimeout(LoadMyPhpScript,5000);
This function does not work:
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'hello.php';
strURL = strURL + cPhpParamString;
$('#MyDiv2').load(strURL);
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
Here's the hello.php
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Note: this is just a mock-up, would use regex to validate gets, etc in production.
RESOLVED
Here is what I ended up with, thank you!
function LoadMyPhpScript1(cPhpParamString)
{
$('#MyDiv1').load('hello.php'+cPhpParamString);
}
setTimeout(function() { LoadMyPhpScript1('?MyVar1=0&MyVar2=1'); },5000);
When you do this:
LoadMyPhpScript2('?MyVar1=0&MyVar2=1')
You are executing the function and passing the result to setTimeout
Try this:
setTimeout(function() { LoadMyPhpScript2('?MyVar1=0&MyVar2=1'); },5000);
However, sending the url querystring like that is an odd way of doing it. Something like this might be better:
function LoadMyPhpScript2(myVar1, myVar2)
{
var strURL = 'hello.php';
$('#MyDiv2').load(strURL, { myVar1: myVar1, myVar2: myVar2 });
}
setTimeout(function() { LoadMyPhpScript2(0, 1); },5000);
Better try this way:
File help3.html:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'help3.php';
strURL = strURL + cPhpParamString;
$.ajax({
url: strURL
}).done(function(data) { // data what is sent back by the php page
$('#MyDiv').html(data); // display data
});
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
</script>
</head>
<body>
<div id="MyDiv">
</div>
</body>
</html>
File help3.php:
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Test on my localhost, and both files on the same folder.