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

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"
});
});

Related

How to submit an array using HTML and Ajax and send it to PHP as array?

I'm trying to submit some of my HTML inputs as an array, and use it in PHP, but the other inputs are being passed to PHP by Ajax (using jQuery). So I need to get the value of the inputs and send them to a PHP file by Ajax. My inputs are like these:
<input value="..." type="hidden" name="something[]" />
<input value="..." type="hidden" name="something[]" />
<input value="..." type="hidden" name="something[]" />
I have never used this way to submit an array and just saw it. I will be thankful if someone explains this way (name="something[]").
Assuming you need to POSTthat payload:
Use the function $.serialize()
var payload = $('[name="somthing[]"]').serialize();
console.log(payload);
$.post( URL, payload);
Or you can use the function .ajax():
$.ajax({
method: "POST",
url: URL,
data: payload
});
Resource
$.ajax()
$.post()
$.serialize()

Avoid form resubmission on reload with AJAX and Warning: Cannot modify header FIX

The problem that I am facing here is that the form is resubmitted when the page is being refreshed. Now I know there are plenty of answers online for the problem I have stated above. But what is different in my problem is that I am using ajax to submit the form so the form is not redirecting and only a section of it is updated. Since I don't want the page to redirect therefore I can not use the post/redirect/get method.
This is my code:
HTML:
<form method="post" onsubmit="return submitdata();">
<textarea maxlength="3000" id="profile-post" name="profile-post" placeholder="Write a post..." rows="3" cols="65" required></textarea>
<input type="submit" value="Post">
</form>
script:
function submitdata()
{
var post=document.getElementById( "profile-post" );
$.ajax({
type: 'post',
url: 'page.php',
data: {
post:post
}
})
};
PHP:
if(isset($_POST['profile-post'])){
$post = $_POST['profile-post'];
mysqli_query($dbc,"INSERT INTO make_post (post, time, date, user_id) VALUES ('$post', CURTIME(), CURDATE(), '$id_profile')");
}
}
Is there any other way I can achieve the desired result which I couldn't find during my search online.
Thanks.
So you type whatever you want into your form fetch it with jquery , send it to php page with ajax and query it into database afterwards dynamically insert it into ... table or something.
Most parts of your code or explanation is missing . this is the most i can give.
<form method="post">
<textarea maxlength="3000" id="profile-post" name="profile-post" placeholder="Write a post..." rows="3" cols="65" required></textarea>
<button type="button" value="Post">
</form>
$(document).ready(function(e){
var post = $('#profile-post').val();
$.ajax({
type:"POST" ,
data :{
'type' : 'post',
'id': id,
'post' : post
},
url : '../allforms.php' //Php page to send data
}).success(function(data){
$('#profile-post').val('');
//Write code of whatever you want to load dynamically
without loading
});
});
}
Please explain your desired result more clearly
I was able to fix this by adding
header('location:page.php');
in my PHP file after form is submitted.
I thought this would redirect to the page.php and it will reload which I wanted to avoid and hence used ajax. But adding that line didn't reload the entire page.
I'm very thankful to everyone for taking out their time and answering to my question.
Also, I was getting an error when using header which was
Warning: Cannot modify header information - headers already sent by..
And it was fixed by adding
<?php ob.start();?>
and the beginning of the file.
I hope this could help anyone with similar problem. Thanks.

How to convert a GET request to POST

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.

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.

Upload files without refreshing the page by using ajax post

I have a page file-upload.jsp with the code snippet below:
<form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file" multiple="" />
<input type="submit" value="Update" />
</form>
I have 2 questions:
The moment I select some files, i.e the onchange event of the input type file, the file(s) should get uploaded.
I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission onchange, so that the Java file can proceed with further operations.
I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.
I tried a lot of code from internet, such as this:
$(document).ready(function(){
$('upload_file').change(function(){
var data = new FormData();
data.append('file', $(this[0].files[0]));
$.ajax({
url: 'photo.jsp',
type: 'post',
contentType: attr('enctype', "multipart/form-data"),
data: data,
success: function(data){
alert(data);
}
})
});
});
but could not get the expected results.
I also need a progress bar for the upload operation.
Look at this example using an IFrame, is in PHP but changing the action should do the trick
Ajax Style File Uploading Using Hidden IFrame
Since you're already using jQuery, I would definitely go for the jQuery Form Plugin, which allows you to do form uploads via AJAX, even if the form contains a file input.
There is an example on its website available that shows how to display a progress bar.
Look at this example it is exact as you want
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx

Categories

Resources