Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Wednesday, May 20

Post Multiple JavaScript Values to PHP Using jQuery AJAX

Step 1. To Package Up data for Sending

    <script>
        // Create an object using an object literal.
        var ourObj = {};
       
        // Create a string member called "data" and give it a string.
        // Also create an array of simple object literals for our object.
        ourObj.data = "Some Data Points";
        ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];

    </script>
   
Step 2: Transmitting This Data in jQuery AJAX

    <script>
        $.ajax({
           url: 'process-data.php',
           type: 'post',
           data: {"points" : JSON.stringify(ourObj)},
           success: function(data) {
                // Do something with data that came back.
           }
        });
    </script>
   
Step 3: Package Sent, Package Received

    <?php
    // Test if our data came through
    if (isset($_POST["points"])) {
        // Decode our JSON into PHP objects we can use
        $points = json_decode($_POST["points"]);
   
        // Access our object's data and array values.
        echo "Data is: " . $points->data . "<br>";
        echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
    }
    ?>

Wednesday, March 11

Redirect request after a jQuery Ajax call.

1. Adding a custom header to the response:
   
    <script>
        public ActionResult Index(){
          if (!HttpContext.User.Identity.IsAuthenticated)
          {
            HttpContext.Response.AddHeader("REQUIRES_AUTH","1");
          }
          return View()   
        }
    </script>


2. Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:
   
    <script>
        jQuery('body').bind('ajaxSuccess',function(event,request,settings){
            if (request.getResponseHeader('REQUIRES_AUTH') === '1'){
               window.location = '/';
            };
        });
    </script>



SOURCE: stackoverflow.com

Sunday, February 22

Determining a web user's time zone

Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.

On the same page, in the , you need to first of all include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the , below the jQuery, paste this:

<script type="text/javascript">
    jQuery(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            jQuery.ajax({
                type: "GET",
                url: "http://domain.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>
You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.


What should every PHP programmer know?

First off, there is no must know about learning PHP and MySQL... You go into it not knowing anything, and you'll come out of it knowing a bunch. If there was a must know, then nobody would be able to get into PHP and MySQL development. I personally think you are at a slight advantage going into this without knowing everything about it. It'll give you a fresh perspective and a think outside of the box attitude :)

As far as the object oriented stuff in this thread, it's true. But, as others have said, it's completely up to the programmer (you) to decide how to write your code. You can use object oriented practices, make a spaghetti code junction, or just right a bunch of functions, or whatever. Either way, as everyone else has been saying, it's up to you :)

IRC channel:

Don't really need this, but I find it helpful... See you in here :)


Manual:

The manual is your friend and probably the only thing you should know before diving in.

1. http://www.php.net/manual/en/

2. http://dev.mysql.com/doc/refman/5.0/en/apis-php.html

Frameworks:

Make sure it's an MVC framework :)

1. http://www.cakephp.org/

2. http://www.phpmvc.net/

3. http://www.codeigniter.com/

4. http://www.symfony.com/

IDE:

Whatever suits you best :)

1. http://www.eclipse.org/

2. http://www.vim.org/

3. http://www.zend.com/en/products/studio/

4. http://php.netbeans.org/

Template engines:

PHP is a good template engine

Model view controller frameworks help with this

Ajax:

1. http://jquery.com/

2. http://www.mootools.net/

3. http://developer.yahoo.com/yui/

4. http://www.prototypejs.org/

5. http://www.extjs.com/

6. http://code.google.com/webtoolkit/

CSS:

1. http://www.yaml.de/en/home.html

2. http://code.google.com/p/blueprintcss/

3. http://developer.yahoo.com/yui/reset/

Definitely not an exhaustive list, and things change constantly... But, it's a start :)

Have fun!


Source: stackoverflow.com

Monday, February 2

Validate user login through JS(JavaScript), Ajax and PHP

    <script>       
    function validateLogIn()
    {
    
        var username  = $("#IdOfYourUserFiled").val();
        var password  = $("#IdOfYourPasswordFiled").val();
        $.ajax({                                      
            url: 'login.php',    //checking the login in                     
            data: {username:username,password:password}, //You have to pass user inputs to next page to validate in DB            
            type: "POST",     //Method by which data being transmitted
            dataType: 'json',                  
            success: function(data)          
            {
                if(data.flag === 0){
                    alert("Username or Password is incorrect");
                } else if (data.flag == 1){
                    window.open('index.php', '_self');  
                }
            }
        }); 
    }
    </script>
 
    login.php
 
    <?php
        /*Database Details */
        define('DB_HOST', 'localhost');
        define('DB_NAME', 'practice');
        define('DB_USER','root');
        define('DB_PASSWORD','');
        
        /* Database connectivity */
        $con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); 
        $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
        
        /* Username and Password */
        $username = mysql_real_escape_string($_POST['username']);
        $password = mysql_real_escape_string($_POST['password']);
        
        $query = mysql_query("SELECT * FROM UserName where userName = '$username' AND pass = '$password'") or die(mysql_error()); 
        $row = mysql_fetch_array($query) or die(mysql_error());
        if(!empty($row['userName']) AND !empty($row['pass'])){
            print(json_encode(array('flag'=>1)));
        } else { 
            print(json_encode(array('flag'=>0)));
        }
        exit;
    ?>

Friday, January 30

With HTML5 file uploads with Ajax and jQuery.

The HTML:
    <form enctype="multipart/form-data">
        <input name="file" type="file" />
        <input type="button" value="Upload" />
    </form>
    <progress></progress>
 
Do some validation if you want. For example, in the onChange event of the file:

    jQuery(':file').change(function(){
        var file = this.files[0];
        var name = file.name;
        var size = file.size;
        var type = file.type;
        //Your validation
    });

file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div).


Ajax submit with the button's click:

    jQuery(':button').click(function(){
        var formData = new FormData(jQuery('form')[0]);
        jQuery.ajax({
            url: 'upload.php',  //Server script to process data
            type: 'POST',
            xhr: function() {  // Custom XMLHttpRequest
                var myXhr = jQuery.ajaxSettings.xhr();
                if(myXhr.upload){ // Check if upload property exists
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                }
                return myXhr;
            },
            //Ajax events
            beforeSend: beforeSendHandler,
            success: completeHandler,
            error: errorHandler,
            // Form data
            data: formData,
            //Options to tell jQuery not to process data or worry about content-type.
            cache: false,
            contentType: false,
            processData: false
        });
    });
 
 
To handle the progress:

    function progressHandlingFunction(e){
        if(e.lengthComputable){
            jQuery('progress').attr({value:e.loaded,max:e.total});
        }
    }

Tuesday, January 27

jQuery ajax, to send JSON instead of QueryString

You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Setting processData to false isn't necessary since JSON.stringify already returns a string.

Pass array to ajax request in $.ajax()

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});