How to convert a GET request to POST - javascript

I don't know if it is possible or not. I referred some site, but I didn't get exact answer.
I am using
click
When I send this request to server in the response page easily I can see "id=4" in address bar, obviously which is not secure, But in post request we cant see this.
So can we convert a get request to post or ant other way is there to hide this from address bar.
Thanks in advance.

Firstly, to convert GET to POST, simply change the link to a form:
<form id="myForm" action="xyz" method="post">
<input type"hidden" name="id" value="4"/>
</form>
This form will not be visible and you can easily auto-submit it using JavaScript in your link:
click
Secondly and more importantly, both GET and POST are equally not secure over HTTP. To secure them, use HTTPS and they will be both equally secure, so no need to change if GET is working for you.

click
Dynamically create a from and post it.
function postForm() {
var form = $('<form method="POST" action="xyz"></form>');
$(document.body).append(form);
form.append('<input type="hidden" name="id" value="4"/>');
form.submit();
}
As Racil suggested in comments, you can also do the following
click
and then
$('#postLink').click(function(e){
e.preventDefault();
//create form and post
});

Call a java script function on onclick which will make the form submission using post method or you can use ajax call to post the data and get your desired results.Use id as a parameter in function.
<a href="#" onclick="postData(4)">
/// Javascript function for ajax call
function postData(id){
var param = { "Id": id};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "xyz.aspx",
data: JSON.stringify(param),
success: function (data) {
/// Recive data here or do your stuff here
}
}
Make a form having single input type hidden and onclick set value of that input type hidden element and submit form using jquery.
<form id="target" action="destination.html">
<input type="hidden" id="hiddenValue">
</form>
/// Javascript function for setting value of hidden element and form submission using jquery
function postData(id){
$("#hiddenValue").val(id);
$("#target").submit();
}
Hopefully this will solve your problem.

Related

Getting data from HTML form, and from Javascript array upon form submission

I'm stuck.
I have a regular HTML form that submits to itself.
<form action="<?php print $phpSelf;?>" method="post" id="PO">
<input>...</>
<input>...</>
<input>...</>
<input type="submit" id="btnCreate" name="btnCreate" value="Create" tabindex="900" class="button">
</form>
And I have an array in Javascript, I'll call it
var jArray;
I need to get the information from the form, and the information from the Javascript array. I can get each of them separately, but I don't know how to get them at the same time.
For the Javascript, this is the method I am using.
function submitPO(){
$.ajax({
type:"post",
url: "jsTo.php", //Send the variable to this page
data:{partsToAdd: jArray}, //{variable name (POST), data to be passed}
cache:false,
success: function(html){ //Function to execute when successful
console.log("Success in the function");
$('p#msg').html(html);
}
});
return false
}; //End of SubmitPO
<p id = "msg"></p>
<form>
<input type="submit" value = "submit" onclick = "return submitPO();">
</form>
When I press the button, it sends the array to jsTo.php where I can get it.
$selectedParts = $_POST['partsToAdd'];
That works fine. I use a similar method for getting the information from the HTML form.
$To = htmlentities($_POST["To"], ENT_QUOTES, "UTF-8");
So, like I mentioned above, I can get either the data from the javascript array, or the data from the form, but not both. Anyone able to help me figure this out? I've looked all over SO, and have found tons of resources on how to submit multiple forms with one button, how to post from JS to PHP, etc., but nothing that has touched on this issue.
You can get the data from the form with .serialize then you can add it to the array data with $.param
data:$.param({partsToAdd: jArray})+'&'+$('#PO').serialize(),
You can just serialized your form.
in your ajax data, just do
data: $('form').serialize()

JQuery button takes url and submits php form

I run an application that shortens urls for authenticated users. The form for this application is simply an input for the full url, which then spits out a shortened url.
I would like to build a button that can be added to generated pages (the urls are long and messy) and once clicked would automatically submit the url shortening form.
The url shortening application is run in php. I've read a little bit about using ajax to submit the form. Does this matter if it's on a different website? Does anyone have a good tutorial or starting point for this sort of thing?
Many thanks!
edit to include code:
<form action="" method="post">
<label for="form_url">Which URL do you want to shorten?</label>
<input type="url" id="form_url" name="form[url]" required="required" value="http://">
<input type="hidden" name="form[_token]">
<button type="submit" role="button">Shorten URL</button>
</form>
$(document).ready(function() {
$('a.btn').click(function() {
var pathname = window.location;
$.ajax({
type: "POST",
url: 'http://url',
data: $(pathname).serialize,
success: success,
dataType: text
});
});
});
There isn't much to go on, considering you didn't post any code, but what I think you're asking is:
<form id="myForm" method="post">
<input type="text" name="long_url"/>
<input type="submit" value="Send"/>
</form>
Now in the Javascript, you'd capture the submit event and call and ajax request:
$("#myForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "urlOfPhp",
data: $("#myForm").serialize(),
success: function(returned_data) {
// Handle Success Here.
}
}).error(function(){
// Handle an Error Here.
});
});
And that's the basics of Ajax. I'm also not clear on the Generated pages button thing, but this is a good starting point.

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

An easy way to post to a URL and not use ajax?

Using jQuery, I know $.ajax() can be used to POST to a url but I can't use $.ajax() for my problem. I want the client to POST to a url and have the server redirect to a user to some url (PRG pattern) so therefore, it cannot use XHR requests.
How can I get the client to POST to a url without creating a <form>? Surely, there's got to be an easier solution than this. jQuery post request (not AJAX)
Why can't you POST with Ajax, and then whenever it returns, do a Javascript redirect within the callback function? Just have the server provide the URL to redirect to as a response.
You can create and send a form or use ajax. There is no other way I know of.
But why not: First save the data using ajax post and then go to the new page.
$.post('youscript.php', function(data) {
window.location.href = data;
});
Otherwise see this old question on how to send it with a dynamically created form.
simplest approach is to use jquery and click() events. and passing them as var's in a dataset using data: {data1: datavals}
ill edit this post once the code is written.
update:
<input type="text" name="data1" id="data1" value="" placeholder="Input text for data 1">
<input type="text" name="data2" id="data2" value="" placeholder="Input text for data 2">
<input type="submit" name="submit" id="submit" value="submit">
$("#submit").click(function(){
$.ajax({
url: "process.php",
data: {data1: $("#data1").val(), data2: $("#data2").val()},
dataType: "json",
type: "POST"
});
});

Process form data using jQuery

I'm currently using Prototype, but I'd like to rewrite this function to jQuery:
function post(div,url,formId) {
new Ajax.Updater(div, url, {
asynchronous:true,
parameters:Form.serialize(formId)
});
}
HTML example that goes with it:
<form method="post" action="" id="foo"
onsubmit="post('result','getdata.php','foo');return false;">
<input type="text" name="data" />
</form>
<div id="result">&lt/div>
I've been looking at jQuery.load() and jQuery.post(), but I'm not sure which one to use and how exactly.
Thanks in advance for your help.
With this HTML:
<form method="post" action="getdata.php" id="foo">
<input type="text" name="data" />
</form>
<div id="result"></div>
You can do this with jQuery:
$(function() { // wait for the DOM to be ready
$('#foo').submit(function() { // bind function to submit event of form
$.ajax({
type: $(this).attr('method'), // get type of request from 'method'
url: $(this).attr('action'), // get url of request from 'action'
data: $(this).serialize(), // serialize the form's data
success: function(responseText) {
// if everything goes well, update the div with the response
$('#result').html(responseText);
}
});
return false; // important: prevent the form from submitting
});
});
The reason I got rid of the onsubmit code is because it is considered bad practice to have inline JavaScript like that. You should strive to make your forms free of JavaScript and then bind all the JavaScript away from it. This is known as unobtrusive JavaScript and it is a Good Thing.
EDIT:
Since you have that code in many pages, this is a function that will do what you want using the same signature you currently have on the post function. I recommend you take a few hours to update all your forms over keeping this, but here it is anyways:
function post(div,url,formId) {
$.post(url, $('#' + formId).serialize(), function(d) {
$('#' + div).html(d);
});
}
As far as your problem, the livequery plugin could help you there. Alternatively, it is as simple as encapsulating the binding code in a function and calling it whenever a form is added.
Use this and get rid of the onsubmit attribute in your HTML:
$(document).ready(function() {
$("#foo").submit(function() {
$.post($(this).attr("action"), $(this).serialize());
return false; // prevent actual browser submit
});
});
jQuery serialize method docs
You can't send "multipart/form-data" forms with jquery because of security problems. You must do it with flash or iframe...

Categories

Resources