I've inherited some PHP code, never having worked with it before, and I'm stuck. I've tried to use echo like I would console.log() in JS, but I'm hardly getting into the script.
I'm trying to post 3 input values and a select option to PHP code, and email that information off to someone. Fairly simple I would assume.
HTML
<form method="post" class="contact-form" id="register-form">
<fieldset>
<input type="text" name="first_name" placeholder="First Name" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="firstName" required>
<input type="text" name="last_name" placeholder="Last Name" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="lastName" required>
<input type="text" name="location_preference" placeholder="Location Preference" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="locationPreference" required>
<select name="internType" style="width: 100%; display: block; color: #000;" id="internType" required>
<option selected="" value="default">Please Select</option>
<option value="inside">Inside</option>
<option value="outside">Outside</option>
<option value="open">Open</option>
</select>
<button name="submit" type="submit" class="btn btn-success submitinformation pull-right" id="submit"> Submit</button>
<button name="reset" type="reset" class="btn btn-success submitinformation pull-right" id="reset"> Reset</button>
</fieldset>
</form>
Pretty basic..
JavaScript
var PATH = 'processor.php';
var APP = 'wse01010';
$("#register-form").on("submit", function(e){
e.preventDefault();
var errors = 0;
var inputs = $('input:text, #internType');
$(inputs).map(function(){
if( !$(this).val() || $(this).val() == "default") {
$(this).addClass('warning'); //Add a warning class for inputs if Empty
errors++;
} else if ($(this).val()) {
$(this).removeClass('warning');
}
});
var formData = $(this).serialize();
console.log(formData);
//console.log($(this)[0]);
//var formData = new FormData( $(this)[0] );
//console.log(formData);
if(errors < 1) {
// If no errors, send POST
$.ajax({
url: PATH + '?i=' + APP,
type: 'POST',
data: formData,
async: true,
success: function (data) {
alert("Success");
},
error: function(xhr, textStatus, errorThrown){
alert('Request failed. Please try again.');
}
});
}
});
This alerts Success every time.
PHP
$firstName = $_POST['first_name'];
if( !isset( $_POST['first_name'] ) ) {
var_dump($_POST); // This gives me an empty array: array(0) { }
$outcomeArr = array(
'outcome'=>'failure',
'message'=>'Step 1 failed.'
);
echo json_encode( $outcomeArr );
exit();
}
unset( $_POST['submit'] );
$postVar = print_r($_POST,true);
//Other code omitted
Here's how the data is being passed.
I'm not sure how to get my Form Data into the correct format (if that's the issue), or why PHP isn't recognizing my POST. I'm also not sure of any other checks I should be doing to validate the POST.
This is the JavaScript that ended up working for me
var form_processor = {
settings : {
'outcome' : -1,
'status' : 0, // 0 == correct, 1 == errors detected
'error_msg' : '',
'path' : 'processor.php',
'app' : 'wse01010'
},
sendData : function(formData){
var self = this;
$.ajax({
url: self.settings.path + '?i=' + self.settings.app ,
type: 'POST',
data: formData,
async: true,
success: function (data) {
toastr.success('Your request went through!', "Success")
},
error: function(xhr, textStatus, errorThrown){
toastr.error("Something went wrong. Please try again.", "Error!")
},
cache: false,
contentType: false,
processData: false
});
},
bindForm : function(){
var self = this;
$('.contact-form').submit(function(e){
self.settings.formObj = $(e.target);
e.preventDefault();
var errors = 0;
var inputs = $('input:text, #internType');
$(inputs).map(function(){
if( !$(this).val() || $(this).val() == "default") {
$(this).addClass('warning'); //Add a warning class for inputs if Empty
errors++;
} else if ($(this).val()) {
$(this).removeClass('warning');
}
});
if( errors > 0 ) {
self.settings.status = 0;
self.settings.error_msg = '';
toastr.error("Please fill in all of the fields.", "Error!")
return false
} else {
formData = new FormData( $(this)[0] );
self.sendData(formData);
}
});
},
init : function(){
this.bindForm();
}
}
form_processor.init();
In your PHP, you start off with this:
echo "1";
When using AJAX, an echo is the same as a return, so this is where your function stops. Remove all unnecessary echo's or your function will simply not continue.
Furthermore, you are using spaces in your HTML name attributes:
<input type="text" name="first name"> <!-- Incorrect -->
Use underscores instead or you will not be able to retrieve the value properly:
<input type="text" name="first_name"> <!-- Correct -->
Afterwards, $firstName = $_POST["first_name"]; is the correct way to retrieve your values in PHP.
I recommend to not use space in name so change that in firstname etc.
for serializing u need this.
$(function() {
$('#register-form').on('submit', function(e) {
var data = $("#register-form").serialize();
$.getJSON("http://YOUR PHP FILE TO CATCH IT &",data)
});
});
on your php page use $_GET['firstname'] for example and add that to a variable.
Your code is setting the content type of the form twice, and both times incorrectly:
Drop enctype="multipart/form-data" from the <form> tag. (This is for file uploads)
Drop contentType: "application/json; charset=utf-8" from the jQuery ajax() call. (This is for JSON, which PHP does not understand natively)
The correct encoding is application/x-www-form-urlencoded, which is the default value for both the <form> tag and the ajax() call.
Related
I use a form that posts comments. It is short with the fields Name, Mail and Comment. However, when the site is open, through another language, for example from German, it is opened in English website.com - Duith version, website.com/en/ - english version. I get a problem and the form gives an error: "An error occurred while processing the form"
Once I debugged it turned out that there was some "redirect" from 302 to 200, how can I solve the problem with this redirection and not get this problem anymore?
POST - https://website.com/?do=comments
Status - 302 Found
GET - https://website.com/en/?do=comments
Status - 200 OK
This is my HTML
<form action="/?do=comments" method="post" id="f5feafacf21681" class="b-comment_form" data-ajax="true">
<div class="form-group form-group-25">
<div class="form">
<label class="required">Name:</label>
<input type="text" name="name" required autocomplete="name" />
</div>
<div class="form">
<label class="required">E-mail:</label>
<input type="text" name="email" placeholder="E-mail" required autocomplete="email" />
</div>
</div>
<div class="form">
<textarea name="text" rows="5" placeholder="Comment" required></textarea>
</div>
<div class="form">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="module" value="news" />
<input type="hidden" name="module_id" value="10707" />
<button type="submit" class="btn btn-primary submit">Save</button>
</div>
</form>
This is my JS
// Class for submitting forms
var Form = function() {
this.init();
};
Form.prototype = {
init: function() {
var _this = this;
$(document).on('submit', 'form[data-ajax]', function(e) {
e.preventDefault();
if ( ! $(this).hasClass('form-loading') ) {
_this.submit( $(this).attr('id') );
}
});
},
submit: function(form_id, callback) {
if ( ! form_id ) form_id = 'form';
var form = $('#' + form_id), url = form.attr('action'), btn = form.find('*[type="submit"]');
if ( form.attr('enctype') == 'multipart/form-data' ) {
var str = new FormData(form[0]),
multipart = true;
str.append('form_id', form_id);
str.append('utm_url', this_url);
str.append('utm_title', this_title);
} else {
var str = form.serialize() + '&form_id=' + form_id + '&utm_url=' + this_url + '&utm_title=' + this_title,
multipart = false;
}
$.ajax({
url: url,
type: 'POST',
data: str,
dataType: 'json',
contentType: ( multipart ) ? false : 'application/x-www-form-urlencoded; charset=UTF-8',
processData: ( multipart ) ? false : true,
beforeSend: function() {
form.addClass('form-loading');
btn.addClass('process');
},
success: function(data) {
if ( data == 'error' ) return false;
if ( callback && typeof(callback) === "function" ) {
callback(form_id, data);
} else {
if ( data.answer == 'stop' ) {
error( data.error );
} else {
if ( data.success ) success( data.success );
}
if ( data.eval ) eval( data.eval );
}
},
error: function() {
error( 'An error occurred while processing the form' );
},
complete: function() {
form.removeClass('form-loading');
btn.removeClass('process');
if ( form.find('#captcha') ) reload();
}
});
}
}, $(document).ready(function() {
Form = new Form
});
I have created an AJAX function in Wordpress. The function is called on form submission. The function is run, but it is not receiving any of the form data that I have submitted. What am I missing?
PHP Function
I have added the PHP function here, which is called successfully via AJAX. This form creates a new user successfully, but only when I create the variables manually (eg. see $new_user_data['user_login'] = 'This Text Works';). For some reason, the $_POST data isn't coming through to the function.
add_action("wp_ajax_register_user", __NAMESPACE__ . "\\register_user");
add_action("wp_ajax_nopriv_register_user", __NAMESPACE__ . "\\register_user");
function register_user() {
// NONCE VERIFICATION
if ( !wp_verify_nonce( $_REQUEST['nonce'], "rtr_register_nonce")) {
exit("Oops! This is embarassing!");
}
// Get all post data for the user.
$new_user_data = array();
$new_user_data['first_name'] = sanitize_text_field($_POST['first-name']);
$new_user_data['last_name'] = sanitize_text_field($_POST['last-name']);
$new_user_data['user_email'] = $_POST['email'];
$new_user_data['user_pass'] = sanitize_text_field($_POST['password']);
$new_user_data['user_login'] = 'This Text Works';
$new_user_data['role'] = 'subscriber';
// Create the User
$registered_user = wp_insert_user( $new_user_data );
$result['user'] = $registered_user;
// AJAX CHECK
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
JQuery
function registerUser(){
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("form-tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm()) {
return false;
}
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
//document.getElementById("regForm").submit();
registerUser();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
$('#nextBtn').click(function () {
nextPrev(1);
});
$('#prevBtn').click(function () {
nextPrev(-1);
});
Form
<?php
$nonce = wp_create_nonce("rtr_register_nonce");
$link = admin_url('admin-ajax.php?action=register_user&nonce='.$nonce);
?>
<form id="regForm" <?php echo 'data-nonce="' . $nonce . '"'; ?> action="<?php echo $link; ?>" method="post" enctype="multipart/form-data">>
<div class="my-3 text-center">
<span class="form-step">1</span>
<span class="form-step">2</span>
</div>
<div class="form-tab">
<p><input name="first-name" placeholder="First Name" oninput="this.className = ''"></p>
<p><input name="last-name" placeholder="Last Name" oninput="this.className = ''"></p>
<p><input name="dob" type="date" oninput="this.className = ''"></p>
</div>
<div class="form-tab">
<p><input name="email" type="email" placeholder="Email" oninput="this.className = ''"></p>
<p><input name="password" type="password" placeholder="Password" oninput="this.className = ''"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="btn btn-brand" id="prevBtn">Previous</button>
<button type="button" class="btn btn-brand" id="nextBtn">Next</button>
</div>
</div>
</form>
Seems you are not triggering registerUser() check following script works fine for me
jQuery(document).ready(function($) {
jQuery('body').on('click', '#nextBtn', function() {
registerUser();
});
});
function registerUser(){
var nonce = jQuery('#regForm').attr("data-nonce");
var formData = jQuery('#regForm').serialize();
jQuery.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
add method="post" to your 'form' - 'get' is the default https://stackoverflow.com%2Fquestions%2F2314401%2Fwhat-is-the-default-form-http-method&usg=AOvVaw1dKc3hW4K6r5SwQurLztBw
The "user_login" is a username of the user so probably it doesn't accepts space too.
See also WP Insert Post
Please try passing some username such as "custom_user" and see the result.
Hope this might work.
Ok it was a bit of help from everyone here. But yes, I was calling the AJAX correctly, but not actually submitting the form. I added a .on(submit) to the form and then added a listener to the form to perform the AJAX call on submit. Here's the amendments below.
function nextPrev(n) {
var x = document.getElementsByClassName("form-tab");
if (n === 1 && !validateForm()) {
return false;
}
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
// ADDED THIS SUBMIT() HERE
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// ADDED AN EVENT LISTENER TO TRIGGER THE AJAX CALL HERE
$('#regForm').on('submit', function () {
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data: {
action: 'register_user',
nonce: nonce,
formData: formData
},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
});
This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/
I am trying to upload a file with ajax and php without page refresh and for submit.
my code is able to run and alert the valid message if I just do the preg_match, but when I add the rest of the validation which need to use the $_FILES[$filrec]["tmp_name"], it won't alert me the valid message.
What is wrong here? isn't it possible to upload the file without submitting the form with the following method?
There are bunch of different suggestions and examples with more complicated javascript or jquery methods, but I am trying to simply the ajax and leave the rest for PHP. is that possible with my bellow ajax function ?
Javascript :
var fileselected = $("#browse").val().replace(/C:\\fakepath\\/i, '');
setTimeout(function() {
$.ajax({
type: 'POST',
url: "ajax/extval.php",
data: {fileprs: fileselected},
dataType: 'json',
cache: false,
success: function(resuval) {
// file validation result
if (resuval === "valid"){
alert ("valid")
PHP :
<form id="upload" method="post" class="<?php echo $orvalue."<separator>".$user_id ?>" action="" enctype="multipart/form-data">
<div id="formcontent">
<label class="required" for="unitprice" title="Unit price"><input type="text" id="unitprice" name="unitprice" />Unit price</label>
<label class="required" for="qty" title="How many pcs"><input type="text" id="qty" name="qty" />Quanity</label>
<label class="required" for="express" title="Express within China"><input type="text" id="express" name="express" />Express</label>
<label class="required" for="linkURL" title="Insert a full URL http:\\"><input type="text" id="linkURL" name="linkURL" />Link</label>
<label for="yourdesc" title="Describe your need clearly"><textarea id="yourdesc" name="yourdesc"></textarea>Description<li><font size="-2">You can type 400 letters only, you typed :</li><li id="lettercounter"></li>letters</font></label>
<label for="formsubmit" class="nocontent"><input type="button" id="submitButton" href="#" class="progress-button" value="Add to order" /><strong>Note:</strong> Items marked <img src="../../images/required.jpg" alt="Required marker" width="20" height="20" /> are required fields</label>
</div>
</form>
PHP :
$filrec =mysql_real_escape_string($_POST['fileprs']);
if(preg_match("/\.(gif|png|jpg|JPG|jpeg|bmp|BMP)$/", $filrec))
{
$fileType = exif_imagetype($_FILES[$filrec]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
$allin = "valid";
echo json_encode($allin);
}
Appreciated
You can use the following PHP code to get the file received from Ajax:
$data = split(",",file_get_contents('php://input'));
$img_data = base64_decode($data[1]);
file_put_contents( 'uploads/' . $_SERVER['HTTP_X_FILENAME'],
$img_data );
You can use Following Ajax POST Request this will help you
<script>
$(document.body).on('click','.postDefects',function(){
var form_data = new FormData();
var defect = $(this).closest('tr').find( "input[name='defect_id']" ).val();
var txt_defect=$("#text_defect").val();
var upload_defect = document.getElementById("upload_defect").files[0];
form_data.append("upload_defect",upload_defect);
form_data.append("defect_id",defect_id);
form_data.append("txt_defect",txt_defect);
console.log(form_data);
$.ajax({
url:"postsample_defects.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading..</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
});
});
</script>
I've been trying to figure this out, but it seems to be harder than i first thought. However, what I'm trying to do is make an ajax post request, but the POST seems to be empty when I'm sending it.
My HTML File
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm', 'name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
My Javascript
$('#statusUpdateForm').submit(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
My PHP (Some of my medhod in the controller)
// Check if the input is a ajax request
if($this->input->is_ajax_request()) {
echo $_POST['profileUpdate'];
}
Notice, when i put echo "Hello World" etc in the controller, i do get "Hello World" in the alert box from the javascript.
I've also tried a var_dump on $_POST and it returns array(0){} When I'm trying to output the specific $_POST['profileUpdate'] variable i get an error like this,
I've also done a alert from the seralize function i JS, this is what i got,
Is there anyone who know how i can fix this problem?
Try changing method to type.
I'm guessing the script is performing a GET request, which is the default setting when using ajax(), instead of a POST request. Like this:
$.ajax({ // Starter Ajax Call
// "method" isn't an option of $.ajax
// method: "POST",
type: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
Try The following Code
In View add the following form
<?php echo form_open('welcome/CreateStudentsAjax'); ?>
<label for="roll">Student Roll Number</label>
<input type="text" id="txtRoll" value="" name="roll"/>
<label for="Name">Students Name</label>
<input type="text" id="txtName" value="" name="name"/>
<label for="Phone">Phone Number</label>
<input type="text" id="txtPhone" value="" name="phone"/>
<input type="submit" name="submit" value="Insert New Students" />
<?php echo '</form>'; ?>
The JQuery Part is below
$(document).ready(function(){
$('form').submit(function(){
//alert('ok');
$.ajax({
url:this.action,
**type:this.method,**
data:$(this).serialize(),
success:function(data){
var obj = $.parseJSON(data);
if(obj['roll']!=null)
{
$('#message').text("");
$('#message').html(obj['roll']);
$('#message').append(obj['name']);
$('#message').append(obj['phone']);
}
else
{
$('#message').text("");
$('#message').html(obj);
}
},
erro:function(){
alert("Please Try Again");
}
});
return false;
});
});
</script>