简体   繁体   中英

Get data using POST and AJAX

I'm trying to send some data in my server asynchronously using AJAX. I need to send the data using the POST method because the data sent are quite many characters and by using GET the created URL will be too big. Well that's not a problem, but for aesthetically reasons I would rather have small URLs. In order to do so I used the solution (question) explained here .

My Javascript code sending the data is:

   var code = "code=" + document.getElementById("code_area").value;
   xmlhttp.open("POST", "run_code.php", true);
   xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xmlhttp.send(code);

The above code is executed when I click a button, but then the URL changes to this: localhost/code.php?code=datadatadatadatadatadatadatadatadatadatadatadatadatadata which seems is no different of using GET instead (my URL has become quite big). I used POST , not GET but still data seems to get transmitted by the URL. Any ideas why is this happening?

You could do that much more easily using jQuery.

$.post("run_code.php", { code: $("#code_area").val() });

Links:

Way easier with jquery...

$.post( 'yoururlhere.com/phppage',
        {code:$("#code_area").val()},
        function(responseData){
            // responseData is the echo'd data set from your php page
        }, 'json'
);

the data within { } are the post KV pairs

responseData is the dataset echo'd back from php

The problem after all was that I was using a submit input field in my HTML page like this:

<input type="submit" />

which when used changed (refreshed) the URL.

By using:

<input type="button" />

the problem has been fixed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM