Submit a form and get a JSON response without jQuery

jquery ajax
onsubmit get form data
html form post json example
react ajax post form
form submit json without ajax
how to submit form data to a restful api in react
react form post
javascript post form data

I have a simple HTML form like this:

            <div class="border-little text-center grey">
                <form action="https://www.THIS IS MY URL.php" method="get">
                    <input name="player" id="player" value="1" class="hidden">
                    <label for="number">Enter a number</label>
                    <input type="text" id="number" name="number" placeholder="">
                    <input type="submit" value="Submit">
                </form>
            </div>

The operation is as follows: The player enters a number, and the server answers using a JSON format.

My issue: When I press "submit" My webpage leaves and redirects to the server page display a JSON formatted answer.

What I want to do: I want to stay on my page and be able to receive the answer in JSON format and display them below my form instead of being redirected to the server page.

More details: example of JSON answer I get from the server:

{"guess": "lower"}

I cannot use any kind of JavaScript library so JQuery is forbidden.

you just use ajax method of js

function r_submit() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.THIS IS MY URL.php", true);
var params = {"player":document.getElementById("player").value};
xhttp.send(params);
xhttp.onload = function() {
    alert(xhttp.responseText);
}
} 

and execute r_submit() function button when you click button

here your html code will be like

 <div class="border-little text-center grey">
                <input name="player" id="player" value="1" class="hidden">
                <label for="number">Enter a number</label>
                <input type="text" id="number" name="number" placeholder="">
                <input type="submit" value="Submit" onsubmit='r_submit()'>
            </form>
        </div>

Submit Form in React without jQuery AJAX, Submit Form in React without jQuery AJAX The json() method resolves the response data to JSON object. Let's Get Back to React. If you want to get the response in a callback, you can't post the form. Posting the form means that the response is loaded as a page. You have to get the form data from the fields in the form and make an AJAX request.

i've written years ago a simple js part, that allows you to send XHR requests easily. it's a little deprecated but it is a simple template to understand how you CAN go on. you could modernize it by using webworkers and make it closer to your setup. if you wish i could post an old prototype in JS from me with webworkers and so on (but some names of variables are in german..)

function getElement(inp)
{
    return document.getElementById(inp);
}

function put(data,div)
{
    getElement(div).innerHTML = data;
}

//information: autoput means: do you wish to write the raw response in a div? [0,1] - when 1 then put the id of the div in var div at the call of the function
function get(url,data,method,autoput,div)
{
    var req;
    if(window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
    }
    else
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    req.onreadystatechange = function()
    {
        if(req.readyState == 4 && req.status == 200)
        {
            if(autoput == 1)
            {
                put(req.responseText, div);
            }
        }
    }

    if(method.toLowerCase() == "get")
    {
        req.open("GET",url+data,true);
        req.send();
    }
    else
    {
        if(method.toLowerCase() == "post")
        {
            if(data !== "")
            {
                req.open("POST", url, true);
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.send(data);
            }
        }
    }
}

Sending forms through JavaScript, HTML forms to send data without loading a new document when response data is received. Standard HTML form submission, as described in the previous article, object can build HTTP requests, send them, and retrieve their results. But neither XML nor JSON fit into form data request encoding. Turning a form element into JSON and submiting it via jQuery By DeveloperDrive Staff Continuing on with our work on creating a To Do Application , this weeks snippet is on how to submit a form using jQuery.

It's possible to use iframe technique when jQuery is forbidden. Submit the form to the named iframe and wait for onload event. Modified html and js code will look like:

<div class="border-little text-center grey">
    <form action="https://www.THIS IS MY URL.php" method="get" target="myframe">
        <input name="player" id="player" value="1" class="hidden">
        <label for="number">Enter a number</label>
        <input type="text" id="number" name="number" placeholder="">
        <input type="submit" value="Submit">
    </form>
</div>
<iframe id="myframe" name="myframe"></iframe>


<script>
    var myframe = document.getElementById("myframe");
    myframe.onload = function() {
        var iframeDocument = myframe.contentDocument || myframe.contentWindow.document; // get access to DOM inside the iframe
        var content = iframeDocument.textContent || iframeDocument.body.textContent; // get text of iframe
        var json = JSON.parse(content);

        if (json && json.guess) {
            // process the json here
            alert(json.guess);
        }
    }
</script>

A Guide to Vanilla Ajax Without jQuery, If POST-ing the request (here we are using GET), this parameter should contain views/index.html <h1>Vanilla Ajax without jQuery</h1> <button contains the server response when all I'm working with is plain old JSON. Basically we have a submit event that fires when a button is clicked. Next we take the value of the button clicked and send it to serverside.php with jQuery’s ajax()-function. From this function we get back our JSON data which we’ll process on success. After that it’s simple if and else to append our #wines div.

Submitting standard web forms with Ajax and JSON, Tutorial on how to submit a web form using AJAX without refreshing the In older version of jQuery you will have to evaluate JSON object as a  It is also passed the text status of the response. As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

AJAX without jQuery, When was the last time you did it without relying on jQuery? This object is the descendant of the ActiveX object which Microsoft Well the XMLHttpRequest doesn't really have the concept of JSON, Most likely you're going to be POST-​ing data from a form, and to do that you can use the FormData API. Ajax forms are the integral part of web technology today. It makes sending HTTP requests very easy, no page reloads and it's fast, it can send-receive information in a various formats such as HTML, JSON or XML. Let's learn various ways to send HTML form data using jQuery Ajax. jQuery has various shorthand Methods to jQuery.ajax (), such as .get

Ajax Requests – You Don't Need jQuery! – Free yourself from the , GETting; POSTing; URL Encoding; JSON; Uploading; CORS; JSONP with the relatively simple XMLHttpRequest object, the answer is probably “no”. and older is by submitting a <form> that contains an <input type="file"> . Depending on the browser, the Enter key may only cause a form submission if the form has exactly one text field, or only when there is a submit button present. The interface should not rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key.

Comments
  • stackoverflow.com/questions/8567114/… ajax is one of those things that are significantly less verbose using a help library.
  • Add named iframe tag below the form and submit the form to this iframe by name. <form action="THIS IS MY URL.php" method="get" target="myframe">... <iframe name="myframe"></iframe>
  • @AlexS. the iframe is a really good Idea thank you a lot it works, by the way do you have an idea how to check the answers and do something if the number in the right one like when I receive {"guess": "YouWon!"}
  • To process json from iframe in main window get it contents by the following way: var myframe = document.getElementsByTagName("iframe")[0], content = (myframe.contentDocument || myframe.contentWindow.document).textContent, json = JSON.parse(content);
  • I am sorry @AlexS. I don't understand what you did on the comment above, can you please give me more details ?
  • I am sorry it doesn't work @manan5439 maybe can you give me more details about what were you trying to do ?