|
| 1 | + |
| 2 | +//POST REQUEST |
| 3 | + |
| 4 | +$(document).ready(function(){ |
| 5 | + $('#postMessage').click(function(e){ |
| 6 | + e.preventDefault(); |
| 7 | + |
| 8 | + //serialize form data |
| 9 | + var url = $('form').serialize(); |
| 10 | + |
| 11 | + //function to turn url to an object |
| 12 | + function getUrlVars(url) { |
| 13 | + var hash; |
| 14 | + var myJson = {}; |
| 15 | + var hashes = url.slice(url.indexOf('?') + 1).split('&'); |
| 16 | + for (var i = 0; i < hashes.length; i++) { |
| 17 | + hash = hashes[i].split('='); |
| 18 | + myJson[hash[0]] = hash[1]; |
| 19 | + } |
| 20 | + return JSON.stringify(myJson); |
| 21 | + } |
| 22 | + |
| 23 | + //pass serialized data to function |
| 24 | + var test = getUrlVars(url); |
| 25 | + |
| 26 | + //post with ajax |
| 27 | + $.ajax({ |
| 28 | + type:"POST", |
| 29 | + url: "/Work folders/OOP php/RESTFUL traversy/php_rest_myblog/api/post/create.php", |
| 30 | + data: test, |
| 31 | + ContentType:"application/json", |
| 32 | + |
| 33 | + success:function(){ |
| 34 | + alert('successfully posted'); |
| 35 | + }, |
| 36 | + error:function(){ |
| 37 | + alert('Could not be posted'); |
| 38 | + } |
| 39 | + |
| 40 | + }); |
| 41 | + }); |
| 42 | +}); |
| 43 | + |
| 44 | + |
| 45 | +//GET REQUEST |
| 46 | + |
| 47 | + document.addEventListener('DOMContentLoaded',function(){ |
| 48 | + document.getElementById('getMessage').onclick=function(){ |
| 49 | + |
| 50 | + var req; |
| 51 | + req=new XMLHttpRequest(); |
| 52 | + req.open("GET", '/Work folders/OOP php/RESTFUL traversy/php_rest_myblog/api/post/read.php',true); |
| 53 | + req.send(); |
| 54 | + |
| 55 | + req.onload=function(){ |
| 56 | + var json=JSON.parse(req.responseText); |
| 57 | + |
| 58 | + //limit data called |
| 59 | + var son = json.filter(function(val) { |
| 60 | + return (val.id >= 4); |
| 61 | + }); |
| 62 | + |
| 63 | + var html = ""; |
| 64 | + |
| 65 | + //loop and display data |
| 66 | + son.forEach(function(val) { |
| 67 | + var keys = Object.keys(val); |
| 68 | + |
| 69 | + html += "<div class = 'cat'>"; |
| 70 | + keys.forEach(function(key) { |
| 71 | + html += "<strong>" + key + "</strong>: " + val[key] + "<br>"; |
| 72 | + }); |
| 73 | + html += "</div><br>"; |
| 74 | + }); |
| 75 | + |
| 76 | + //append in message class |
| 77 | + document.getElementsByClassName('message')[0].innerHTML=html; |
| 78 | + }; |
| 79 | + }; |
| 80 | + }); |
| 81 | + |
0 commit comments