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

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

Integrating Kafka with Node.js

Integrating Kafka with Node.js Apache Kafka is a popular open-source distributed event streaming platform that uses publish & subscribe mechanism to stream the records(data). Kafka Terminologies Distributed system: Distributed system is a computing environment where various software components located on different machines (over multiple locations). All components coordinate together to get stuff done as one unit.   Kafka Broker: Brokers are cluster of multiple servers. Message of each topic are split among the various brokers. Brokers handle all requests from clients to write and read events. A Kafka cluster is simply a collection of one or more Kafka brokers. Topics: A topic is a stream of "related" messages. Its unique throughout application. Kafka producers write messages to topics. Producer: Producer publishes data on the topics. A producer sends a message to a broker and the broker receives and stores messages. Consumers: Consumers read data from topics. A consu...