0

I wrote XMLhttpRequest function for making a ajax POST.When I add new job this function is called and added job is also shown in HTML.The code is below.

function req_add()
        {
            var hr = new XMLHttpRequest();
            var url = "To-Do.php";
            var content = document.getElementById("content").value;
            var vars = "content=" + content;

            hr.open("POST", url, true);
            hr.setRequestHeader("Content-type","application/x-www-form-
urlencoded");
            hr.onreadystatechange=function()
            {
                if(hr.readyState == 4 && hr.status == 200)
                {
                    var return_data = hr.responseText;
                    document.getElementById("result").innerHTML               
= return_data;
                }
            }
            hr.send(vars);
            document.getElementById("result").innerHTML =   

"Processing...";
        }

In advance I was using $.getJSON for GET operation.Now I want to write a function that both GET and POST requests can be done.The function will be like this=> makeRequest(type,params,URL) ,type is for POST and GET. There will be onsuccess function whether the data is returned successfully or not.And when I write common function will I use hr.send ()? Thanks.

ntf
  • 1,323
  • 2
  • 12
  • 17
  • 1
    if you use $.getJSON it mean then you use jQuery, why then you don't use $.ajax, $.get and $.post? – jcubic Mar 12 '13 at 19:29
  • @jcubic I must write a common function that both operation can be done. – ntf Mar 12 '13 at 19:32
  • 2
    You should really have a look at the [jQuery api](http://api.jquery.com) and especially at [$.ajax](http://api.jquery.com/jquery.ajax/) which is all you need – Andreas Mar 12 '13 at 19:35
  • Fully agree with Andreas. Writing straight javascript is a complete waste of time. Using JQuery functions is a lot better & easier than reinventing the wheel each time. – Sylverdrag Mar 12 '13 at 19:45
  • @ntf you can do both operations in $.ajax by toggling the setting the "type" option. – Matt Mar 12 '13 at 22:51

1 Answers1

-1

It is indeed possible and there's alot of info when you google it. Search for information about the XMLHttpRequest object and how it supports GET/POST requests and how to pass parameters.

And Yes: you can use a common XMLHttpRequest object (hr variable) and conditionally/switch for diffrent types of requests. Be sure to handle errors and events correctly, you are missing quite much right now.

You can find some info here to start with: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

EDIT below, this works on my local server, but there's much work to be done with the js. You should test the integrity of simultaneous requests for example...

Edited HTML:

<html>
    <head>
        <title>To-Do</title>
        <meta name="description" content="To-Do" charset="utf-8">
        </meta>
        <script language="javascript" type="text/javascript">
            function mr(type, URL) {

                var hr = new XMLHttpRequest();

                //SET UP VARS CORRECTLY FOR GET/POST
                var content = document.getElementById("content").value;
                var vars = "content=" + content;

                if (type == 'GET')
                    URL = URL + '?' + vars;

                //SET EVENTHANDLERS (THERE ARE ALOT MORE)
                hr.onreadystatechange = function() {
                    if (hr.readyState == 4 && hr.status == 200) {
                        var return_data = hr.responseText;
                        document.getElementById("result").innerHTML = return_data;
                    }

                }
                //OPEN THE REQUEST
                hr.open(type, URL, true);

                //SET HEADERS
                hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

                switch(type) {
                    case 'GET':
                        hr.send();
                        break;
                    case 'POST':
                        hr.send(vars);
                        break;
                }

                document.getElementById("result").innerHTML = "Processing...";

            }
        </script>
        <style type="text/css">
            button {
                cursor: pointer
            }
            div {
                color: #666;
                font: normal 13px "Trebuchet MS";
                width: 350px;
                padding: 10px
            }
        </style>
    </head>

    <body>
        <div>
            Add Item:
            <input type="text" name="name" id="content">
            <br>
            <button onclick="javascript:mr('POST','post.php');" type="button" id="btn1">
                Submit
            </button>
            <br>
            <button onclick="javascript:mr('GET','get.php');" type="button" id="btn2" >
                List Jobs
            </button>
            <div id="result"></div>
        </div>
    </body>
</html>

PHP files that return:

get.php

<?php echo "GET\n"; if(isset($_GET)) print_r($_GET); ?>

post.php

<?php echo "POST\n"; if(isset($_POST)) print_r($_POST); ?>
apelsinapa
  • 575
  • 3
  • 9
  • I read a lot but cannot find any helpful thing. I tried XMLhttpRequest for both GET and POST but seperately.I want to combine them. My whole code https://docs.google.com/document/d/1n4SSmdyGnuOPYJRSI5m25zHZc81yyYJQynmmskAkDs4/edit?usp=sharing. – ntf Mar 13 '13 at 15:02
  • If you have a working one for POST it shouldn't be too hard. How does it fail? What happends in the code when you step-debug? When i do this, I just initilize the XMLHttpRequest, then xhr.open(type, url, true); (independent of GET/POST), prepare the variables. That code you sent, it looks like you open the request after you send it. Try this order: Initilize XMLHttpRequest, bind Events, Open the request, Send the request... – apelsinapa Mar 13 '13 at 16:01
  • I tried what you said and in that order.In this case, Get was successful but Post was not.I write the updated code, mr funtion, please look at it. https://docs.google.com/document/d/1n4SSmdyGnuOPYJRSI5m25zHZc81yyYJQynmmskAkDs4/edit?usp=sharing – ntf Mar 13 '13 at 17:08
  • 1
    I will edit my post, i've edited what you have. I will not go into your php. But your javascript was working, and you should learn how to debug. I've made minimal adjustments and tested locally. – apelsinapa Mar 13 '13 at 17:43
  • you can debug javascript in almost any browser... Latest versions of Chrome, firefox, ie has built in debuggers...http://stackoverflow.com/questions/66420/how-do-you-launch-the-javascript-debugger-in-google-chrome – apelsinapa Mar 13 '13 at 17:56
  • Your code works successfully with get.php and post.php.However, according to my To-Do.php it doesn't work.:/ – ntf Mar 13 '13 at 18:27
  • 1
    Then you have some trouble with that file. Figure out what. Make sure not to use GET or POST variables without checking if they exist with isset($_GET['variable']). Also make sure the variable contains something that you can use for your purpose. If you want a better answer you should explain why it isn't working, and where it fails. – apelsinapa Mar 13 '13 at 18:32