Ok, so I'm using JS and I am having issues with the following function.
In my PHP file I have:
<?php
$file = fopen("utensils/".$cake.".txt", "r") or exit("Unable to open file!");
while(!feof($file)) {
$image = fgets($file);
echo "<div id='".$image."' class='utensil' onclick='useUtensil(this.id)'>".$image."</div>";
}
fclose($file);
?>
whilst in the JS I have:
function useUtensil(id) {
alert(id);
if (id == "Sandwich Tins") {
alert(id);
} else {
alert("You do not need that utility!");
}
}
It's a very strange bug since I have a practically identical piece of code which works, however, with this code, although the first alert(id) alerts "Sandwich Tins", it does not alert(id), instead running into the else statement.
Any help is much appreciated!
So you're saying that the alert is returning "Sandwich Tins", and yet the comparison is still failing? If that's the case, then as the others have mentioned there's either:
1) Leading or trailing spaces.
2) Case issues (Although from what you claim that doesn't seem to be the case). No pun intended.
3) "Sandwich Tins" is wrong. Maybe it should be id == "Sandwich Tin"?
Test the first one by doing this:
function useUtensil(id) {
if (id.trim() == "Sandwich Tins") {
alert(id);
} else {
alert("You do not need that utility!");
}
}
If that doesn't work, try this:
function useUtensil(id) {
if (id.trim().toLowerCase() == "Sandwich Tins".toLowerCase()) {
alert(id);
} else {
alert("You do not need that utility!");
}
}
If that still doesn't work, I suggest inspecting the input in your console and making sure you're comparing it with the correct string.
put a space
id ==" Sandwich Tins"
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;
});
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.
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>
I have a database with my projects, Table called: Projects. In this table i have 3 columns:
ID, Titel, BLOB
This is my php:
{
echo '<div class="project_box">';
echo '<p class="project_text">' . $row['titel'] . '</p>';
echo '<img class="project_box_image" src="data:image/jpeg;base64,' . base64_encode($row['image']) . '" width="200" height="200"</img>';
echo '</div>';
}
Every ting loads already into my website, but now i want to check if the titel equals to something, with jQuery.
Now I have this code, but it works only for 1 div. If I make a second div in my database it loads in my website but when i click each of them it says alert "test".
It seems my code wont see the difference between the 2 title's in my div's
$('.project_box').click(function() {
if ($('.project_text').text() == "Portefolio"){
window.location.href = "portefolio/";
}else if ($('.project_text').text() == "test"){
alert('test');
}
});
.project_box is the div I load my, title and BLOB in, and on click I want to check project text equals to something.
.project_text is the title text of the project.
I hope its clear for you, it would really help my out!
thanks.
When you have multiple <p class="project_text"> how do you think jQuery interprets $('.project_text')? You can use .find() to get the class that is inside the clicked box.
$('.project_box').click(function() {
if ($(this).find('.project_text').text() == "Portefolio"){
window.location.href = "portefolio/";
}else if ($(this).find('.project_text').text() == "test"){
alert('test');
}
});
I think a switch() would be better here as well, saves you writing the .text() part multiple times.
$('.project_box').click(function() {
switch ($(this).find('.project_text').text()) {
case "Portefolio":
window.location.href = "portefolio/";
break;
default:
alert("test");
break;
}
});
it seems that it will solve your problem:
Better Way use children():
replace your jquery by this:
$('.project_box').click(function() {
var strText = $(this).children(".project_text").text();
if (strText == "Portefolio"){
alert("portefolio");
}else if (strText == "test"){
alert('test');
}
});
Demo:http://jsfiddle.net/a6NJk/676/
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/