2

I have written a javascript to post data to a server. This seems to be working but I'm having trouble catching the servers response in iframe. I want to catch the servers response in iframe or in a datastream without forwarding to a other page or refreshing but i will settle with just stopping the page from being forwarded or refreshed.

I have tried adding target="my_frame" to the button and the form attributes but it doesn't seem to work.

My code, I slightly modified my code for presentation:

 <html>
  <head>

    <title>post</title>

  </head>
  <body>

<script language="javascript">

   var myDictionary = [];
    myDictionary["username"] = "stackoverflow";
    myDictionary["password"] = "mypassword";


function post(dictionary, url, method) {
    method = method || "post"; 

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", url);

    for (key in dictionary) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden"); 
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", dictionary[key]);
        form.appendChild(hiddenField); 
    }

    document.body.appendChild(form); 
    form.submit();
}
</script>

<input type="button" target="my_frame" value="Submit" onclick="javascript:post(myDictionary, 'http://www.website.com/register/registernow');" />

    <iframe name="my_frame" src="">

  </body>
</html>

Thanks for reading and for all replies.

2
  • add target="<id of iframe>" to the form and id="<id of iframe>" to the iframe, after the form was submitted you can catch the »load« event of the iframe Commented Jan 17, 2013 at 18:40
  • I added id="my_Frame" to the iframe and form.setAttribute('target', 'my_Frame'). Now the servers response opens in a new tab. I have also tried adding target="my_Frame" to the button but it does nothing. Commented Jan 17, 2013 at 19:47

1 Answer 1

1

What you are looking for is an Ajax POST.

You don't need to create a form and submit it, instead you need XMLHttpRequest, or if you are using jquery you can use $.post or $.ajax.

See for example http://blog.mgechev.com/2011/07/21/ajax-jquery-beginners/

Sign up to request clarification or add additional context in comments.

1 Comment

If I understood your question - then you are doing it wrong... orm submit will not give you the server response and will trigger a page redirect. You want Ajax to get the server response in javascript without redirecting. I really recommend jquery to do it, but it appears you are not using jquery so the article I linked to shows both jquery and non-jquery ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.