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...

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]');

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string Using PHP $string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world.  CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg   CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be'; $string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string); Using Javascript <script> function linkify(inputText) {     var replacedText, replacePattern1, replacePattern2, replacePattern3;     //URLs starting with http://, https://, or ftp://     replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;     replacedText = inputT...