...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
September 15, 2013

Sending json with php and parse it in ajax call

User2589904’s Question:

I don’t have experience using JSON with php and ajax and I need your help.

I have a php page that validates user input… Before using json, I used to store them in an array. I was able to parse the json when I store my values in an array like this
$data = array(“success”=>true, “msg”=>”my masg”);
json_decode($data);

and then in my ajax call on success function I data.success and data.msg

How do I store multipe msgs or errors in my array and parse them in my ajax call?
here is my code

here I want to validate user input and I would like to validate many fields

    if(isset($_POST['txt_username']) &&($_POST['txt_username']!=""))
    {
        $username =trim( $_POST['txt_username']);
        $username  = filter_input(INPUT_POST, 'txt_username',
                    FILTER_SANITIZE_STRING);
    }
    else
    {

             }

So how do I do it in the else statement?

here is my ajax call

 $.ajax({       
            type: "POST",
            dataType: "json",
            cache: false,
            data: {txt_username:$("#username").val(), txt_password:$("#password").val()},

            beforeSend: function(x) {

                if(x && x.overrideMimeType) {

                    x.overrideMimeType("application/json;charset=UTF-8");
                }

            },

            url: 'proccessing_forms/admin_login.php',

            success: function(data) {

                // parse the data
            }
    });


    }

You can use multidimensional arrays for this:

$msg = array("success" => array(), "error" => array());

// ... DO you processing on if and else

//When you need to add to an success do
$msg['success'][] = "My Success";

//When you need to add to an error do
$msg['error'][] = "My error";


echo json_encode($msg); exit;

On the ajax’s success event, you can access both of these variables individually.

success: function(data) {
    var errors = data.error;
    var succesess = data.success

    //Process each msg
    $.each(errors, function(index, msg) {
         console.log(msg);
    });
}
Read more

How to have a centered bootstrap layout

User2594008’s Question:

I need to create a responsive layout, and I have used bootstrap before but I have never actually attempted this. Making full width designs is plenty easy, but I want a two column layout that would say.. have a max width of 900px together.

The example of what I am trying to do can actually be seen right here on stackoverflow. There are two columns to this site, but both columns are centered on the page right now with space to the left and right. I just need that (and responsive as well for smaller screens).

Assuming your container has an id of container you can center it by giving auto left and right margin like:

#container { 
   margin: 0 auto;
}

The width of a default bootstrap grid is 960px and is already centered by default. You only have to assign a class called container like

<div class="container">
     <!-- The begin your row -->
     <div class="row">
          <div class="span8">
               Demo right part of stackoverflow
          </div>
          <div class="span4">
               Demo left part of stackoverflow         
          </div>
     </div>
</div>
Read more

Sort by AVG(rating)

Tompa’s Question:

I am trying to write a mySQL-query that sorts by first suburb and then AVG(rating_table.rating).

Here is the street_table:

id       street_name       suburb

0        streetone         subone
1        streettwo         subthree
2        streetthree       subthree
3        streetfour        subtwo

And here is the rating_table:

street_id    rating

1            1
2            1
3            4
2            2
1            3

And this is the result I am looking for:

id      suburb         avarage_rating

0       subone         (no rating)
1       subtwo         1 + 3 / 2 = 2
3       subthree       4 / 1 = 4 (Just one vote..)
2       subthree       2 + 1 / 2 = 1.5

(As you can see, #3 is before #2 because of the avarage_rating)

You can combine the ORDER BY to use multiple columns like:

SELECT .... ORDER BY suburb, AVG(rating_table.rating);

You can define order specific to items too

SELECT .... ORDER BY suburb ASC, AVG(rating_table.rating) DESC;
Read more

Can't get responseText from $.post

Andrey Yasinishyn’s Question:

I need to get a string from the server using jquery $.post, the issue is that I can’t get the responseText from it.
So if I run

role = $.post('user_helper/return_current_role', {id: 3}, null, "json").responseText;
console.log(role);

I get undefined
If I try

role = $.post('user_helper/return_current_role', {id: 3}, null, "json");
console.log(role);

I get an object Object { readyState=1, getResponseHeader=function(), getAllResponseHeaders=function(), more...}, where responceText is, for example, teacher.
Here is this response, copied from firebug:

readyState
    4

responseText
    "teacher"

status
    200

statusText
    "OK "

As it’s asynchronous, and has a callback function, how about:

$.post('user_helper/return_current_role', {id: 3}, function(result) {
    var role = result;
    console.log(role);
}).fail(function(a,b,c) {
    console.log(a);
    console.log(b);
    console.log(c);
});

You can not use the result of an ajax call, until it’s returned from the server.
It’s just how asynchronous calls work!

EDIT:

chained on a fail method, see if that tells you anything ?

You can do it this way too:

$.post('user_helper/return_current_role', {id: 3}, function(data) {
   var role = data; 
   // Now Do what you need
}, "json");
Read more

jQuery scripts on ajax content WITHOUT using $(document).on

Tonechild’s Question:

I am using an infinite scroll plugin which uses ajax.

When the ‘next page’ is loaded via ajax, all other ajax related scripts that are on the next page do not work. I have been told that I have to use ‘delegated events'(ie change $(id).click() to $(document).on) – problem is that means editing multiple plugins and changing dozens of function calls.

Is there any way I can avoid changing everything to $(document).on and do something cool with the infinite scroll?????

I’d much rather modify the infinite scroll plugin rather than modifying other ajax related plugins to make them fit.

Unfortunately you have very few options here, and switching to delegated events is by far the best of them.

The problem is that your old code was assigning behaviour to “particular elements” when what it should really have been doing is creating page-wide responses to “certain types of actions”.

I see 3 possibilities, and only one of them is guaranteed to work.

  1. Run any scripts that are needed on new pages each time a new page is loaded. The downside here being that unless you are careful about also “tearing down” between content loads you will have behaviours repeating or colliding with each other (eg: double popups, broken animations).
  2. Encapsulate the dynamic areas in <iframe>s. Depending on your architecture this may or may not be possible, and certainly won’t be easy to integrate with some kind of infinite scrolling plugin which already expects a certain page structure.
  3. Bite the bullet and fix the crappy code.

Loading scripts inside your ajax loaded content is a bad way to start with anyway. What you need is event delegation to attach itself to any dynamically added elements.

$("body").on("click", ".yourclass", function() {
    //This function will run for every element with `yourclass` class you load via ajax
});
Read more
September 12, 2013

PHP Array during echo

Anthonytherockjohnson’s Question:

I have an assignment to do but am having trouble understanding the given psuedocode :/

<?php
$bucket = new array();
print $bucket->addrocks('Rock1')->addrocks('rock2')-
>addrocks('Rock3');

echo "<h1>My Bucket</h1>";
echo "<ul>";
foreach($bucket as $rock){
echo "<li>". $rock ."</li>";
}
echo "</ul>";
?>

Now my trouble starts with understanding how they want me to construct the array after the “print” call? i am not looking for a direct answer to this just maybe a tutorial link or a finger in the right direction

Thank you in advance

Well unlikely but may be the array is not an construct but an class in your pseudocode. My assumptions depend on the use of new keyword and the user of -> and addrocks which looks like a method.

So, create a class called array (stupid I know) and get going.

However the user of foreach($bucket) also shows that it expects $bucket to be array. So decide wisely 🙂

May be use a magic method called __toString() inside the class and return back the array.

Read more

Using mod_rewrite to make Blog URLs more SEO Friendly

Three3’s Question:

I am trying to turn my blog URLs into a more SEO friendly format using mod_rewrite. All of my articles are stored in a simple MySQL database. Each blog article url looks like this:

http://www.test.com/blog?id=20&category=online%20php%20tutorials&pagename=how%20to%20customize%20functions

I have managed to to make them look like this using mod_rewrite:

http://www.test.com/blog/online-php-tutorials/how-to-customize-functions/20

Here is my code that I paced in my .htaccess file:

RewriteRule ^blog/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/?$ /blog?id=$3&category=$1&pagename=$2 [L]

So what happens is this: When I click on the URL http://www.test.com/blog/online-php-tutorials/how-to-customize-functions/20, all of my CSS and images are not loading because it is trying to load them from a directory that does not actually exists. How would I load the files without having to create multiple directories that contain my sites CSS files and images?

Use root identifier / in your path. This will point the DocumentRoot of your server. Let me explain How this works

For an image like this:

<img src='test.jpg' /> 

Browser/Server will find it as http://www.test.com/blog/online-php-tutorials/how-to-customize-functions/20/test.jpg' but if you use / before the path

<img src='/test.jpg' />

It will look for it in http://www.test.com/test.jpg

Another Technique

Use full path in your files like:

<img src='http://test.com/test.jpg' />
Read more

Testing JavaScript With Firefox – refresh does not seem to always refresh JavaScript

KDawg’s Question:

I am testing on a live server and editing JavaScript on the CodeIgniter framework there.
I am testing it in Firefox.

Typically I make some javascript changes and then save my edits via FTP, hit refresh in the browser, look for my changes and carry on.

For some reason – the newly saved javascript is not always showing up when I refresh.
I am sure it is nothing like, I forgot to upload, or did not wait for it to fully save – as I have tested this a number of times – simply adding an alert and refreshing – looking for the alert…. sometimes it is not there… Second refresh… there it is.

Anyone know what gives or how to ensure the refresh picks up the changes?

Thanks all 🙂

This particular problem is caused by caching. It is both useful and sometimes pain. JavaScript Library like jQuery uses a simple technique when we add script to the DOM. It appends a random key at the end of file, thus faking the HTTP request as new.

Normally, you would not require the script to change when viewed by the user, but when you are developing it becomes a real pain. So during those time, just add some random text at the end of every file during load or if you are too lazy to do that, send a header saying to clear the cache.

In PHP something like at the top will do it:

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1990 05:00:00 GMT");
Read more

PHP Notice: Array to string conversion Error

Beardy’s Question:

Been experiencing this error for a little while and can’t find any conclusive answers on fixing it. I have tried removing quotes from $key in line 59 but to no avail.

if (!get_magic_quotes_gpc()) {
    if (isset($_POST)) {
        foreach ($_POST as $key => $value) {
            $_POST['$key'] =  trim(addslashes($value));
        }
    }

    if (isset($_GET)) {
        foreach ($_GET as $key => $value) {
            $_GET[$key] = trim(addslashes($value));
        }
    }   
}

LINE 59

$_POST['$key'] =  trim(addslashes($value));

Error On Screen

Notice: Array to string conversion in
C:Inetpubvhostsdomain.comhttpdocslibraryconfig.php on
line 59

Check if it is array before you assign it

$_POST[$key] =  !is_array($value) ? trim(addslashes($value)) : '';
   //  ^   Remove the quotes here                          //  ^ Do something 
                                                           //  Instead of 
                                                           //  Using empty
Read more

The OOP way of doing things (in PHP)

Marcos’s Question:

I’m still trying to wrap my head around OOP, having been brought up in procedural coding a long time ago. Been stretching my legs in PHP for a while now.

So I’ve read a lot about best practices and paradigms and such. Especially SOLID. And I’ve tried to do things in a number of different ways. MVC-style, I ended up with extremely long, convoluted models that were either tightly couple to everything else, or had to be injected with half a dozen dependencies. Then I swung back to fat controllers, who did pretty much all the work and the models were only like helpers.

Now, I need a judgement on my current approach. Would this be a valid (SOLID) OOP way of doing a user-account-management system:

class PDO_Wrapper { # wraps PHP's PDO functions nicely
    public function select(...);
    public function insert(...);
    public function delete(...);
    public function update(...);
}

class ORM extends PDO_Wrapper { # very basic
    public function load($id); # assigns everything in row $id to object paramters
    public function save(); # writes all object parameters to db
}

class User extends ORM { # some User specific functions
    public function hashPassword($password);
    public function sendConfirmationMail();
    ...
}

class Login extends User { # one model for each User action (login, register, forgot password...)
    public function login($input);
}

Well, I dont know which one of SOLID priniciples are you following:

Lets break down your code

class ORM extends PDO_Wrapper { # very basic
    public function load($id); # assigns everything in row $id to object paramters
    public function save(); # writes all object parameters to db
}

This class, is extending PDO_Wrapper. Now lets ask, does it provide an extension of PDO_Wrapper? Actually It does, so its kind of correct. But for this:

class User extends ORM { # some User specific functions
    public function hashPassword($password);
    public function sendConfirmationMail();
    ...
}

Does User extend the ORM in some way? NO, it uses it! So very wrong. You have to create an object of it inside the class and use it like:

class User {
   private $orm_db;

   function __construct() {
        $this -> orm_db = new ORM();
   }
}

Now for this:

class Login extends User { # one model for each User action (login, register, forgot password...)
    public function login($input);
}

Login is an action done by the object of User class. So it is a method of User Class, not a sub class.

class User {
private $orm_db;

   function __construct() {
        $this -> orm_db = new ORM();
   }

   public function login($input) {
        //...
   }
}

I hope it clears some concept about OOP.

Read more
...

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