I am a new user and I need help with JQuery and Ajax. I am good at PHP only.
I have a HTML Page which has a newsletter signup section,
<h4>Newsletter</h4>
<form id="main-news-contact-form" class="news-contact-form" name="news-contact-form" method="post" action="/scripts/xnews.php" role="form">
<div class="input-group">
<input type="text" class="form-control" required="required" placeholder="Enter your email" name="email"/>
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">Go!</button>
</span>
</div>
</form>
And the relevant JQuery -
//newsletter form
var form = $('.news-contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(15000).fadeOut();
},'json');
return false;
});
I have a php script, that reads the form data and saves the email address received in the database table, but for some reason the data (email address) is not being received by the PHP Code, the code below is executed.
if(empty($_POST["email"]))
{
echo("failed");
}
I don't know what I am doing wrong, I have a 'contact us' form, which is working absolutely fine, but I don't know why this newsletter form is not working with jquery.
I assure that all the javascript files are included in the html page, the php page is running absolutely fine, it does not return any php or mysql errors, I am setting JSON headers correctly, it's just that I am not getting the email address entered into the form. Earlier it was working but Ajax was not working, now I managed to get Ajax to work but the JavaScript code is not sending the form data.
Can you please help or help me to debug this.
Thanks in advance !
Your code is not sending any data to the server. Try to add the data as a second parameter to the function.
// get the text from the input field with the id "email"
var email = $.("#email").val();
// get the url from the form
var url = $("#newsletter-send").attr('action');
$.post( url, { email: email }, function( data ) {
// The code that you want to execute after sending the ajax call
}, "json");
Please do not copy paste the code but try to find the reasoning behind it. You might need to check the url variable to make sure you are posting to the right place. Also try to add an id attribute to the input field that contains the email.
I hope this will help you.
Try with this:
var form = $('#main-news-contact-form');
form.submit(function(e) {
e.preventDefault(); // Prevent submitting the form
$this = $(this);
$.post($this.attr('action'), $this.serialize()).done(function(data) {
// Do something with data
$this.prev().text(data.message).fadeIn().delay(15000).fadeOut();
}, 'json');
});
Related
This question already has an answer here:
Understanding HTML Form Element behavior
(1 answer)
Closed 1 year ago.
I have a simple online form that calls a PHP script on submit.
<form name="newform" id="regForm" action="../includes/submit.inc.php" method="post">
When the submit button is clicked the site URL in the browser changes to http://example.com/includes/submit.inc.php and the page is blank.
I want to display a Thank you message after form is submitted and I want the URL to remain http://example.com
I've tried using JS to hide the main container of my website and enabling a DIV with the thank you message.
function submit() {
document.getElementById("main").style.display = "none";
document.getElementById("success").style.display = "inline";
}
document.getElementById('regForm').onsubmit = function () {
var terms = document.getElementById('consentBox');
if (!terms.checked) {
showWarnings(warnings);
return false;
}
submit();
return true;
};
This kind of works I can see the thank you message for a split second but then the browser goes to http://example.com/includes/submit.inc.php and the page is blank. I really want to avoid redirecting to another .php file. I know I could do something like this:
header( "location: ../success.php", true, 301 );
But prefer to display the message on the same page. How can I achieve this?
Thanks in advance.
You can add post php code in the same page where you written the main code.
For example-
<form name="newform" id="regForm" action="inex.php" method="post">
<?php
//and your php post code here
?>
This can achieved through the use of AJAX and the serialization of the form. This is written with the assumption that the php script returns a status message (html block looking to be displayed) upon successful completion. This can also be helpful for error handling, in the event there is an issue within the php script. This example makes use of the jQuery library.
<form name="myForm" id="myForm">
<input type="text" name="input1">
<input type="text" name="input2">
</form>
// Using jQuery
$('#myForm').submit(function(e) {
//Prevent Default
e.preventDefault();
// Gather Form Values into Array
var values = {};
$.each($('#myForm').serializeArray(), function(_, kv) {
values[kv.name] = kv.value;
});
$.ajax({
method: "POST",
url: "pathToFile/formHandlingFile.php",
dataType: "html",
data: {
vals: values
}
})
.done(function(data) {
$('#main').hide()
$('#success').html(data)
$('#success').show()
})
});
I've created a Vue app with a form. When the user clicks on submit the submit is handled by a JavaScript function that sends an ajax request (using Axios). The data sent is a custom JSON object I've created from combining the data from the input fields. I've created some dummy code below just to show the idea:
<form method="post" v-on:submit.prevent>
<input name="emailAddress" v-model="emailAddress" autocomplete="email"/>
<button type="submit" v-on:click="submit()">Submit</button>
</form>
submit: function(){
var jsonObject = {testValue : this.emailAddress +"123"};
axios.post(MY_URL, jsonObject)
.then(response => {
...
})
.catch(error => {
....
})
}
After submitting once and reloading the page I was hoping that the recent email input would show up as suggestions in the email input field but that doesn't happen. My guess is that this doesn't happen because I dont submit the form with the email input using multipart/form-data.
Is there any way to update the browser's autocomplete/autofill when submitting the form the way I'm doing?
try putting this in your form
autocomplete="on"
https://www.w3schools.com/tags/att_input_autocomplete.asp
You need to specify type of the input field type="email"
Note: The autocomplete attribute works with the following types: text, search, url, tel, email, password, datepickers, range, and color.
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.
I'm stuck.
I have a regular HTML form that submits to itself.
<form action="<?php print $phpSelf;?>" method="post" id="PO">
<input>...</>
<input>...</>
<input>...</>
<input type="submit" id="btnCreate" name="btnCreate" value="Create" tabindex="900" class="button">
</form>
And I have an array in Javascript, I'll call it
var jArray;
I need to get the information from the form, and the information from the Javascript array. I can get each of them separately, but I don't know how to get them at the same time.
For the Javascript, this is the method I am using.
function submitPO(){
$.ajax({
type:"post",
url: "jsTo.php", //Send the variable to this page
data:{partsToAdd: jArray}, //{variable name (POST), data to be passed}
cache:false,
success: function(html){ //Function to execute when successful
console.log("Success in the function");
$('p#msg').html(html);
}
});
return false
}; //End of SubmitPO
<p id = "msg"></p>
<form>
<input type="submit" value = "submit" onclick = "return submitPO();">
</form>
When I press the button, it sends the array to jsTo.php where I can get it.
$selectedParts = $_POST['partsToAdd'];
That works fine. I use a similar method for getting the information from the HTML form.
$To = htmlentities($_POST["To"], ENT_QUOTES, "UTF-8");
So, like I mentioned above, I can get either the data from the javascript array, or the data from the form, but not both. Anyone able to help me figure this out? I've looked all over SO, and have found tons of resources on how to submit multiple forms with one button, how to post from JS to PHP, etc., but nothing that has touched on this issue.
You can get the data from the form with .serialize then you can add it to the array data with $.param
data:$.param({partsToAdd: jArray})+'&'+$('#PO').serialize(),
You can just serialized your form.
in your ajax data, just do
data: $('form').serialize()
I'm trying to combine a form.submit() call with a jquery/ajax call to get a response from my php login script - I've just spent a few hours trying to hack together some of the hundreds of posts/examples on a similar topic but am out of ideas now so am hoping someone can help.
My sign in form looks like this...
<form id ="signInForm" action= "/userManagement/proxy_process_login.php" method="post" name="login_form">
<input required id="signInUserId" name="email" type="text" placeholder="Username/Email" class="input-medium">
<input required id="signInPassword" name="password" type="password" placeholder="Password" class="input-medium">
<button id="signin" name="signin" class="btn btn-success" onclick="signInSubmit(this.form, this.form.signInPassword);">Sign In</button>
</form>
The function signInSubmit() (called by the button's onclick) simply validates the text fields, and replaces the plain text password with a hashed version before finally calling "form.submit()", like this...
//ommited a bunch of text input validation
var p = document.createElement("input");
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
password.value = ""; // Make sure the plaintext password doesn't get sent.
form.submit();
My PHP script (proxy_process_login) also works fine before adding any jquery/ajax and essentially does this...
if (login($email, $password, $mysqli) == true) {
// Login success (ok to reload existing page)
header("Location: ../index.php?login=success");
exit();
} else {
// Login failed (do NOT want to reload page - just message "fail" back via AJAX so I can update page accordingly)
echo "fail";
exit();
}
But given the route I'm taking to submit the form, I'm struggling to incorporate an Ajax example - because I've got this new "form" variable (with the hashed p variable appended), so I can't use an Ajax call which refers back to the form using jquery like this...
$.ajax({type:'POST', url: '/userManagement/proxy_process_login.php', data:$('#signInForm').serialize(), success: function(response) {
console.log(response);
}});
(because the jquery reference doesn't include the new variable, and I've already specified the php script in the action attribute of my form)
And I also can't call something like "serialize()" on my "form" variable inside signInSubmit().
Any ideas on an appropriate way to structure a solution to this?! Thanks!
Unfortunately there is no callback for native form submission using action attribute , it was used in the past to redirect you to that page and show the results there.
Modern method now is to use ajax call , after perventingthe default submission.
Solution:
HTML:
<form id="myForm">
<!-- form body here --!>
</form>
Javascript:
$("#myForm").submit(function(e){
e.preventDefault();//prevent default submission event.
//validate your form.
//disable your form for preventing duplicate submissions.
//call you ajax here.
//upon ajax success reset your form , show user a success message.
//upon failure you can keep your fields filled , show user error message.
})
this is a typical algorithm i use in any project i do , i recommend using parsley JS for front-end validation.