Hello guys i have this php jquery ajax create user form that passes the create details to the php script but i keep getting null on the post variables anyhelp would be appreciated! code below
Html:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*" id="createUserPass">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" id="createUserPass">
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control"><option value="yes">Ja tak!</option><option value="nej" selected="">Nej tak</option></select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
jquery:
$(document).ready(function(){
$("#submitCreateUser").click(function(){
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#createUserPassC").val();
var newsletter = $("#newsletter").val();
$.ajax({
type: "POST",
url: "createuserajax.php",
data: "username="+username+"&email="+email+"&pass="+pass+"&cPass="+cPass,
success: function(html){
if(html=='true')
{
alert(username);
}
else
{
}
},
}
);
});
});
PHP:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
var_dump($username);
$securePassword = md5(($password));
$sqlInsertUser = "INSERT INTO users (username,email,password) VALUES ('$username','$email','$securePassword')";
$result = mysqli_query($con,$sqlInsertUser);
As adeneo says, your html form is likely being submitted the standard way before the ajax call is made because you haven't prevent the default behaviour. try the below instead:
Alternatively, you could remove <input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!"> and give the id="submitCreateUser" to some other element like a custom button or link. When you click and input tag with the type submit it will submit the accompanying form the normal way by default. This happens before the click handler hears the click so the form is submitted before your code call the ajax. Use a different element for the click and this wont happen
And don't forget for this to work at all, your php file must echo something which will be returned in your html variable, without that html will never be true and nothing will ever happen.
Part of your problem is that your input elements, specifically the ones for the password and password checks both have two separate id tags the first is duplicated and the second is a different id altogether. Also in your jquery, when you try to get the id check value you use another, different, id.
Here is a test page that address all of these issues and works as expected:
http://dodsoftware.com/sotests/createuserajax.html
The test php code:
<?php
if( isset($_POST) )
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
echo 'username --'.$username.', email --'.$email.', password --'.$password;
}
?>
The html code:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" >
<!-- these lines had duplicated id tags-->
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control">
<option value="yes">Ja tak!</option>
<option value="nej" selected="">Nej tak</option>
</select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
The jQuery code:
<script>
$(document).ready(function() {
$("#submitCreateUser").click(function( event ) { // add event var here
event.preventDefault(); // add this line to stop the form from submitting the normal way before the ajax call
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#confirmUserPass").val(); // you were using "#createUserPassC" here in error
var newsletter = $("#newsletter").val();
var datastring = "username=" + username + "&email=" + email + "&pass=" + pass + "&cPass=" + cPass +"&newsletter=" + newsletter;
$.ajax({
type: "POST",
url: "createuserajax.php",
data: datastring,
success: function(html) {
if (html) { // changed this line from "if (html == 'true')" just for testing
alert(html); // changed this line from "alert(username);" just for testing
} else {
alert('something went wrong!');
}
},
});
});
});
</script>
Related
In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;
I tried to validate by submitting a form by using ajax on codeigniter, when I want to insert data but only a few input fields only and input field that I do not use I try to hide, but attr required still running on the input field that I have hidden, how to solve this. so delete the required input field when hidden.
Views
<form id="fr" method="post" class="form-horizontal form-label-left">
<div class="form-group">
<label for="fullname">Section * :</label>
<select name="section" class="form-control" required="required">
<option value="">Select section</option>
<option value="manager">Manager</option>
<option value="head manager">Head Manager</option>
</select>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Kitchen * :</label>
<input type="text" name="name_kitchen" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Resto * :</label>
<input type="text" name="name_resto" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="fullname"> </label><br>
<button type="button" id="submit" class="btn btn-primary"><i class="fa fa-save"></i> Simpan</button>
</div>
</form>
<script>
$("[name='section']").change(function(){
var value=$(this).val();
if(value == "manager"){
$("[name='name_kitchen']").hide();
$("[name='name_resto']").show();
}else{
$("[name='name_kitchen']").show();
$("[name='name_resto']").hide();
}
});
$("#submit").click(function() {
$.ajax({
type: "POST",
url: base_url+"add",
dataType: 'json',
data: $('#fr').serialize(),
success: function(data) {
if(data.status) {
$(".add-from-staff").toggle("slow");
$("#fr").load(location.href + " #fr");
$('form#fr input[type="text"],texatrea, select').val('');
}else {
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
},
error: function (request, jqXHR, textStatus, errorThrown) {
alert('Error');
console.log(request.responseText);
}
});
});
</script>
Controllers
public function add() {
$this->_validate();
$insert = $this->My_models->_add();
echo json_encode(array("status" => TRUE));
}
function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('name_kitchen') == '')
{
$data['inputerror'][] = 'name_kitchen';
$data['error_string'][] = 'Kitchen is required';
$data['status'] = FALSE;
}
if($this->input->post('name_resto') == '')
{
$data['inputerror'][] = 'name_resto';
$data['error_string'][] = 'Resto is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
so how when I choose one of the select options that hide disabled required?
when u are hiding any div u can get the element and remove its required attribute using jquery
$("[name='name_kitchen']").removeAttr('required');
e.g:
$("#elementID").removeAttr('required');
In this example I would not use the required attribute. It is causing more headaches than it is worth. Instead, rely on the server-side validation.
To determine which "section" is in use it seems to me that passing another piece of info to the controller would be the easiest way to solve the problem. This could be done many different ways. Adding another hidden field is one option.
Somewhere inside the <form> add
<input type="hidden" id="use-section" name="use_section" value="">
It is not clear that you have a "default" section shown when you first show the page. If there is one then use that for the "value" in the above field.
During the handler
$("[name='section']").change(function(){ ...
set the value of the "use_section" field.
var value=$(this).val();
$("#use-section").val(value);
You can evaluate the "use_section" in your controller, or in your case, in the model which is where I assume you are capturing the data posted.
if($this->input->post('use_section') === "manager")
{
//get the fields you want
}
else
{
//get the other fields
}
I have a suggestion regarding _validate(). Instead of calling exit() to short-circuit add() return a value - TRUE if it works, or $data if it doesn't. The last few lines of _validate() become
if($data['status'] === FALSE)
{
return $data;
}
return TRUE;
Then use this add() method
public function add()
{
if(TRUE === ($status = $this->_validate()))
{
$insert = $this->My_models->_add();
$status = array("status" => TRUE);
}
echo json_encode($status);
}
Use of exit or die in CodeIgniter is, IMO, not appropriate because it short-circuits the framework's designed execution flow.
I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work
I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.
I am trying to post contact page data to my view, but it stopped working when I included if else statements.
Here is my script:
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
}else
{
return true;
}
}
</script>
And here is my form:
<form class="contact-form">
{% csrf_token %}
<p class="input-block">
<label for="contact-name"><strong>Name</strong> (required)</label>
<input type="text" name="name" value="" id="contact-name" required>
</p>
<p class="input-block">
<label for="contact-email"><strong>Email</strong> (required)</label>
<input type="email" name="email" value="" id="contact-email" required>
</p>
<p class="input-block">
<label for="contact-subject"><strong>Subject</strong></label>
<input type="text" name="subject" value="" id="contact-subject">
</p>
<p class="textarea-block">
<label for="contact-message"><strong>Your Message</strong> (required)</label>
<textarea name="message" id="contact-message" cols="88" rows="6" required></textarea>
</p>
<div class="hidden">
<label for="contact-spam-check">Do not fill out this field:</label>
<input name="spam-check" type="text" value="" id="contact-spam-check" />
</div>
<input type="submit" value="Submit" onclick="javascript:Submit();">
<div class="clear"></div>
</form>
Without the if else it was working fine but now all pages are reloading with all form data as query parameters. How can I correct this?
First you need to prevent the default action if you are trying to do AJAX.
Since, I see you are already using jQuery. I recommend adding the following to the top of your <script>:
$("#contact-form").submit(function(e){
e.preventDefault();
Submit();
});
Obviously, you won't need this anymore..
onclick="javascript:Submit();"
Now run this code in any sort of javascript debugger (Chrome and Safari both have good ones) and you should be good!
Try this please..i hope it works...
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".contact-form").submit(function(e){
e.preventDefault();
Submit();
});
});
</script>
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
}
}
You need to return a false from your Submit() function. Also, call the function from the form tag using onsubmit handle.
<form class="contact-form" onsubmit="Submit();">
and in Submit() function:
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
} else {
return true;
}
Do not use javascript: in an onxxx event handler. javascript: is a protocol specifier that goes on a URL, but the onclick handler expects raw javascript, not a URL.
You need to return false from the onclick to prevent the default action of submitting the form. I assume you do want to prevent the default and use AJAX instead?