I am trying to send form data to another PHP file.
its working but once data is submitted the page is not redirecting to that specific page.
Like it work in php.
function codeverify() {
var code=document.getElementById('verificationCode').value;
coderesult.confirm(code).then(function (result) {
if (confirm("OTP Confirmed!")) {
var number=document.getElementById('number').value;
$.post("confirm-phone-reg.php", { status: number }); //send data to file
//document.location.href = "http://localhost/test/new/confirm-phone-reg.php";
} else {
window.location.href = "http://localhost/test/new/try-again.php";
};
var user=result.user;
console.log(user);
}).catch(function (error) {
alert(error.message);
});
}
How can I make sure when I send data to the confirm-phone-reg.php the post data and my page will be opened there.
I searched too much on internet but failed to search for answer.
I hope you guys will help me.
var number = document.getElementById('number').value;
var url = 'register.php';
var form = $('<form action="' + url + '" method="post">' + '<input type="text" name="phone" value="' + number + '" />' + '</form>');
$('body').append(form);
form.submit();
For those who are also stuck like this.
This is the easiest way to send data to another file and also redirect at the same time.
This question already has answers here:
JavaScript post request like a form submit
(32 answers)
Closed 7 years ago.
Basically what I want to do is send POST data when I change the window.location, as if a user has submitted a form and it went to a new page. I need to do it this way because I need to pass along a hidden URL, and I can’t simply place it in the URL as a GET for cosmetic reasons.
This is what I have at the moment, but it doesn’t send any POST data.
if(user has not voted) {
window.location = 'http://example.com/vote/' + Username;
}
I know that you can send POST data with jQuery.post(), but I need it to be sent with the new window.location.
So to recap, I need to send api_url value via POST to http://example.com/vote/, while sending the user to the same page at the same time.
For future reference, I ended up doing the following:
if(user has not voted) {
$('#inset_form').html('<form action="http://example.com/vote/' + Username + '" name="vote" method="post" style="display:none;"><input type="text" name="api_url" value="' + Return_URL + '" /></form>');
document.forms['vote'].submit();
}
per #Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Return_URL + '" />' +
'</form>');
$('body').append(form);
form.submit();
Construct and fill out a hidden method=POST action="http://example.com/vote" form and submit it, rather than using window.location at all.
Here's a simple small function that can be applied anywhere as long as you're using jQuery.
var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});
// jquery extend function
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
value = value.split('"').join('\"')
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
}
});
Here is a method, which does not use jQuery.
I used it to create a bookmarklet, which checks the current page on w3-html-validator.
var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';
var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you are using jQuery, there is a redirect plugin that works with the POST or GET method. It creates a form with hidden inputs and submits it for you. An example of how to get it working:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Note: You can pass the method types GET or POST as an optional third parameter; POST is the default.
The answers here can be confusing so i will give you a sample code that i am working with.
To start with note that there is no POST parameter to java script windows.location function that you are referring to.
So you have to...
Dynamically make a form with a POST parameter.
Dynamically put a textbox or textboxes with your desired values to post
Invoke the submit form you dynamically created.
And for the example.
//---------- make sure to link to your jQuery library ----//
<script type="text/javascript" >
var form = $(document.createElement('form'));
$(form).attr("action", "test2.php");
$(form).attr("method", "POST");
$(form).css("display", "none");
var input_employee_name = $("<input>")
.attr("type", "text")
.attr("name", "employee_name")
.val("Peter" );
$(form).append($(input_employee_name));
var input_salary = $("<input>")
.attr("type", "text")
.attr("name", "salary")
.val("1000" );
$(form).append($(input_salary));
form.appendTo( document.body );
$(form).submit();
</script>
If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.
On test2.php you can get your values thus.
$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];
Needless to say , make sure you sanitize your passed values.
Generic function to post any JavaScript object to the given URL.
function postAndRedirect(url, postData)
{
var postFormStr = "<form method='POST' action='" + url + "'>\n";
for (var key in postData)
{
if (postData.hasOwnProperty(key))
{
postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
}
}
postFormStr += "</form>";
var formElement = $(postFormStr);
$('body').append(formElement);
$(formElement).submit();
}
This is quite handy to use:
var myRedirect = function(redirectUrl, arg, value) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
$('body').append(form);
$(form).submit();
};
then use it like:
myRedirect("/yourRedirectingUrl", "arg", "argValue");
var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};
Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/
Going to try this and other suggestions for my work.
Is there any other way to do the same ?
You can use target attribute to send form with redirect from iframe.
Your form open tag would be something like this:
method="post" action="http://some.url.com/form_action" target="_top"
SOLUTION NO. 1
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id='"+product_id+"'");
SOLUTION NO. 2
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);
details
I have 2 email input fields with a class name of send_email. I want to show a email client when the user double clicks on an email field. To do that I am using the following jQuery code but it's showing an error message:
event is not defined
$(document).ready(function(){
$('input.send_mail').dblclick(function() {
event.preventDefault();
var email = $(this).val();
var subject = '';
window.location = 'mailto:' + email + '?subject=' + subject;
});
});
In your dblclick code you use event.preventDefault(), yet haven't set the event property. Try this:
$('input.send_mail').dblclick(function(event) { // < 'event' here
event.preventDefault();
// your code...
}):
Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.
I am writing a jQuery plugin for login form and I have an issue with the 'Submit' button. My 'Submit' button click function never gets executed.
Here is my jsfiddle code http://jsfiddle.net/c4jRx/1/
(function ($) {
$.fn.login = function (options) {
options = $.extend({}, $.fn.login.config, options);
return this.each(function () {
var markup = '<div>' +
'<form method="post" action="">' +
'<table><tr><td><label>User Login</label></td></tr>' +
'<tr><td><input type="text" id="user_id" placeholder="Apple ID" required></td></tr>' +
'<tr><td><input type="password" id="password" placeholder="Password" required></td></tr>' +
'<tr><td><input type="submit" id="authenticate" value="Login to your account"></td></tr>' +
'</table>' +
'</form>' +
'</div>';
return $(this).html(markup);
});
$('#authenticate').click(function() {
debugger;
var user = $('#user_id').val();
var password = $('#password').val();
console.log("User: " + user + "Password: " + password);
});
};
$.fn.login.config = {
// set values and custom functions
};
}(jQuery));
I have modify your fiddle and attaching it over here. The actual problem was you have written click event in login function and after adding html you have written return statement so click event was not getting registered. Here is the solution for that.
Put you click event in document.ready like this:
$(document).ready(function() {
$('#loginScreen').login();
$('#authenticate').click(function() {
var user = $('#user_id').val();
var password = $('#password').val();
console.log("User: " + user + "Password: " + password);
});
});
Here is your updated fiddle : http://jsfiddle.net/c4jRx/5/ Thanks