...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
August 16, 2010

AJAX + PHP + HTML HELP: AJAX refresh ruining layout of site

Question by ritch

Can anyone help me here, when i run this code the page repeats its self. I also need it to refresh which it isnt doing.

Like this:
alt text

EDITED Code Below:

<?php include 'config.php' ?>
<script language="javascript">
function createRequestObject() {

   var req;

   if(window.XMLHttpRequest){
      // Firefox, Safari, Opera...
      req = new XMLHttpRequest();
   } else if(window.ActiveXObject) {
      // Internet Explorer 5+
      req = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
      // There is an error creating the object,
      // just as an old browser is being used.
     alert("Your Browser Does Not Support This Script - Please Upgrade Your Browser ASAP");
   }

   return req;

}

// Make the XMLHttpRequest object
var http = createRequestObject();

function sendRequest(page) {

   // Open PHP script for requests
   http.open('get', page);
   http.onreadystatechange = handleResponse;
   http.send(null);

}

function handleResponse() {

   if(http.readyState == 4 && http.status == 200){

      // Text returned FROM the PHP script
      var response = http.responseText;

      if(response) {
         // UPDATE ajaxTest content
         document.getElementById("msgstatus").innerHTML = response;
      }

   }

}


function repeatloop()
{
sendRequest('test.php'); // replace "inbox-status.php" with your php page's url
setTimeout("repeatloop()", 10000);
}

var replacementDiv = document.createElement("div");
replacementDiv.innerHTML = response;
document.getElementById("msgstatus").innerHTML = replacementDiv.firstChild.innerHTML;

window.onload=function() {
repeatloop();
}
</script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head><body>

<?php // Collet Latest Posts

$query = "
    SELECT Users.UserID, Wall.Message, Users.Forename, Users.Surname 
    FROM Wall
    INNER JOIN Users ON Wall.UserID = Users.UserID
    ORDER BY Wall.MessageID DESC
    LIMIT 20;";
$result = mysql_query($query) or die('Invalid query: ' . mysql_error());

// Collet Post User
    ?>
    <div id ="container">
        <div id="insideleft">
            <ul>
                <li><a href="index.php">Home</a></li>
                <li><a href="profile.php">Edit Profile</a></li>
                <li><a href="wall.php">Community Wall</a></li>
                <li><a href="logout.php">Logout</a></li>
            </ul>
        </div>
        <div id="insideright">
            <h1>Community Wall</h1>
            <br />
            <div id="postcontainer">
                <form method="post" action="wall.php" name="wallpost" id="wallpost">
                    <input type="text" name="message" id="message" class="message" />
                    <input type="submit" name="messagesub" id="messagesub" value="Post Message" class="post"/><br /><br />
                 </fieldset>
                </form>
            </div>
            <span id="msgstatus">
            <?php while ($row = mysql_fetch_assoc($result)) { ?>
            <div id="messagecontainer">
            <img class="pic" src="dummy.gif">
            <p class="messageposter">
            <?php echo "<b>{$row['Forename']} {$row['Surname']}</b><br />"; ?>
            </p>
            <p class="message">
            <?php echo stripslashes($row['Message']); ?>
            </p>
            </div>
            </span>
<?php
} ?>

Answer by Rudu

K so first – as Michael pointed out, you should be using a div for msg status:

Second – assuming the example file is called test.php, you’re loading the entire content of the page back into the msgstatus sub-element (rather than just the SQL). You’d actually be doing this to infinity, except that browsers don’t allow executable code to be posted in an AJAX reply (so the second embedded tier is being ignored).

I’m assuming you’ve simplified out of your code, but following is the updated code based on what you posted. NOTE there’s a bit of a style difference (feel free to ignore ;)!), you also included a BR in p.MESSAGEPOSTER when the paragraph was handling the newline (so I removed it).

<?php 

include 'config.php' 

function latestPosts() {
    $query = "
    SELECT Users.UserID, Wall.Message, Users.Forename, Users.Surname 
    FROM Wall
    INNER JOIN Users ON Wall.UserID = Users.UserID
    ORDER BY Wall.MessageID DESC
    LIMIT 20;";

    $result = mysql_query($query) or die('Invalid query: ' . mysql_error());

    while ($row=mysql_fetch_assoc($result)) {
        echo "<div id="messagecontainer">
    <img class="pic" src="dummy.gif">
    <p class="messageposter">
        <b>".$row["Forename"]." ".$row["Surname"]."</b>
    </p>
    <p class="message">
        ".stripslashes($row["message"]."
    </p>
</div>n";
    }
}


//Test for AJAX on the post - only output the values.
if ($_REQUEST['ajax']==1) {
    latestPosts();
    exit();
}


?>
<script language="javascript">
function createRequestObject() {

   var req;

   if(window.XMLHttpRequest){
      // Firefox, Safari, Opera...
      req = new XMLHttpRequest();
   } else if(window.ActiveXObject) {
      // Internet Explorer 5+
      req = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
      // There is an error creating the object,
      // just as an old browser is being used.
     alert("Your Browser Does Not Support This Script - Please Upgrade Your Browser ASAP");
   }

   return req;

}

// Make the XMLHttpRequest object
var http = createRequestObject();

function sendRequest(page,vars) {

   // Open PHP script for requests
   http.open('get', page+'?'+vars);
   http.onreadystatechange = handleResponse;
   http.send(null);

}

function handleResponse() {

   if(http.readyState == 4 && http.status == 200){

      // Text returned FROM the PHP script
      var response = http.responseText;

      if(response) {
         // UPDATE ajaxTest content
         document.getElementById("msgstatus").innerHTML = response;
      }

   }
}


function repeatloop()
{
    sendRequest('test.php','ajax=1'); // replace "inbox-status.php" with your php page's url
    setTimeout("repeatloop()", 10000);
}

window.onload=function() {repeatloop();}
</script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head><body>
    <div id ="container">
        <div id="insideleft">
            <ul>
                <li><a href="index.php">Home</a></li>
                <li><a href="profile.php">Edit Profile</a></li>
                <li><a href="wall.php">Community Wall</a></li>
                <li><a href="logout.php">Logout</a></li>
            </ul>
        </div>
        <div id="insideright">
            <h1>Community Wall</h1>
            <br />
            <div id="postcontainer">
                <form method="post" action="wall.php" name="wallpost" id="wallpost">
                    <input type="text" name="message" id="message" class="message" />
                    <input type="submit" name="messagesub" id="messagesub" value="Post Message" class="post"/><br /><br />
                 </fieldset>
                </form>
            </div>
        <div id="msgstatus">
<?php
//Output the current posts - you may not even want to do this since AJAX will fill it in right after load
latestPosts();?> 
        </div>
    <!-- ... we have some truncating! -->
?>

Some other points:

If you’re going with an AJAX solution, you might want to consider leaving the box empty in the starting HTML (drop latestsPosts(); at line 118), and then load the list once the page is rendered.

The way this is currently coded, every 10 seconds the complete list is reloaded by AJAX, you may want to track the latest post (perhaps by ID?) and pass that back to the AJAX command so that either:

  1. An update is only provided when there’s been a change. (JS response processing would ignore an empty return – current code would overwrite status with blank)
  2. Only new entries are provided. (JS response processing would prepend the new response to the existing msgstatus object).

Because this is a dynamic AJAX script you should be using the POST verb, not GET (it also requires some changes to how you post variables – the +'?'+vars in the http.open line needs to be in the body instead). Technically GET allows the browser to cache the results – I particularly notice this on Internet Explorer (ironically it seems they followed the W3C spec on this while the others don’t). Long story short – some users may complain the messages don’t stay up to date.

Answer by Starx

Well…… I didn’t read your all post, but when you are loading something through ajax, who only have to load a portion of the layout… not the entire layout itself,,, that would just be wrong…….. and get the effect like in your case.

SO since you are using PHP, try to filter the ajax request and then try to output the required portion only back the JavaScript………..

Read more
August 15, 2010

Jquery Inline Editing

Question by abc

There is a table that the data is being loaded dynamically in to it using Jtemplate. After I right click on a row and click on edit the entire row should go to the edit mode and the cells should contain dropdowns,text,date fields etc.as well it should display save and cancel buttons onclick of edit. after clicking on save the change data should go to the database using ajax. Hope you have suggestions for this.

thanks,
abc

Answer by Starx

You cannot expect much help based on the information you provided. But I will give you a small example

HTML

<div id="mytext">Your name loaded from database</div>
<a class="triggeredit" href="javascript:void();">Edit</a>

Script

$(function() {
   $(".triggeredit").click(function() {
       var thetext = $('#mytext').html();
       $("#mytext").html('<input type="text" name="edittext" id="edittext" value="'+thetext+'" />');
   });
});
Read more

JavaScript Find In Text File

Question by mobilestimulus

I have been searching for a JavaScript “Find In Page” tool to place in a HTML file so that when I enter a search term and click submit, the script will search a TEXT file of my choice and find a match on the text page for the entry submitted. Can someone give me a hand? Thanks.

Answer by Starx

Use regex pattern matching to highlight the searched text

Check this
http://www.nsftools.com/misc/SearchAndHighlight.htm

Read more
August 14, 2010

PHP, making MySQL statements and the use of quotes

Question by jel402

After setting up a mysqli object in php, i want to make to insert some POST variables into a table, but I have a question about how the quotes will work out:

$sql = "INSERT INTO whatever (a, b, c)
 VALUES ('$_POST[a]','$_POST[b]','$_POST[c]')";

I’m aware, however, that most times I’ve used global variables like POST or GET, there are quotes around the variable name — my question is do I have to so in the sql statement above? Should I then escape single or double quotes around those variable names? Not sure if quotes are even necessary…

Answer by KennyTM

Since you are using MySQLi already, why not use a prepared statement?

if ($stmt = $mysqli->prepare('INSERT INTO whatever (a,b,c) VALUES (?,?,?)') {
   $stmt->bind_param('sss', $_POST['a'], $_POST['b'], $_POST['c']);
   ....

This will take care of the quotes for you automatically and securely (against SQL injection).

See http://www.php.net/manual/en/mysqli-stmt.bind-param.php for example usage.

Answer by Starx

Quotes primarily means to group something, either string or something else. For example you are inserting Hello I am someone to the database then your query would be like this INSERT INTO tables VAlueS (Hello I am someone, other data, again another data) this will not clarify your parameters.

Escaping the quotes are good option, but only if you are using the same quotes inside a quote for example

$sql = "INSERT INTO whatever (a, b, c)
 VALUES ("$_POST[a]","$_POST[b]","$_POST[c]")";

In this case, it will render error, so you have to escape your quotes.

Read more
August 13, 2010

How can I create a simple datapicker in PHP?

Read more

Confusing JavaScript statement: "var x = new this();"

Question by user419125

I thought I understood the concept of the JavaScript prototype object, as well as [[proto]] until I saw a few posts regarding class inheritance.

Firstly, “JavaScript OOP – the smart way” at http://amix.dk/blog/viewEntry/19038

See the implementation section:

var parent = new this('no_init');

And also “Simple JavaScript Inheritance” on John Resig’s great blog.

var prototype = new this();

What does new this(); actually mean?

This statement makes no sense to me because my understand has been that this points to an object and not a constructor function. I’ve also tried testing statements in Firebug to figure this one out and all I receive is syntax errors.

My head has gone off into a complete spin.

Could someone please explain this in detail?

Answer by strager

AJS.Class effectively* translates this:

var Person = new AJS.Class({
    init: function(name) {
        this.name = name;
        Person.count++;
    },
    getName: function() {
        return this.name;
    }
});
Person.count = 0;

into this:

var Person = function (name) {
    this.name = name;
    Person.count++;
};

Person.prototype = {
    getName: function() {
        return this.name;
    }
};

Person.extend = AJS.Class.prototype.extend;
Person.implement = AJS.Class.prototype.implement;

Person.count = 0;

Therefore, in this case, this in AJS.Class.prototype.extend refers to Person, because:

Person.extend(...);
// is the same as
Person.extend.call(Person, ...);
// is the same as
AJS.Class.prototype.extend.call(Person, ...);

* There are a lot of cases I don’t go over; this rewrite is for simplicity in understanding the problem.

Answer by Starx

see this link http://www.quirksmode.org/js/this.html It will tell you about the this keyword, but I am not sure what this() is, may be its some kind of user defined function…… that you are not aware of…

Read more

Stable jquery or flash uploader

Question by Sir Lojik

I have been using a jquery plugin called uploadify for handling file uploads as it comes with interactive flash upload. but everyone on my website is complaining its not working. can some one please recommend me one that works in most situations. Thank you

Answer by Wayne Khan

Well, jQuery upload would be handled very different from a Flash-based upload. So you’ve to decide what’s right for the site.

jQuery: http://jquery.malsup.com/form/
Flash: http://code.google.com/p/swfupload/

Answer by Starx

UPloadify its jquery and flash both………… http://www.uploadify.com/

Read more
August 9, 2010

Storing settings inside DB

Question by dom

can someone tell me what’s the best way to store many different settings in a
database? Should I use one table with id,key,value?

Here is an example what i have to store:

PageNavigation.Font = "fontRegular";
PageNavigation.FontSize = 14;
PageNavigation.FontColor = 0x000000;
PageNavigation.SubFont = "fontRegular";
PageNavigation.SubFontSize = 12;
PageNavigation.SubFontColor = 0x000000;
PageNavigation.width = 200;
PageNavigation.height = 22;
PageNavigation.spacing = 5;
PageNavigation.LetterSpacing = 0;
PageNavigation.top = 250;
PageNavigation.rightMargin = 24;
PageNavigation.RollOverColor = 0xFF3300;
PageNavigation.ActiveColor = 0xCCCCCC;
PageNavigation.Icon = "/assets/images/arrow_default.png";
PageNavigation.IconLeft = 5;
PageNavigation.TextLeft = 5;
PageNavigation.SubIcon = "";
PageNavigation.SubIconLeft = 5;
PageNavigation.SubTextLeft = 22;

PageViewer.BackgroundColor = 0xe9edee;
PageViewer.ThumbSource = "";
PageViewer.maxVisible = 17;
PageViewer.ThumbWidth = 38;
PageViewer.ThumbHeight = 49;
PageViewer.ThumbActiveBorder = 2;
PageViewer.ThumbActiveBorderColor = 0xEE2233;
PageViewer.ThumbSpacing = 10;
PageViewer.ThumbLeft = 20;
PageViewer.ThumbBorderColor = 0xFF3300;
PageViewer.ThumbBorderSize = 1;
PageViewer.ThumbRollOverColor = 0xDDDDDD;
PageViewer.ThumbActiveColor = 0xCCCCCC;
PageViewer.ThumbSelectColor = 0xCCCCCC;
PageViewer.ThumbShadow = 1;
PageViewer.ThumbLayout = "Layout1";
PageViewer.ButtonLayout = "ButtonLayout1";

I’m new to database design and don’t know good resources to learn db-design

Cheers,
Dom

Answer by Starx

the best I think is to create a field for each type of setting. What does this do is,

  • we can keep many user defined settings of many users in one table.
  • we can create different sets of predefined setting which can be useful in several cases

ETC

Read more

Ghost code?Regarding missing tag in html file

Question by Gin

I’m having a problem regarding html.I got a html script contains no </body> nor </html> closing tags in the file yet when its source code view in the browser,both the </body> and </html> closing tags appears in the source code together with a <div>...</div> block of code.
How could this possible to happen?

Answer by Starx

Sometimes, if you are using web authoring applications like dreamweaver, netbeans, …. etc, they complete your un-complete tags before publishing them.

And, nowadays browsers are smart enough to correct those mistakes, while rendering the HTML file.

May be you will not get the same result in old browsers like IE6, FF1…….. Try it…

Read more
August 7, 2010

jQuery ajax load html from another server

Question by StealthRT

Possible Duplicate:
Load website into DIV

Hey all i am trying to find a way to call an external website and retreve its HTML so that i can check for something in it (wither the user entered a valid VIN # or not depending on what this website calls back)

This is the code i have:

$.ajaxSetup ({

  cache: false
 });

 $("#load_callback").click(function(){
    $.ajax({
    url: 'http://www.google.com',
    dataType: 'text',
    success: function(data) {
   alert(data);
    }
  });
 });

It works but only if i have it pointed to my server (and running on my server also). Is there a way i can call an external website using jquery/ajax? I am aware of the Same origin policy but was hoping something like what i want to do did not fall into that catagory?

I cant even get an iFrames title? Really??? wow….

David

Answer by Starx

Stick to simple things, if you want to load websites, be simple and go with iframe. If you want to make request use PHP or similar. For example you can use curl method to make request to another websites through PHP. Or even simpler, setup a form to request to another web server.

Read more
...

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