{"id":496,"date":"2019-02-13T16:16:58","date_gmt":"2019-02-13T16:16:58","guid":{"rendered":"https:\/\/dapliw.org.ve\/?p=496"},"modified":"2019-02-13T16:16:58","modified_gmt":"2019-02-13T16:16:58","slug":"wordpress-wp-rest-api-v2-crud-con-jquery-ajax","status":"publish","type":"post","link":"https:\/\/saemas.com\/sitio_web\/wordpress-wp-rest-api-v2-crud-con-jquery-ajax\/","title":{"rendered":"WordPress &#8211; WP REST API v2, CRUD usuarios con Jquery Ajax"},"content":{"rendered":"<p>Para crear, leer, actualizar y eliminar usuarios de WordPress (<strong>C<\/strong>reate, <strong>R<\/strong>ead, <strong>U<\/strong>pdate y <strong>D<\/strong>elete) usando la WP REST API v2 desde un script Jquery Ajax procedemos a:<\/p>\n<ul>\n<li>En el documento Html creamos los botones que har\u00e1n la llamada a Jquery Ajax:<\/li>\n<pre>\n&lt;a href=\"#\" id=\"create\" class='btn btn-info'&gt;Create&lt;\/a&gt;\n&lt;a href=\"#\" id=\"read\" class='btn btn-info'&gt;Read&lt;\/a&gt;\n&lt;a href=\"#\" id=\"update\" class='btn btn-info'&gt;Update&lt;\/a&gt;\n&lt;a href=\"#\" id=\"delete\" class='btn btn-info'&gt;Delete&lt;\/a&gt;\n<\/pre>\n<li>En el script agregamos la funci\u00f3n de encriptaci\u00f3n base64:<\/li>\n<pre>\n\/**\n*\n*  Base64 encode \/ decode\n*  http:\/\/www.webtoolkit.info\/\n*\n**\/\nvar Base64 = {\n\n\/\/ private property\n_keyStr : \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=\",\n\n\/\/ public method for encoding\nencode : function (input) {\n    var output = \"\";\n    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n    var i = 0;\n\n    input = Base64._utf8_encode(input);\n\n    while (i < input.length) {\n\n        chr1 = input.charCodeAt(i++);\n        chr2 = input.charCodeAt(i++);\n        chr3 = input.charCodeAt(i++);\n\n        enc1 = chr1 >> 2;\n        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n        enc4 = chr3 & 63;\n\n        if (isNaN(chr2)) {\n            enc3 = enc4 = 64;\n        } else if (isNaN(chr3)) {\n            enc4 = 64;\n        }\n\n        output = output +\n        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +\n        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);\n\n    }\n\n    return output;\n},\n\n\/\/ public method for decoding\ndecode : function (input) {\n    var output = \"\";\n    var chr1, chr2, chr3;\n    var enc1, enc2, enc3, enc4;\n    var i = 0;\n\n    input = input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g, \"\");\n\n    while (i < input.length) {\n\n        enc1 = this._keyStr.indexOf(input.charAt(i++));\n        enc2 = this._keyStr.indexOf(input.charAt(i++));\n        enc3 = this._keyStr.indexOf(input.charAt(i++));\n        enc4 = this._keyStr.indexOf(input.charAt(i++));\n\n        chr1 = (enc1 << 2) | (enc2 >> 4);\n        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);\n        chr3 = ((enc3 & 3) << 6) | enc4;\n\n        output = output + String.fromCharCode(chr1);\n\n        if (enc3 != 64) {\n            output = output + String.fromCharCode(chr2);\n        }\n        if (enc4 != 64) {\n            output = output + String.fromCharCode(chr3);\n        }\n\n    }\n\n    output = Base64._utf8_decode(output);\n\n    return output;\n\n},\n\n\/\/ private method for UTF-8 encoding\n_utf8_encode : function (string) {\n    string = string.replace(\/\\r\\n\/g,\"\\n\");\n    var utftext = \"\";\n\n    for (var n = 0; n < string.length; n++) {\n\n        var c = string.charCodeAt(n);\n\n        if (c < 128) {\n            utftext += String.fromCharCode(c);\n        }\n        else if((c > 127) && (c < 2048)) {\n            utftext += String.fromCharCode((c >> 6) | 192);\n            utftext += String.fromCharCode((c & 63) | 128);\n        }\n        else {\n            utftext += String.fromCharCode((c >> 12) | 224);\n            utftext += String.fromCharCode(((c >> 6) & 63) | 128);\n            utftext += String.fromCharCode((c & 63) | 128);\n        }\n\n    }\n\n    return utftext;\n},\n\n\/\/ private method for UTF-8 decoding\n_utf8_decode : function (utftext) {\n    var string = \"\";\n    var i = 0;\n    var c = c1 = c2 = 0;\n\n    while ( i < utftext.length ) {\n\n        c = utftext.charCodeAt(i);\n\n        if (c < 128) {\n            string += String.fromCharCode(c);\n            i++;\n        }\n        else if((c > 191) && (c < 224)) {\n            c2 = utftext.charCodeAt(i+1);\n            string += String.fromCharCode(((c &#038; 31) << 6) | (c2 &#038; 63));\n            i += 2;\n        }\n        else {\n            c2 = utftext.charCodeAt(i+1);\n            c3 = utftext.charCodeAt(i+2);\n            string += String.fromCharCode(((c &#038; 15) << 12) | ((c2 &#038; 63) << 6) | (c3 &#038; 63));\n            i += 3;\n        }\n\n    }\n\n    return string;\n}\n}\n<\/pre>\n<li>Adem\u00e1s agregamos en el script las llamadas Ajax para Create, Read, Update y Delete:<\/li>\n<pre>\n$(document).ready(function(){\n    \/\/ Create\n    $('#create').click(function(e) \n    {        \n        $.ajax({\n            url: 'https:\/\/midominio.com\/wp-json\/wp\/v2\/users',\n            type: 'POST',\n            crossDomain: true,\n            beforeSend: function ( xhr ) {\n                xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'usuario:password' ) );\n            },\n            data: {username: 'pedroperez', password : 'pedro123', email : 'pedro@gmail.com', first_name : 'Pedro', last_name : 'P\u00e9rez'},\n            success: function( data, txtStatus, xhr ) {\n                console.log( data.username );\n                console.log( xhr.status );\n            },\n            error: function (xhr, ajaxOptions, thrownError) {\n                console.log(xhr.status);\n                console.log(thrownError);\n            }\n        }); \n    });\n\n    \/\/ Read\n    $('#read').click(function(e) \n    {\n        $.ajax({\n            url: 'https:\/\/midominio.com\/wp-json\/wp\/v2\/users\/10',\n            type: 'GET',\n            crossDomain: true,\n            beforeSend: function ( xhr ) {\n                xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'usuario:password' ) );\n            },\n                success: function( data, txtStatus, xhr ) {\n                console.log( data.name );\n                console.log( data);\n                console.log( xhr.status );\n            },\n            error: function (xhr, ajaxOptions, thrownError) {\n                console.log(xhr.status);\n                console.log(thrownError);\n            }\n        });\n    ;});\n\n    \/\/ Update\n    $('#update').click(function(e) \n    {\n        $.ajax({\n            url: 'https:\/\/midominio.com\/wp-json\/wp\/v2\/users\/10',\n            type: 'PUT',\n            crossDomain: true,\n            beforeSend: function ( xhr ) {\n                xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'usuario:password' ) );\n            },\n            data: {name: 'Pedro Santaella'},\n            success: function( data, txtStatus, xhr ) {\n                console.log( data.username );\n                console.log( xhr.status );\n            },\n            error: function (xhr, ajaxOptions, thrownError) {\n                console.log(xhr.status);\n                console.log(thrownError);\n            }\n        });\n    });\n\n    \/\/ Delete \n    $('#delete').click(function(e) \n    {\n        $.ajax({\n            url: 'https:\/\/midominio.com\/wp-json\/wp\/v2\/users\/10',\n            method: 'DELETE',\n            crossDomain: true,\n            beforeSend: function ( xhr ) {\n                xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'usuario:password' ) );\n            },\n            data: {force : 'true', reassign : 1},\n            success: function( data, txtStatus, xhr ) {\n                console.log( data );\n                console.log( xhr.status );\n            },\n            error: function (xhr, ajaxOptions, thrownError) {\n                console.log( xhr.status );\n                console.log( thrownError );\n            }\n        });     \n    });\n});\n<\/pre>\n<li>En la operaci\u00f3n Delete se deben pasar en la variable data los par\u00e1metros: 'force' : true y 'reassign' : idDelUsuarioAlCualSeLeAsignaranLosPostDelUsuarioQueSePretendeEliminar<\/li>\n<ul>\n","protected":false},"excerpt":{"rendered":"<p>Para crear, leer, actualizar y eliminar usuarios de WordPress (Create, Read, Update y Delete) usando la WP REST API v2 desde un script Jquery Ajax procedemos a: En el documento Html creamos los botones que har\u00e1n la llamada a Jquery Ajax: &lt;a href=\u00bb#\u00bb id=\u00bbcreate\u00bb class=&#8217;btn btn-info&#8217;&gt;Create&lt;\/a&gt; &lt;a href=\u00bb#\u00bb id=\u00bbread\u00bb class=&#8217;btn btn-info&#8217;&gt;Read&lt;\/a&gt; &lt;a href=\u00bb#\u00bb id=\u00bbupdate\u00bb class=&#8217;btn [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"material-hide-sections":[],"footnotes":""},"categories":[21],"tags":[22],"class_list":["post-496","post","type-post","status-publish","format-standard","hentry","category-wordpress","tag-wordpress"],"_links":{"self":[{"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/posts\/496","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/comments?post=496"}],"version-history":[{"count":0,"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/posts\/496\/revisions"}],"wp:attachment":[{"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/media?parent=496"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/categories?post=496"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/saemas.com\/sitio_web\/wp-json\/wp\/v2\/tags?post=496"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}