Search code examples
javascriptjqueryjsonechojsfiddle

How to use JSfiddle echo feature in javascript?


Below JS fiddle is the sample echo feature done onload of the page. We are getting the value 1 from the json response.

JSFiddle

And, I'm trying to add username and emailid and get back the response. But I'm getting an error like

{"error":"key missing: title"}

This is my fiddle OwnJSFiddle

Can someone help on this to fix this issue? I wanted to add name and emailid through echo/json and get the response and show in html.


Solution

  • I have found a solution yet I had to modify your code to work a little differently.

    jQuery Version

    JSFiddle

    In this fiddle, I add a submit event listener to your form.

    I use e.preventDefault() to prevent default submit action.

    Later, I use JSON.stringify() on your JSON object.


    Vanilla JS Version

    JSFiddle

    In this fiddle, I used XHR request to achieve the same thing.

    If using XHR requests for /echo/json/ you need to use the application/x-www-form-urlencoded header and stringify the parameters into the URL even though it's a POST request.


    I'd say the issue was that you were trying to POST via $.ajax() and submit at the same time.