jQuery posting JSON
Asked Answered
A

4

221

update: I would like to pass the var value to the server

hello, same old, same old ... :)

I have a form called <form id="testForm" action="javascript:test()"> and a code area called <code id="testArea"></code>

I am using this code to stringify and display the data in the code area:

var formData = form2object('testForm');
document.getElementById('testArea').innerHTML = JSON.stringify(formData, null, '\t');
var value = JSON.stringify(formData, null, '\t');

What I want is to send this data to a JSON file. I've been working on this project : http://ridegrab.com/profile_old/ and if you press Submit Query button you will see the head of the page populate.

Also I want use this piece of script to send data:

    function authenticate(userName, password) {
    $.ajax
    ({
        type: "POST",
        //the url where you want to sent the userName and password to
        url: 'username:password@link to the server/update',
        dataType: 'json',
        async: false,
        //json object to sent to the authentication url
        data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
        success: function () {

        alert("Thanks!"); 
        }
    })
}

Again, all I want is to be able to send that JSON data to the server. My server is set up to update or POST the data in the right place.

Alcoholic answered 6/4, 2011 at 17:49 Comment(3)
i can't make it work :) i don't know how to put them together to send that data to the server... even if i replace data with data: value,...!!??Alcoholic
Firstly, are you certain it's not a connection issue? If you assign an error function, does it get called? If so, with what error?Tremendous
Though it's over a year old, I'll answer @Patrioticcow's latest question about how to do that. You see the "success" option that you sent into the ajax method? Do the same thing with "error." As in "error: MyErrorHandlingFunction" or "error: function(error) { [Error handling code here] }"Whitfield
W
251

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type header:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting JSON to webservice

Wellrounded answered 6/4, 2011 at 18:19 Comment(7)
@tasos I think this is what you're after: #5807471Wellrounded
Echoing the incorrectness here; this will work OK for simple scenarios, but the url-encoded message can be very problematic, especially for arrays of stuff.Ecospecies
@Ecospecies and Jonas N - Can you guys help me figure out how to update my answer for correctness? The examples in the jQuery docs (here: api.jquery.com/jQuery.post) make it appear as though you can post either a JS object or a string, which led me to believe that jQuery would handle all of the necessary string serialization.Wellrounded
Patrioticcow said: "what if i want to send the json from var value" Unless the value is an array or an object this is not valid JSON.Peder
Consider what happens when your data contains, for instance, a list of things: { foo: [1,2,3], bar: 'baz' }. This will get form-encoded as foo%5B%5D=1&foo%5B%5D=2&foo%5B%5D=3&bar=baz (unescaped, it's foo[]=1&foo[]=2&foo[]=3&bar=baz). Likely not what you want server-side.Ecospecies
That won't quite work if you want to post JSON to a REST service, because jQuery will be posting the content as 'application/x-www-form-urlencoded; charset=UTF-8', while most REST services would be expecting 'application/json'; @teknopaul's answer would work much better in that case.Tetrastichous
A "stringified JavaScript object" is a plain String objectWengert
E
296

You post JSON like this

$.ajax(url, {
    data : JSON.stringify(myJSObject),
    contentType : 'application/json',
    type : 'POST',
    ...

if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want

Erudition answered 2/11, 2012 at 23:41 Comment(0)
W
251

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type header:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting JSON to webservice

Wellrounded answered 6/4, 2011 at 18:19 Comment(7)
@tasos I think this is what you're after: #5807471Wellrounded
Echoing the incorrectness here; this will work OK for simple scenarios, but the url-encoded message can be very problematic, especially for arrays of stuff.Ecospecies
@Ecospecies and Jonas N - Can you guys help me figure out how to update my answer for correctness? The examples in the jQuery docs (here: api.jquery.com/jQuery.post) make it appear as though you can post either a JS object or a string, which led me to believe that jQuery would handle all of the necessary string serialization.Wellrounded
Patrioticcow said: "what if i want to send the json from var value" Unless the value is an array or an object this is not valid JSON.Peder
Consider what happens when your data contains, for instance, a list of things: { foo: [1,2,3], bar: 'baz' }. This will get form-encoded as foo%5B%5D=1&foo%5B%5D=2&foo%5B%5D=3&bar=baz (unescaped, it's foo[]=1&foo[]=2&foo[]=3&bar=baz). Likely not what you want server-side.Ecospecies
That won't quite work if you want to post JSON to a REST service, because jQuery will be posting the content as 'application/x-www-form-urlencoded; charset=UTF-8', while most REST services would be expecting 'application/json'; @teknopaul's answer would work much better in that case.Tetrastichous
A "stringified JavaScript object" is a plain String objectWengert
B
2

In case you are sending this post request to a cross domain, you should check out this link.

https://mcmap.net/q/98314/-why-am-i-getting-an-options-request-instead-of-a-get-request

Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

Battle answered 26/1, 2016 at 1:41 Comment(0)
P
-2

Post async function with event.

//---------------------Buffers <0-9>--------------------- 
var gBuffer=[];

function GetBuffer(pIndex=0) {
    if (pIndex<0 || pIndex>9) {
        console.log('Error, pIndex out of interval <0,9>');
        return null;
    }
    if (gBuffer.length<10) {gBuffer.length=10;}
    return gBuffer[pIndex];
}

function SetBuffer(pIndex=0, pJson="") {
    if (pIndex>=10 || pIndex<0) { 
        console.log('Error, pIndex out of interval <0,9>');
        return null;
    } 
    if (gBuffer.length<10) {gBuffer.length=10;}
    return gBuffer[pIndex]=pJson;
}

//---------------------Post and generate event--------------------- 

function sleep(ms=3) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function gWait(pIndex=0, pTimeoutSec=10, pEventTag="html", pEventName="PostEvent" ) {  // async, generate event 
    if (pIndex<0 || pIndex>9) {
        console.log('Error, pIndex out of interval <0,9>');
        return;
    }
    var i=0;
    console.log('gWait start');
    while (i < 25*pTimeoutSec && GetBuffer(pIndex)==null) {
      await sleep(40);
      i++;
    }
    if (i>=25*pTimeoutSec)  {
      SetBuffer(pIndex,'{"error":"SRV error. Fetch timeout ('+pTimeoutSec+' sec)"}');
    }
    console.log('gWait stop, iteration:'+i+'/'+25*pTimeoutSec);
    $(pEventTag).trigger(pEventName,pIndex); //generate event
}

async function Post(pJSON="", pIndex=0, pTimeoutSec=10, pEventTag="html", pEventName="PostEvent") { //send JSON and return response to gArray[pIndex]
    if (pIndex<0 || pIndex>9) {
        console.log('Error, pIndex out of interval <0,9>');
        return;
    }
    var js=Trim(pJSON);
    if (js=="") { js="{}"; } //empty JSON   
    SetBuffer(pIndex,null);
    try {
        if (pTimeoutSec>0) {gWait(pIndex,pTimeoutSec,pEventTag,pEventName);} //timeout controll, and generate event
        var resp=await fetch("ajax",   //url to server example: "http://localhost:8081/api/services/tags/"
        {   method: "POST",
            headers: {"Content-Type": "application/json; charset=utf-8" },
            body: js,
            async: true,
        })
        if (resp.status==200) {
            const result= await resp.json();
            SetBuffer(pIndex,JSON.stringify(result));
        } else {
            SetBuffer(pIndex,'{"error":"SRV error. '+resp.status+'"}');   
        }
    }
    catch (err) {
       SetBuffer(pIndex,'{"error":"SRV error. Failed to fetch."}');
    }  
    if (pTimeoutSec<=0) { $(pEventTag).trigger(pEventName,pIndex);} //generate event
}

$(document).ready(function(){
   alert('ok');
   $("html").on("PostEvent", function(event,msg){ 
      console.log(event.type+' gBuffer['+msg+']:'+GetBuffer(msg));
   });
   
   $("form").submit(function (event) {
       event.preventDefault();
       Post('{"hello":""}');  //JSON post
       event.preventDefault();
    });
});
    
Pterodactyl answered 24/7, 2023 at 18:14 Comment(2)
The mentioned solution also deals with the error when there is no connection (ERR_CONNECTION_REFUSED). It also allows you to set a load timeout for all browsers if needed. It's just a part of the code that I debugged through my own GO server. The only shortcoming is the global variable, which could also be removed, but I think it has certain advantages.Pterodactyl
When to use try-catch vs async functions, here is an article about it: javascript.plainenglish.io/…Pterodactyl

© 2022 - 2024 — McMap. All rights reserved.