...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 13, 2012

jquery ajax: doctype syntax error and $ is not defined error on remote server

Question by vaanipala

My jquery ajax code is working fine on my local server. However, it is not working on the remote server justhost.com. This is driving me nuts. 🙁 Can someone point out on where i’m going wrong?

Merry Flowers is the link to my website. When u go to the website with firebug on, u will be able to see the below mentioned errors.

When I try to debug with firebug, i’m getting the following 2 errors:

i’m getting a syntax error on the following line:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

I tried with different doctypes and I was still getting the same errors.

i’m getting “$ is not defined error” on the following line:

$(document).ready(function(){

Google chrome developer tool’s errors:

    Resource interpreted as Script but transferred with MIME type text/html: "http://www.merryflowers.com/js/jquery.js".
jquery.js:1Uncaught SyntaxError: Unexpected token <
home:8Uncaught ReferenceError: $ is not defined

When i click on network tab for chrome developer tool,

jquery.js's type is text/html not application/javascript. While the other javascript files are of type application/javascript.

cakephp’s original default.ctp code after all the corrections as requested by Lazerblade:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 

Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<?php
 echo $this->Html->charset();
 ?>
<title>
    <?php  __('Merry Flowers Montessori'); ?>
    <?php echo $title_for_layout; ?>
</title>
<?php
    //echo $this->Html->meta('icon');
    echo $this->Html->css('cake.generic');  //link to cake.generic.css will be 

placed in $scripts_for_layout
        echo $this->Html->css('navbar.css'); 
        echo $this->Html->script('jquery.js'); //Include jquery library
/*      echo $this->Html->script('swfobject.js');
*/

    echo $this->Session->flash();
    echo $this->Session->flash('email');
    echo $scripts_for_layout;
?>
<script type="text/javascript">
   //var j=jQuery.noConflict();
  $(document).ready(function(){
      $("#MerryParentEmail").change(function(){
        //txt=$("#MerryParentEmail").val();
        email_id=$("#MerryParentEmail").serialize();
        //alert(txt);
        $.post("/students/get_parent_info",email_id,function(result_str){
        result_array=result_str.split('*****');
          $("#MerryParentInitial").val(result_array[0]);
          $("#MerryParentName").val(result_array[1]); 
          $("#MerryParentLandline").val(result_array[2]);
          $("#MerryParentMobile").val(result_array[3]); 
          $("#MerryParentAddress").val(result_array[4]);
          $("#MerryParentStateId").val(result_array[5]);
          state=result_array[5];
          txt_str="state_id="+state;
          $.get("/students/getcities",txt_str,function(result){
            $("#MerryParentCityId").html(result).show();
            $("#MerryParentCityId").val(result_array[6]);
          });
          $("#MerryParentPostalCode").val(result_array[7]);
        });
      });

       $("#MerryParentStateId").change(function(){
        state=$(this).val();
        txt_str="state_id="+state;
        $.get("/students/getcities",txt_str,function(result){
            $("#MerryParentCityId").html(result).show();
        });
       });
 });
 </script>
</head>
<body>

<div id="container">
    <div id="header">
            <?php 
               echo $this->element('logo');
               echo $this->element('navbar');
              ?>
    </div> <!-- finish div header -->
    <div id="content">
        <div>
            <div id="content1">
            <?php echo $content_for_layout; ?>
            </div>
            <div id="content2">
                <?php 
                       echo $this->Html->link($this->Html->image("admission_open.gif",array("alt"=>"admissions")),
                                "/students/add",array('escape'=>false));  //if escape is false, admission_open.gif 

displays, otherwise only link <img src="/merry_flowers/img/admission_open.gif" alt="admissions"/> displays.
                          echo $this->Html->image("contact_us.gif", $options=array()); 
                    ?>  
                </div> 
            </div>
        </div>  <!--finish div content-->
        <div id="footer"> 
            &copy;  2011 Merry Flowers Montessori | Designed by VRI Web
        </div>
   </div><!--div container finish-->
</body>
</html>

The following is the view source code of default.ctp after all the corrections (the layout page in cakephp).

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 

Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   <title>
        Merry Flowers Montessori        Home    </title>
    <link rel="stylesheet" type="text/css" href="/css/cake.generic.css" /><link rel="stylesheet" type="text/css" href="/css/navbar.css" /><script type="text/javascript" src="/js/jquery.js"></script><script type="text/javascript" src="/js/swfobject.js"></script>   <script type="text/javascript">
       //var j=jQuery.noConflict();
      $(document).ready(function(){
          $("#MerryParentEmail").change(function(){

        //txt=$("#MerryParentEmail").val();
        email_id=$("#MerryParentEmail").serialize();
        //alert(txt);
        $.post("/students/get_parent_info",email_id,function(result_str){
        result_array=result_str.split('*****');
          $("#MerryParentInitial").val(result_array[0]);
          $("#MerryParentName").val(result_array[1]); 
          $("#MerryParentLandline").val(result_array[2]);
          $("#MerryParentMobile").val(result_array[3]); 
          $("#MerryParentAddress").val(result_array[4]);
          $("#MerryParentStateId").val(result_array[5]);
          state=result_array[5];
          txt_str="state_id="+state;
          $.get("/students/getcities",txt_str,function(result){
            $("#MerryParentCityId").html(result).show();
            $("#MerryParentCityId").val(result_array[6]);
          });
          $("#MerryParentPostalCode").val(result_array[7]);
        });
      });

       $("#MerryParentStateId").change(function(){
        state=$(this).val();


txt_str="state_id="+state;
            $.get("/students/getcities",txt_str,function(result){
                $("#MerryParentCityId").html(result).show();
            });
           });
     });
     </script>
</head>

<body>
<div id="container">

    <div id="header">
            <div>
<div style="float:left; width:98%; background-color:#ffffff;">
<img src="/img/logo.png" alt="" />  </div>
<div style="float:right; width:5%; top:100%; right:10%;">
<a href="/pages/home">Home</a>  </div>

    </div><div id="menu">

    <ul id="nav">

<!--        <li><a href="/pages/home">Home</a></li>
-->         <li><a href="#">Our Program</a><ul>

        <li><a href="/pages/preschool">Preschool</a></li>
        <li><a href="/pages/kindergarten">Kindergarten</a></li>
        <li><a href="/pages/summer_camp">Summer Camp</a></li>
        </ul>
        </li>
        <li><a href="#">About Us</a><ul>

        <li><a href="/pages/about_us">Merry Flowers</a></li>
        <li><a href="/pages/tour_our_school">Tour Our School</a></li>
        <li><a href="/pages/contact_us">Contact Us</a></li>
        </ul>
        </li>

        <li><a href="#">My Child</a><ul>
        <li><a href="/merry_parents/register">Report Card</a></li>

        </ul>
        </li>

        <li><a href="#">Events</a><ul>
        <li><a href="#">News &amp; Events</a>               <ul>
                <li><a href="/pages/sports_day">Sports Day</a></li>
                <li><a href="/pages/annual_day">Annual Day</a></li>

            </ul>
        </li>

        <li><a href="/pages/list_of_holidays">List of Holidays</a></li>
        </ul>
        </li>
        <li><a href="#">FAQ</a><ul>
        <li><a href="/pages/faq">FAQ</a></li>

        <li><a href="/feedbacks/add">Feedback</a></li>
        <li><a href="/forum/home">Discussion</a></li>
        </ul>
        </li>
        <li><a href="#">Admissions</a><ul>
        <li><a href="/students/add">Enroll Now</a></li>
        </ul>

        </li>
    </ul><!--finish ul nav-->
   </div> <!--finish div menu-->        </div> <!-- finish div header -->
    <div id="content">
        <div>
            <div id="content1">
            <script type="text/javascript">
//<![CDATA[
swfobject.embedSWF("/main_ani.swf", "content1", "530", "300", "9.0.0",
            "", {}, {wmode : "opaque"}, {});
//]]>
</script>               </div>

                <div id="content2">
                    <a href="/students/add"><img src="/img/admission_open.gif" alt="admissions" /></a><img src="/img/contact_us.gif" alt="" />  
                </div> 
            </div>

    </div>  <!--finish div content-->
    <div id="footer"> 
        &copy;  2011 Merry Flowers Montessori | Designed by VRI Web
    </div>


 </div><!--div container finish-->
</body>

</html>

By the way, i’m using jquery with cakephp. Thank you.

Answer by Lazerblade

Check again. The issue isn’t the jQuery file itself, it’s in the way it’s being added, possibly the .htaccess file has a conflict, or the path is set up wrong. It’s trying to load an error page. Look at the preview and response in Chrome Developer Tools, specifically the response when it loads jQuery.js. You’re loading your website page when you request the jQuery file. I’d need to see more of the actual code, not the view source, in order to figure out the exact issue, but the result is that jQuery isn’t loading…

EDIT: Check that your jQuery file is indeed in the /js/ folder and that it is named exactly jquery.js, not jquery.latest.min.js or something along those lines. Filenames are case sensitive, so if it’s jQuery.js (note the capital Q), you’ll need to rename or change your code. Also open the jQuery file and make sure it’s not empty (often “downloading” jQuery requires opening the file in your browser as plain text, copying all, pasting into a file, and saving that file).

EDIT2: If this is working locally but not remotely, there are 2 possible reasons. You’re either missing the rewrite conditions in your .htaccess file in your public folder, or you have /localhost/ in one of your config files, either apache httpd.config or an .htaccess file, or possibly in your config.php file (called from index.php in your public folder).

Options -Indexes
RewriteEngine on
#
# Redirect all non-image and non-file requests to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

Example of .htaccess in your public folder, to redirect all requests whose path is not in your public folder to go to your index file instead.

Answer by Starx

The way you are sending the request is

$.post("../students/get_parent_info" ... );

Which seem more like a directory traversing not a link. Even though it might seem to work in a phase, you should use this. You might have to provide direct link like

$.post("http://domain.com/students/get_parent_info", ... );
Read more
April 12, 2012

How to use PHP string in mySQL LIKE query?

Question by John Robinson

I am trying to find the number of rows that match a specific pattern. In this example, all that START with “123”:

This is working:

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '123%'");
$count = mysql_num_rows($query);

The problem is the LIKE will vary, so I’m trying to define it in the script, then execute the query, but this is NOT working:

$prefix = "123";
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix.'%'");
$count = mysql_num_rows($query);

How can I get this query to work properly in the second example?

EDIT: I’ve also tried it without the period (also not working):

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix'%'");

Answer by Jon

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it’s not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Answer by Starx

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

Read more

Jquery custom validation non numeric

Question by Brian Perin

I’m trying to write a custom validation function for jquery. The rule should be that the field cannot ONLY be numeric. I know how to write only numeric or only alpha but I want the rule to say that a value of “12345” would fail, but “12345A” would be validated

This is what I have for non numeric

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !value.match(/[0-9]+/);
},"Only alphabatic characters allowed.");

but I can’t figure out how to do not ONLY numeric.


Working script

Here are three rules that might be helpful, the last one is the one that answers this question.

 jQuery.validator.addMethod("noSpace", function(value, element) { 
    return value.indexOf(" ") < 0 && value != ""; 
}, "No spaces please");

jQuery.validator.addMethod("alpha", function(value, element) {

    return this.optional(element) || /^[a-z]+$/i.test(value);
},"Letters only please.");

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || isNaN(Number(value));
},"String cannot be numeric");

Answer by Elliot Bonneville

Use parseInt (which returns NaN if the operand isn’t strictly a number) like this:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(parseInt(value));
},"Only alphabatic characters allowed.");

Don’t use != in this case or you could wind up with this unpleasant situation.


According to Ken Browning‘s comment, parseInt might not be appropriate here. Try this instead:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(Number(value));
},"Only alphabatic characters allowed.");

Answer by Starx

I think this regex should be enough

/[a-z]/i.test(value);

Usage

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !(/[a-zA-Z]/i.test(value));
},"Only alphabatic characters allowed.");
Read more

multiple form submission with one submit

Question by skylab

I’ve been trying to think this through and figure out if it is possible or not. I’m using zen-cart as shopping cart software, but what I’d like to do, is hard code a page that is basically a list of 7-9 products, next to each product is a checkbox, so I’d like to figure out a way, via html,javascript or jquery to submit whichever forms(products) are checked to the cart. The typical form submission for a product looks something like this(sometimes there may be one or two additional hidden fields):

<form name="cart_quantity" action="index.php?action=add_product" method="post"      enctype="multipart/form-data">
    <input type="hidden" name="cart_quantity" value="1">
    <input type="hidden" name="products_id" value="7">
    <input type="hidden" name="id[6]" value="9" id="attrib-6-9"> 
    <input type="image" src="buy_button.png" alt="Add to Cart" title="Instructional Video Part 1: Add to Cart">
</form>

There would be 7-9 of these on the page, each with a checkbox, so I’m assuming a script would need to figure out which ones where checked and submit them via the form action? Maybe there is a better way of going about this that I’m not thinking of because a)it’s over my head or b)just haven’t figured it out yet. Anyway is something like this possible?

Answer by Starx

You can do it, as this

$("#yourcommonbuton").click(function() {
    if($("#checkbox1").prop('checked') == true) $("#form1").submit();
    if($("#checkbox2").prop('checked') == true) $("#form2").submit();
    if($("#checkbox3").prop('checked') == true) $("#form3").submit();
    return false;
});
Read more

mysql bug database error

Question by vvavepacket

Why is that when I search a row in my database, it ended up 0 results? In fact, there are rows that meet my search criterion when I view them manually, but the search button doesnt work as it is. Heres how

enter image description here

you can see there are rows that have ‘0000-00-00 00:00:00’ in them, but when I used the search feature, it ended up like this:

enter image description here

take note that Im entering it in the right field which is ‘AcctStopTime’.

TIA

Answer by ascii-lime

You’re searching with LIMIT 30 , 30.

That will cause there to be no results if there as less than 30 results total. Try LIMIT 0 , 30 instead.

Answer by Starx

If you analyze your query, you can see LIMIT 30, 30.

What it says is, extract 30 rows, from the 30th position. So, if you do not have any records more than or beyond 30, then your query will return an empty set.

Next thing you might want to check is the WHERE condition

If the given values does not match any field it will not return any records also.

Read more

whats faster, more efficient, loading a js file with arrays or populating arrays from tables

Question by Leigh

I am rebuilding an ecom site where the product data is stored in a multidimensional JS array that gets loaded on page load. This data is constantly being accessed with JS due to the nature of the site, to update prices based on user selections. There are many options that affect final price.

From a programming standpoint, a DB table is much easier to maintain and update than are JS arrays, and since I am porting the site over to PHP and MYSQL, I have been considering moving these arrays into tables.

So, would it be better to populate an array from the DB on load so that the pricing data is always available to the JS, or stay with hard coded JS files? I considered getting data via ajax as needed, but since this site has to constantly update pricing with user interaction, I have pretty much ruled that out.

How would you handle it?

Answer by Starx

No

I think its a bad idea to populate the database as array. If you do not filter the data you require from the database, this can be hazardous. Not to mention the amount of memory it is going to hog.

Sending correct ajax request, when a data is called for, is the right way to way.

Just look around Stackoverflow, the datas are very vital part, so all the necessary field are automatically updated when needed. It does not import all the db and store it on a array. It probably sends ajax request to check to see if something was updated.

Read more

php not redirecting

Question by NSchulze

I’m trying to write the logout of a website. When I do this I want the page to redirect to the login page. I think I’m doing it the correct way, but can’t get the right result. Could you guys point me in the right direction?

Relevant Code:

<button onclick="logout()">Logout</button>

function logout()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.location=xmlhttp.responseText;
}
}
xmlhttp.open("GET","logout.php",true);
xmlhttp.send();
}

<?php
session_destroy();

header("Location:http://localhost:8888/loginns.html");

mysql_close($con);
?>

Thanks!

Answer by Starx

You are sending an ajax request to the page. But you are redirecting in the PHP script. That will have no effect.

You should redirect in the JavaScript after the ajax request like

window.location = 'http://localhost:8888/loginns.html';
Read more

Escape all special characters in a string that is sent by jquery ajax

Question by developer747

I am trying to send text in key value pairs while doing a contentType: "application/json; charset=utf-8", ajax post to a web service. The problem I am facing is that if one of the parameters (that accepts text from the user) has quotes (“) it breaks the code [Eror message: Invalid object passed in ] . So far I have tried these without any success

var text = $("#txtBody").val(); 
var output1 = JSON.stringify(text); 
var output2 = text.replace(/[-[]{}()*+?.,\^$|#s]/g, "\$&"); 

Any ideas on how to escape the special characters for the jquery ajax post?

Answer by Trevor

Answer by Starx

There is already a function escape(var) which helps you escape the values. It should be enough for the purpose you are talking about

var output2 = escape(text);
Read more

Creating variables and reusing within a mysql update query? possible?

Question by miss_piggy

I am struggling with this query and want to know if I am wasting my time and need to write a php script or is something like the following actually possible?

UPDATE my_table 
SET @userid = user_id 
AND SET filename('http://pathto/newfilename_'@userid'.jpg')
FROM my_table 
WHERE filename 
LIKE '%_%' AND filename 
LIKE '%jpg'AND filename 
NOT LIKE 'http%';

Basically I have 700 odd files that need renaming in the database as they do not match the filenames as I am changing system, they are called in the database.
The format is 2_gfhgfhf.jpg which translates to userid_randomjumble.jpg

But not all files in the database are in this format only about 700 out of thousands. So I want to identify names that contain _ but don’t contain http (thats the correct format that I don’t want to touch).

I can do that fine but now comes the tricky bit!!

I want to replace that file name userid_randomjumble.jpg with http://pathto/filename_userid.jpg So I want to set the column user_id in that row to a variable and insert it into my new filename.

The above doesn’t work for obvious reasons but I am not sure if there is a way round what I’m trying to do. I have no idea if it’s possible? Am I wasting my time with this and should I turn to PHP with mysql and stop being lazy? Or is there a way to get this to work?

Answer by Bohemian

Yes you can do it using straightforward SQL:

UPDATE my_table 
SET filename = CONCAT('http://pathto/newfilename_', userid, '.jpg')
WHERE filename LIKE '%_%jpg'
AND filename NOT LIKE 'http%';

Notes:

  • No need for variables. Any columns of rows being updated may be referenced
  • In mysql, use CONCAT() to add text values together
  • With LIKE, an underscore (_) has a special meaning – it means “any single character”. If you want to match a literal underscore, you must escape it with a backslash ()
  • Your two LIKE predicates may be safely merged into one for a simpler query

Answer by Starx

Yes it is possible without the php. Here is a simple example

SET @a:=0;
SELECT * FROM table WHERE field_name = @a;
Read more

add up widths of elements until a ceiling is meet

Question by GermanMan

I have a header text changes length. I also have a set of logos that have a static length.

The problem: When the header (text) gets too long or short the logos either do not use the space effectively or the logos end up going to another line.

Solution in Simple Terms I want a script that adds up the width of logos one-by-one and when a certain width is meet it stops showing the logos.

For Example:

– The logos are hidden.
– The header space is 400px
– The container is 800px
– remainder space is 400px
– the script would add up the logos one-by-one until the 400px was meet
– If the 4th logos was at 450px it would not show that logo or any other logo after.

http://jsfiddle.net/FDkRN/

I tried what I know, but I am still new to js so any help would be great.

Thanks in advance!

Answer by Starx

Fix the width of heading, so its does not cross the boundary and set your logo container to hide the overflow content

h5 { width: 800px; }
#logos ul { white-space: nowrap; width: 400px; overflow: hidden; }
Read more
...

Please fill the form - I will response as fast as I can!