Send Data to php file with javascript - javascript

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.

Related

redirect to another page with post instead of get data [duplicate]

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

node.js how receive values from form

I create a server with node.js. Then I build an http form on the specific address. (I'm going do different forms on different addresses).
I want to receive data from the user in specific field. (I'll give them different ID's).
But I can't receive it with document.getElementById() because DOM is undefined in node.js.
Can you advise a specific module for solving this problem, or some useful method?
var server = new http.Server(function(req, res){
if (req.url=='/') {
res.statusCode=200;
auth(res);
res.end();
} else {
res.statusCode=404;
res.end("Page not found");
}
})
function auth(res) {
res.writeHead(200, {
'Content-Type': 'text/html',
});
var body = '';
body= '<form action="/" method="post">'+
'<thead>Connection details </thead>' +
'<br>'+
'<textarea id ="text" name="text" rows="1" cols="50"></textarea><br>'+
'<input value="localhost" id="host">Host</input><br>' +
'<input value="root" id="user">User </input><br>' +
'<input value="********" id="pass">Pasword </input><br>' +
'<input type="submit" value="Connect" id="scheme"></input><br></body></html>'
var toWrite = header + body;
res.write(toWrite);
}
Set up as your project is now, you will receive the parameters from the form in req.body. I recommend looking into express and body-parser, to parse incoming data.

CKEditor file upload not working in Yii2

I'm working on Yii2 Project where I've integrated http://ckeditor.com/demo
Now I want to implement functionality of file/image upload in it.
This is how I integrated CKEditor in Yii2 Project.
Step1: AppAsset.php
public $js = [
'ckeditor/ckeditor.js',
];
Calling ckeditor.js javascript file from config/AppAsset Class
Step2: View
<?= $form->field($model, 'standard_output_information')->textarea(['rows' => 2, 'class'=>'ckeditor']) ?>
Step3: config.js
CKEDITOR.editorConfig = function (config) {
var base_url = window.location.origin;
var pathArray = window.location.pathname.split('/');
var projectUrl = base_url + "/" + pathArray[1] + "/" + pathArray[2] + "/" + pathArray[3] + "/uploads";
config.filebrowserImageBrowseUrl = base_url + "/pcwf" + "/backend" + "/web" + "/businessprocessprofile" + "/upload";
config.filebrowserImageUploadUrl = base_url + "/pcwf" + "/backend" + "/web" + "/businessprocessprofile" + "/upload";
};
Here I've configured ImageBrowserUrl and ImageUploadUrl mentioned here http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)
Step4: Controller
public function actionUpload() {
echo \yii\helpers\Html::csrfMetaTags();
echo "<pre>";
print_r($_FILES);
print_r($_REQUEST);
exit;
}
Here I'm expecting uploaded image data. But whenever I click on Send it to Server button after selection of an image its giving me following error.
Not sure whether its issue of wrong url configuration in config.js or is it Yii2 form submission issue.
Any help would be appreciated.
I believe you have a problem with the CRSF tokens. Read more about the security here: http://www.yiiframework.com/doc-2.0/guide-security-best-practices.html. The easiest way to get around this is to disable CRSF for that particular action. You can take a look on how to do that here: https://stackoverflow.com/a/28526946/1880627
Rather than disabling CSRF validation it is far better and more secure to submit the token with the form to pass server-side validation. This can be quite easily done by injecting a hidden input field into the upload form with javascript:
$(document).off('click', '.cke_dialog_tabs a[id^="cke_Upload_"]').on('click', '.cke_dialog_tabs a[id^="cke_Upload_"]', function () {
var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
$forms.each(function () {
if (!$(this).find('input[name=' + csrfName + ']').length) {
var csrfTokenInput = $('<input/>').attr({
'type': 'hidden',
'name': csrfName
}).val(yii.getCsrfToken());
$(this).append(csrfTokenInput);
}
});
});
For a more detailed discussion on the issue refer to 2amigos/yii2-ckeditor-widget, issue #2. This is also where the code snippet is taken from, with a few minor tweaks to cover the case of multiple widgets on the page.

Append image in function jquery

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.

FB api call in for loop

I'm trying to get all facebook comments with profile pictures of commentators through fb.api() call. Currently all comments gets outputed i just can't get profile pictures to append to appropriate comment.
In for loop which loops through all comments is another FB.api call which gets the profile pic of user who commented on video and than append them into single comment block. With this code i get profile pictures of all users who commented in every single comment.
What am i doing wrong?? Thank you in advance!
var komentarji_length = response.comments.data.length;
for (var i = 0; i < komentarji_length; i++) {
var user_id = response.comments.data[i].from.id;
FB.api("/" + user_id + "/picture", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
var ime = response.comments.data[i].from.name;
var message = response.comments.data[i].message;
$(".fb_comments").append('<div class="single_comment"><div class="comments_profile_pic' + i + '"></div><div class="name">' + name + '&nbsp says:</div><div class="single_message">' + message + '</div></div>');
}
Issue 1: comments_profile_pic_link is not defined, the variable is: profile_pic_link.
But then also the problem will not be solved. When you call "/" + user_id + "/picture" it is redirected to the image url automatically. So you can directly use the image url as: https://graph.facebook.com/{user-id}/picture. No need to make the API call unnecessarily.
Example
Still if you wish to get the proper image url (not required though), use redirect=0 with your call-
FB.api("/" + user_id + "/picture?redirect=0", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});

Categories