sending by post php ajax - javascript

Good morning, I want to send to an external site to my two variables by post are username and password and the page I create a cache in the browser when I go to another url already be logged in code what I do is check for through PHP if the data is correct or not, if they are correct returned if, but returns no, if they are correct what I want to do is force the form to send the submit the url, the problem is that everything works fine to the point the submit the form no longer do anything, can you help me?
Thank You
My code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#submit").click(function () {
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
</script>
</head>
<body>
<form action="" method="post" id="formoid">
<div><label>Usuario:</label><input name="user" placeholder="Usuario" type="text" id="user"></div>
<div><label>Contraseña:</label><input name="pass" placeholder="Contraseña" type="text" id="pass"></div>
<div><input name="enviar" type="submit" value="Enviar" id="submit"></div>
<div><input name="btnPass" type="submit" value="¿Olvidaste tu contraseña?"></div>
</form>
</body>

Just declare the event parameter in the click handler, and then do event.preventDefault(). Doing so, the default submit action is ignored and your code will be executed instead:
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});

checkout the result whether its returning "si" if its correct
try
changing code
from
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
to
$("#formoid").attr('action', 'http://xzc.tv/login');
$("#form").submit();
try using id of form

To submit try the following
$("form#formoid").submit();
$("form#formoid")[0].submit();
$("form#formoid").submit(function(e) {});

Related

JavaScript Multiple Forms [duplicate]

If I have a form like this,
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>
how can I submit it without redirecting to another view by JavaScript/jQuery?
I read plenty of answers from Stack Overflow, but all of them redirect me to the view returned by the POST function.
You can achieve that by redirecting the form's action to an invisible <iframe>. It doesn't require any JavaScript or any other type of scripts.
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form action="submitscript.php" target="dummyframe">
<!-- Form body here -->
</form>
In order to achieve what you want, you need to use jQuery Ajax as below:
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
url: '/Car/Edit/17/',
type: 'post',
data:$('#myForm').serialize(),
success:function(){
// Whatever you want to do after the form is successfully submitted
}
});
});
Also try this one:
function SubForm(e){
e.preventDefault();
var url = $(this).closest('form').attr('action'),
data = $(this).closest('form').serialize();
$.ajax({
url: url,
type: 'post',
data: data,
success: function(){
// Whatever you want to do after the form is successfully submitted
}
});
}
Final solution
This worked flawlessly. I call this function from Html.ActionLink(...)
function SubForm (){
$.ajax({
url: '/Person/Edit/#Model.Id/',
type: 'post',
data: $('#myForm').serialize(),
success: function(){
alert("worked");
}
});
}
Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:
function formSubmit(event) {
var url = "/post/url/here";
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.onload = function() { // request successful
// we can use server response to our request now
console.log(request.responseText);
};
request.onerror = function() {
// request failed
};
request.send(new FormData(event.target)); // create FormData from form that triggered event
event.preventDefault();
}
// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
document.getElementById(formId).addEventListener("submit", formSubmit);
}
Place a hidden iFrame at the bottom of your page and target it in your form:
<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>
Quick and easy. Keep in mind that while the target attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.
So you really should be using Ajax to future-proof.
Okay, I'm not going to tell you a magical way of doing it because there isn't.
If you have an action attribute set for a form element, it will redirect.
If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"
In your someFunction() you do whatever you want, (with AJAX or not) and in the ending, you add return false; to tell the browser not to submit the form...
One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data or application/x-www-form-urlencoded:
<form onsubmit='return false'>
<!-- ... -->
</form>
You need Ajax to make it happen. Something like this:
$(document).ready(function(){
$("#myform").on('submit', function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if(name=='' || email=='' || password=='' || contact=='')
{
alert("Please fill in all fields");
}
else
{
// Ajax code to submit form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
See jQuery's post function.
I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.
Also, see the preventDefault function, of jQuery!
The desired effect can also be achieved by moving the submit button outside of the form as described here:
Prevent page reload and redirect on form submit ajax/jquery
Like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
Using this snippet, you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.
function submitForm(form, successFn){
if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
var id = form.getAttribute("id");
} else {
console.log("Form id attribute was not set; the form cannot be serialized");
}
$.ajax({
type: form.method,
url: form.action,
data: $(id).serializeArray(),
dataType: "json",
success: successFn,
//error: errorFn(data)
});
}
And then just do:
var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
console.log("Form submitted");
});
Fire and forget vanilla js + svelte
function handleSubmit(e) {
const request = new Request(`/products/${item.ItemCode}?_method=PUT`, {
method: 'POST',
body: new FormData(e.target),
});
fetch(request)
}
Used in Svelte:
<form method="post" on:submit|preventDefault={handleSubmit}>
If you control the back end, then use something like response.redirect instead of response.send.
You can create custom HTML pages for this or just redirect to something you already have.
In Express.js:
const handler = (req, res) => {
const { body } = req
handleResponse(body)
.then(data => {
console.log(data)
res.redirect('https://yoursite.com/ok.html')
})
.catch(err => {
console.log(err)
res.redirect('https://yoursite.com/err.html')
})
}
...
app.post('/endpoint', handler)

How to get alert in nodejs using jquery ajax?

I'm trying to create a function in javascript that gives an alert if the posted data in a form is good or wrong, I'm using Jquery and nodejs
there is my function from clientside.
function myFunction() {
console.log('hellooooo');
$('#select_link').submit(function(e){
e.preventDefault(); // avoid to execute the actual submit of the form.
console.log('select_link clicked');
var value = document.getElementById(secretnumber);
$.ajax({
url: "/testValue", // La ressource ciblée
type: "POST",
data: value,
contentType: 'application/json',
dataType: 'json',
success: function(returns) {
console.log('Data received : ' + returns);
if (returns) {
alert("Correct number");
} else {
alert("Wrong number");
}
}
});
});
}
And this is my form in html
<form onsubmit="myFunction()">
<input type="text" name="number" id="secretnumber">
<input type="submit" value="Testear" id="select_link">
</form>
And this is my server function
app.post('/testValue',(req,res)=>{
console.log('Received data in server :' + req.body);
//res.send(req.body);
if(req.body.value ==='4')
{
res.send('true');
}else{
res.send('false');
}
});
Excuse me, but I'm a little lost on that code, thanks so much for your help

Why is jquery-ajax submitting form multiple times?

I have read this: jQuery ajax form submitting multiple times
It didn't help.
If i type something on form and click the submit button then it sends one request. Second time if i type something and click it sends two requests. Third time it sends three requests and so on. Why is this? Did i do any mistake in jquery code?
Here is my code:
index.php =>
<div id="id_div_1" class="cl_div_comment_container"></div>
<form id="id_form_1" method="POST">
<input type="hidden" value="1" name="nm_hidden_post_id">
<textarea class="cl_textarea_comment" style="resize:none;" rows="1" cols="50" name="nm_comment_content"></textarea>
<input class="cl_submit_comment" type="submit" value="Comment" name="nm_submit_comment">
</form>
javascript.js =>
$(document).ready(function(){
console.log('hello');
$('input[name="nm_submit_comment"]').on('click',function(){
var frm = $(this).closest("form")[0];
var frm_id = $(frm).attr("id");
var frm_id_splitted = frm_id.split("_");
var frm_id_splitted_2 = frm_id_splitted[2];
console.log($('div#id_div_' + frm_id_splitted_2));
$(frm).on('submit',function(e){
e.preventDefault();
frm_serialized = $(this).serialize();
console.log(frm_serialized);
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function(data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
});
});
save-comment.php =>
<?php
if (session_id() == '') {
session_start();
}
echo json_encode($_POST);
?>
You are registering the event for form submit inside the code you have for the click event on the button. So every time you click the button, it will keep adding the event over and over.
This should be good enough.
$(document).ready(function(){
$('input[name="nm_submit_comment"]').on('click',function(e){
e.preventDefault();
var frm = $(this).closest("form");
var frm_id = frm.attr("id");
var frm_id_splitted = frm_id.split("_");
var frm_id_splitted_2 = frm_id_splitted[2];
var frm_serialized = frm.serialize();
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function(data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
});
Try one then on
$("#id_form_1").one('submit', function (e) {
e.preventDefault();
frm_serialized = $(this).serialize();
console.log(frm_serialized);
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function (data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
Also no need to make submit bind just serialize your nearest form and make ajax call. You are binding event inside and event performs multiple binding.
You can try this:
$(document).off().on("click","#submit",(function(e) {
e.preventDefault();
}

Redirect when using 'onclick' with an input element

My HTML is -
<input type="submit" onclick="javascript:agreeprint();" value="Proceed">
And my JavaScript function is -
<script type="text/javascript">
function agreeprint()
{
if($("#company").val()==''||$("#office_address").val()=='')
{
alert('<?php echo $this->translate('Please enter the empty field values'); ?>');
return false;
}
else
{
var companyval = $("#company").val();
var officeaddrval = $("#office_address").val();
$.ajax({
type: "POST",
url: "/index/agreement",
data: $( "form" ).serialize(),
success: function(msg){
if(msg.substr(0,9)=='contratt_')
location.href = '/filename/'+msg;
}
});
}
window.location = "/index"; //The redirection is not working
}
</script>
After the function is finished the redirection process does not happened. What am I doing wrong?
There is nothing wrong with the redirection because I ran jun the redirection part of your code,
<script type="text/javascript">
function agreeprint()
{
window.location = "/index"; //The redirection is not working
}
</script>
<input type="submit" onclick="javascript:agreeprint();" value="Proceed">
and it works perfectly. There must be something wrong with the javascript before the redirection:
if($("#company").val()==''||$("#office_address").val()=='')
{
alert('<?php echo $this->translate('Please enter the empty field values'); ?>');
return false;
}
else
{
var companyval = $("#company").val();
var officeaddrval = $("#office_address").val();
$.ajax({
type: "POST",
url: "/index/agreement",
data: $( "form" ).serialize(),
success: function(msg){
if(msg.substr(0,9)=='contratt_')
location.href = '/filename/'+msg;
}
});
}
Judging from the errors that I was getting when I ran the code I am guessing that there is a problem with your AJAX because I got a odd POST error when I ran the code and I also discovered that there is a missing ")" but I am not familiar with AJAX so I am just guessing,
SyntaxError: missing ) after argument list
I hope this helps,
Conor.

jquery ajax form submit

Is this code correct? I'm trying to submit it and also I would like on submit if text area would be empty again.
<script type="text/javascript">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var fid = $(".messag").attr("id");
var val = $("#mess_ar").val();
$.ajax({
type: "POST",
url: "send_message.php",
data: "fid="+ fid +"&val="+ val,
success: function(){
$("#mess_ar").
}
});
return false;
});
}):
</script>
I'm trying to upload this:
<form id="submit" method="POST">
<textarea name="mess_cont" id="mess_ar" autofocus="autofocus" cols="70" rows="5"> </textarea>
<button id="mess_but" type="submit">Send</button>
</form>
Thankx...
Looks good. To empty the textarea use the following in the ajax success callback:
$("#mess_ar").val('');
​$(function(){
$("form#submit").submit(function(e){
e.preventDefault();
var fid = $(".messag").attr("id");
var val = $("#mess_ar").val();
$.ajax({
type: "POST",
url: "send_message.php",
data: "fid="+ fid +"&val="+ val,
success: function(){
$("#mess_ar").val("");
}
});
});
});​
Use
$("#submit").on('submit', function(e){...});
instead of
$("#submit").submit(function(e){...});
if you are using latest version of jquery.
What are you actually looking for? Does it return the data in response too? Add the functions to track your the error case too. Make something like
<script type="text/javascript">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var fid = $(".messag").attr("id");
var val = $("#mess_ar").val();
$.ajax({
type: "POST",
url: "send_message.php",
data: "fid="+ fid +"&val="+ val,
success: function(incoming_data){
// ALERT incoming data if coming
$("#mess_ar").text(""); // DO YOUR JOB CONTINUOU
},
error: function() {
alert("BROKEN REQUEST.");
}
});
return false;
});
});
</script>
Else, seems all fine.

Categories

Resources