Skip to main content

JSON Jquery Ajax

If use want to trigger ajax on Click

  $('.taskStat').live('click',function(){
       $.ajax({
            type: 'POST',
            url: ajax_url+"Members/change_Addtask/"+stat,
            success: function(data) {
                var obj=JSON.parse(data);
                if(obj.resp=='true')
                {
                    alert("Hello sudhir");
                } else
                {
                    alert("Checking Value");
                }
            }
        });
    });

OR

$('.taskStat').live('click',function(){
       $.ajax({
            type: 'POST',
            url: ajax_url+"Members/change_Addtask/"+stat,
            success: function(data) {
               var obj = jQuery.parseJSON(attr);
              $.each(obj, function(key, value) {
                   alert(key+'is'+value);                       
               });
            }
        });
    });
Function

function change_Addtask($id=NULL){
           
        $resp=array();
        if($id==1)
        {
       
            $resp['resp']="false";
        }
        else{
                   
            $resp['resp']="true";
        }
        echo json_encode($resp);
        die;
    }

Manipulation of jQuery Ajax

$.ajax({
url: "demo.php",    // the requested URL
data: {id: 123},  //data send to the requested URL
type: "GET", 
dataType : "json",  // type of data we expect to back from URL
success: function( json ) { // function called after request succeeds.
$( "<h1/>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
},
error: function( xhr, status, errorThrown ) { // executes when fails
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) { //code to run regardless of success or failure
alert( "The request is complete!" );
}
});
async : Used for request synchronization . Set to trueor false
 Note : If you set this option to false, your request will block execution of other code until the response is received.
cache: Used for cached response if available
Note: Defaults to true for all dataTypes except "script" and "jsonp". When set to false, the URL will simply have a cache busting parameter appended to it.
complete :A callback function to run when the request is complete, regardless of success or failure. 
context
The scope in which the callback function(s) should run (i.e. what this will mean inside the callback function(s)). By default, thisinside the callback function(s) refers to the object originally passed to $.ajax().
data
The data to be sent to the server. This can either be an object or a query string, such as foo=bar&baz=bim.
dataType
The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.
error
A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.
success
A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the dataType was JSON), as well as the text status of the request and the raw request object.
timeout
The time in milliseconds to wait before considering the request a failure.
type
The type of the request, "POST" or "GET". Defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all browsers.
url
The URL for the request.
How check ajax run : Press F12 or open firebug;
Click on all to get the whole details.


Now click on link & click on param to view send data.


Now click on response to view response data


How to decode JSON string in PHP?
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($array);

How to create JSON from php array?
$string='[{"name":"Sudhir ","Address":"AZAMGARH"},{"name":"Pandey","Address":"LUCKNOW"}]';
$data = json_decode($string);

How to convert JSON Object into PHP Object?
$string='[{"name":"Sudhir ","Address":"AZAMGARH"},{"name":"Pandey","Address":"LUCKNOW"}]';
$data = json_decode($string,false);
print_r($data);

How to convert JSON Object into PHP Array?
$string='[{"name":"Sudhir ","Address":"AZAMGARH"},{"name":"Pandey","Address":"LUCKNOW"}]';
$data = json_decode($string,true);

print_r($data);

Comments

Popular posts from this blog

Generate XML file in Cakephp

Steps to Generate XML file using CakePHP: Step-1 Enable to parse xml extension in config route.php file.     Router::parseExtensions('xml'); Step-2 Add Request Handler Component to the Controller    var $components = array(‘RequestHandler’); Step-3 Add controller Action For XML Generation in Post Controller     function generateXMLFile()     {         if ($this->RequestHandler->isXml()) { // check request type             $this->layout = 'empty'; // create an empty layout in app/views/layouts/empty.ctp              }        }  Add header code in empty layout <?php header('Content-type: text/xml');?> <?php echo $this->Xml->header(); ?> <?php echo $content_for_layout; ?> Step-4 Set up View To generate XML Create xml folder inside Posts vi...

Simple JavaScript Object and Class Examples

In JavaScript, most things are objects. An object is a collection of related data and/or functionality Namespace: Everything you create in JavaScript is by default global. In JavaScript namespace is Global object . How to create a namespace in JavaScript? Create one global object, and all variables, methods, and functions become properties of that object. Example:  // global namespace var MYAPP = MYAPP || {}; Explaination: Here we first checked whether MYAPP is already defined.If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP How to create sub namespaces? // sub namespace MYAPP.event = {}; Class JavaScript is a prototype-based language and contains no class statement.JavaScript classes create simple objects and deal with inheritance. Example: var Person = function () {}; Explaination: Here we define a new class called Person with an empty constructor. Use the class keyword class Calculation {}; A class expr...

How to Add Next Previous links to The Event Calendar

Add Next/Previous links to The Event Calendar Wordpress Plugin Add code to your child theme’s functions.php file /**  * Allows visitors to page forward/backwards in any direction within month view */ if ( class_exists( 'Tribe__Events__Main' ) ) { class ContinualMonthViewPagination {     public function __construct() {         add_filter( 'tribe_events_the_next_month_link', array( $this, 'next_month' ) );         add_filter( 'tribe_events_the_previous_month_link', array( $this, 'previous_month' ) );     }     public function next_month() {         $url = tribe_get_next_month_link();         $text = tribe_get_next_month_text();         $date = Tribe__Events__Main::instance()->nextMonth( tribe_get_month_view_date() );         return '<a data-month="' . $date . '" href="' . $url . '" rel="next"...