What I want to achieve:
I need to use POST method then after success, it will locate to another url of ajax along with the POST data.
This is what I have done so far:
<script>
$("#btnSubmit").click(function(){
var ddate = $("#ddate").val();
var empid= $("#empid").val();
$.ajax({
type:'POST',
url:'../PaySlip/view_payslip.php',
data:{numnumnum:empid,dateito:ddate},
success:function(){
window.location ="../PaySlip/view_payslip.php";
}
});
});
Problem:
Upon success, the view_payslip cannot gather the POST data that I have transferred. I know what I did was wrong. That is why I'm asking for help to how to get this right.
Thank you in advance.
What you need to do is to post dynamic form in success callback.
I have also similar requirement in one of my project and for that I have created a method similar to shown below.
In this method you need to pass URL, windows option and params which is your data object, name is the window name, if you want to open in same window then instead of opening a new window you can pass blank in name param and omit the window.open() statement. You can modify it as per your requirement.
function submitDynamicForm(url, windowoption, name, params)
{
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", url);
form.setAttribute("target", name);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
}
document.body.appendChild(form);
window.open("", name, windowoption);
form.submit();
document.body.removeChild(form);
}
Related
I have a array student. I need to pass this array in another php page via POST, not from GET, because it can contains thousands of characters.
I am trying to open new page sheet.php and echo the array student, I do simply checking echo $_POST['mnu'], but it is showing undefined index error.
var http = null;
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}
else{
http = new ActiveXObject('Microsoft.XMLHTTP');
}
http.open('POST','sheet.php',true);
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
window.open('sheet.php','_blank')
}
}
http.send('mnu='+JSON.stringify(student));
Like #RamRaider commented.. you're making two requests to sheet.php. The first being a "silent" POST request and the second being a GET request after the first POST request has successfully completed.
The second request won't share the payload of the first.
If I under stand correctly the below code should do what you are wanting...
// Create a form element
// <form action="sheet.php" method="post"></form>
var tempForm = document.createElement('form');
tempForm.setAttribute('action', 'sheet.php');
tempForm.setAttribute('method', 'POST');
tempForm.setAttribute('target', '_blank'); // Open in new tab
// Create an input field
// <input name="mnu" value="...">
var tempInput = document.createElement('input');
tempInput.setAttribute('name', 'mnu');
tempInput.setAttribute('value', JSON.stringify(student)); // Set field value
// Add the input to the form
tempForm.appendChild(tempInput);
// Add the form to the body in order to post
document.body.appendChild(tempForm);
// Submit the form
tempForm.submit();
// Remove the form
document.body.removeChild(tempForm);
And if you're using jQuery you can simplify the above code..
$('<form>', {
action: 'sheet.php',
method: 'POST',
target: '_blank',
html: $('<input>', {
name: 'mnu',
value: JSON.stringify(student)
}).prop('outerHTML')
}).appendTo($('body')).submit().remove();
Change http.send('mnu='+JSON.stringify(student)); to http.send(JSON.stringify(student));
And then in your sheet.php use json_decode($_POST) to fetch your POST data
I have several User Controls and one of which requires a click to go to a different page. I have a javascript function that is called and with the alert within, I know it's posting the correct data. Also this Javascript call is used with other websites and is working fine, but they are not dealing with user controls. The user control, calls ShowNotes, but posting to a normal form page with a site.master page. I'm thinking I'm missing something simple, so please be kind and let me know what I'm missing.
function ShowNotes(appName, serverName, appDataID) {
var params = [];
params.push({
AppName: appName,
ServerName: serverName,
AppDataID: appDataID
});
formPost("/Notes.aspx", params);
}
function formPost(url, params) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("name", "hiddenForm");
form.setAttribute("action", url);
var hiddenField;
for (var key in params) {
for (var val in params[key]) {
hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", val);
hiddenField.setAttribute("value", params[key][val]);
form.appendChild(hiddenField);
//alert(val + ": " + params[key][val]);
}
}
document.body.appendChild(form);
form.submit();
}
Then on the Notes.aspx side, I debug and show the Request.Form.Count = 0. What can I possibly be missing? I also looked at the request.QueryString and it's empty.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.Form.Count > 0)
{
EDIT:
Based on VDWWD comment, I modified the method to check if a form exists and use that one. I'm still getting the same results.
function formPost(url, params) {
var form = document.forms[0];
if (form == undefined) {
form = document.createElement("form");
form.setAttribute("name", "hiddenForm");
form.setAttribute("id", "hiddenForm");
}
alert(form.id);
form.setAttribute("method", "post");
form.setAttribute("action", url);
var hiddenField;
for (var key in params) {
for (var val in params[key]) {
hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", val);
hiddenField.setAttribute("value", params[key][val]);
form.appendChild(hiddenField);
//alert(val + ": " + params[key][val]);
}
}
document.body.appendChild(form);
form.submit();
}
I started researching this 301 Moved Permanently and found that people stating, to change the post to just the page without the extension. The 301 is redirecting the page without the extension, causing the POST data to not be passed.
So I changed my JavaScript to remove the .aspx and put a slash in it's place and it works, even through it's a ASPX page:
function ShowNotes(appName, serverName, appDataID) {
var params = [];
params.push({
AppName: appName,
ServerName: serverName,
AppDataID: appDataID
});
formPost("/Notes/", params);
}
I tested the following simplified snippet from your edit after my comment.
<script type="text/javascript">
function formPost(url, params) {
var form = document.forms[0];
form.setAttribute("method", "post");
form.setAttribute("action", '/default.aspx');
hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", 'FormPostTest');
hiddenField.setAttribute("value", "TheValueOfTheHiddenField");
form.appendChild(hiddenField);
form.submit();
}
</script>
And on Default.aspx I retrieve the value with this Request.Form["FormPostTest"] and it works just fine. Even if the post page is different from the page the form is on.
Are you sure you are posting to the correct page and with the correct name?
I made a webcam page in Laravel5.
I would like to send POST(javascript, WEBCAMjs) to crop.blade.php(laravel).
My code works well when run with only php.
=> form.setAttribute("action", "crop.php");
However, if I try to send it to laravel(crop.blade.php), it returns MethodNotAllowedHttpException.
=> form.setAttribute("action", "crop.blade.php");
How can I solve this problem?
thanks for your help in advance!
Webcam.snap( function(data_uri) {
var obj1 = data_uri
var form = document.createElement("form");
form.setAttribute("charset", "UTF-8");
form.setAttribute("method", "Post");
#form.setAttribute("action", "crop.php");
form.setAttribute("action", "crop.blade.php");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "raw");
hiddenField.setAttribute("value", obj1);
form.appendChild(hiddenField);
var url ="crop"
var status = "toolbar=no,directories=no,scrollbars=no,resizable=no,status=no,menubar=no,width=1240, height=1200, top=0,left=20"
document.body.appendChild(form);
form.submit();
}
It will be the routing. If you go to your web.php file, you will see the route that you are loading for the page. It might look like the following:
Route::get('crop', function () {
return view('crop');
});
You also need the following to allow post requests
Route::post('crop', function () {
// Logic for the post request
});
Obviously it would be better to use controllers instead of closures, but that's the general idea.
I am trying to submit a javascript form like following
node.on("click", function(d){
var name =encodeURIComponent(d.ancestors()[0].data.id) ;
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "clickable_cluster");
form.setAttribute("target", "_blank");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("user_name", "{{user_name}}");
hiddenField.setAttribute("thresh1", "{{thresh1}}");
hiddenField.setAttribute("thresh2", "{{thresh2}}");
hiddenField.setAttribute("thresh3", "{{thresh3}}");
hiddenField.setAttribute("pthresh1", "{{pthresh1}}");
hiddenField.setAttribute("pthresh2", "{{pthresh2}}");
hiddenField.setAttribute("pthresh3", "{{pthresh3}}");
hiddenField.setAttribute("node", "name");
form.appendChild(hiddenField);
document.body.appendChild(form);
//window.open('', 'view');
//window.location.assign("clickable_cluster", '_blank');
form.submit();
});
But, the flask server in backend doesnt receives any of these post parameters.
#app.route('/clickable_cluster', methods=['POST'])
def clicable_cluster():
print "request got ", request.form.items() # is []
What am I missing?
Thanks
The general reason why you don't get any data submitted by your form request is because a form request generally sends all input fields with it's name & value as content.
Currently you are only setting attributes on a nameless input field.
You could generalize the adding of your form elements in the following way. The attachToForm function will take a form and an object as input parameters and will create appropriate input fields for each property inside your object.
function attachToForm( form, content ) {
Object.keys( content ).forEach( prop => {
var input = document.createElement('input');
input.name = prop;
input.value = content[prop];
form.appendChild( input );
});
}
node.on("click", function(d){
var name =encodeURIComponent(d.ancestors()[0].data.id) ;
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "clickable_cluster");
form.setAttribute("target", "_blank");
attachToForm( form, {
"user_name": "{{user_name}}",
"thresh1": "{{thresh1}}",
"thresh2": "{{thresh2}}",
"thresh3": "{{thresh3}}",
"pthresh1": "{{pthresh1}}",
"pthresh2": "{{pthresh2}}",
"pthresh3": "{{pthresh3}}",
"node": "name"
});
document.body.appendChild(form);
form.submit();
});
I am guessing that the values you are sending are placeholders for the real data or part of your rendering engine, but generally it should do the trick.
I have the following code that gets executed when button is pressed.
function signInButton(){
var data = {
"userName" : $("#text_userName").val(),
"password" : $("#password_signInPassword").val()
};
var userName = $("#text_userName").val();
var password = $("#password_signInPassword").val();
var loadUrl= parentApp + "/executeLogin.htm";
makeNetCall(loadUrl, data, function(responseJson) {
jQuery("#text_userName").val('');
jQuery("#password_signInPassword").val('');
post('/TestWebProject/pages/SetSession.jsp', {name: 'Johnny Bravo'});
},
function(err) {
jQuery("#text_userName").val('');
jQuery("#password_signInPassword").val('');
alert("Invalid Username/Password");
});
}
but this post request post('/TestWebProject/pages/SetSession.jsp', {name: 'Johnny Bravo'}); is getting aborted.
post method is
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
There is no other request that could abort my post request. Why is this happening then? Any has encountered this before? solution/workaround?
Read NS_BINDING_ABORTED Javascript window.location.replace()
Based on your network output, it looks like you are redirecting to the login while the post is still going on. I'm not sure what the code of makeNetCall looks like, but I assume something in there is causing the page to change before the form is even done loading.