Jquery-form-plugin implementation to current request call - php

I have a form with multiple file upload as well as others field along, normally I will request jquery ajax to process the data as below, and I can alert all input parameters and pass to server-side to perform certain task.
Since I have upload field in this form, I has acknowledged that is impossible to passes files data through $('#my_form').serialize(), I have some search here and know jquery form plugin can help with this issue, but I don't really get to know how it works, I hope somebody can enlighten me here with working example on how can I implement to above ajax method, and also how can I alert all input values is in post before send to sever-side to process, thanks for help!!!
Here is the current ajax request which is cannot see 'input type "file"' parameter:
$('#btn_submit').click(function(){
var parameters = $('#my_form').serialize();
var btn = $(this);
btn.button('loading')
alert(parameters);
$.ajax({
url: 'inc/callback/process.php',
type: 'POST',
data: parameters,
dataType: 'json',
success: function(response){
if(response.success == 'success'){
$('#successful').show().html('<b>saved!</b>');
}else{
$('[id$="_error"]').html('');
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
}).always(function(){
btn.button('reset')
});
});
<form class="form-horizontal" role="form" method="post" id="my_form" enctype="multipart/form-data">
<input type="hidden" name="user_id" value="<?php echo $data->userid ?>">
<input type="hidden" name="list_id" value="<?php echo $listid ?>">
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="files[]" class="multi" accept="gif|jpg" maxlength="3" />
</div>
<div class="form-group">
<label for="publish"></label>
<input type="checkbox" name="publish" <?php echo $checked ?>> Publish</div>
</div>
<div class="form-group">
<label for="email">Name</label>
<input type="text" id="name" name="name" value="<?php echo $list->name ?>"><span class="error" id="name_error"></span>
</div>
<hr />
<button class="btn btn-success" id="btn_submit" type="button" data-loading-text="Loading...">Save</button>
</form>
EDITED:
I've been tried the code provided by #Markus Fröhlich, but the form will submitted directly to inc/callback/process.php, seems like the ajaxForm doesn't trigger as well as alert never shown!
//this jq is refer as external js file at the bottom before </body>
$("#my_form").ajaxForm({
dataType: "json",
beforeSend: function() {
var btn = $(this);
btn.button('loading')
alert(parameters);
},
uploadProgress: function(event, position, total, percentComplete) {
console.log(percentComplete); // Show the completed percent
},
success: function(response) {
if(response.success == 'success'){
$('#successful').show().html('<b>Edited saved!</b>');
}else{
$('[id$="_error"]').html('');
// display invalid error msg
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown );
}
}).always(function(){
btn.button('reset')
});
<form class="form-horizontal" role="form" method="post" id="my_form" enctype="multipart/form-data" action="inc/callback/process.php">
<input type="hidden" name="user_id" value="<?php echo $data->userid ?>">
<input type="hidden" name="list_id" value="<?php echo $listid ?>">
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="files[]" class="multi" accept="gif|jpg" maxlength="3" />
</div>
<div class="form-group">
<label for="publish"></label>
<input type="checkbox" name="publish" <?php echo $checked ?>> Publish</div>
</div>
<div class="form-group">
<label for="email">Name</label>
<input type="text" id="name" name="name" value="<?php echo $list->name ?>"><span class="error" id="name_error"></span>
</div>
<hr />
<button class="btn btn-success" id="btn_submit" type="submit" data-loading-text="Loading...">Save</button>
</form>

This code should works with ajaxForm! (Not tested!!!)
Don't forget the new form action, and the Button Type is now "submit".
$("#my_form").ajaxForm({
dataType: "json",
beforeSend: function() {
var btn = $(this);
btn.button('loading')
alert(parameters);
},
uploadProgress: function(event, position, total, percentComplete) {
console.log(percentComplete); // Show the completed percent
},
success: function(response) {
if(response.success == 'success'){
$('#successful').show().html('<b>saved!</b>');
}else{
$('[id$="_error"]').html('');
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
},
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown );
}
});
<form action="inc/callback/process.php" class="form-horizontal" role="form" method="post" id="my_form" enctype="multipart/form-data">
<input type="hidden" name="user_id" value="<?php echo $data->userid ?>">
<input type="hidden" name="list_id" value="<?php echo $listid ?>">
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="files[]" class="multi" accept="gif|jpg" maxlength="3" />
</div>
<div class="form-group">
<label for="publish"></label>
<input type="checkbox" name="publish" <?php echo $checked ?>> Publish</div>
</div>
<div class="form-group">
<label for="email">Name</label>
<input type="text" id="name" name="name" value="<?php echo $list->name ?>"><span class="error" id="name_error"></span>
</div>
<hr />
<button class="btn btn-success" id="btn_submit" type="submit" data-loading-text="Loading...">Save</button>
</form>

Related

Ajax request is retrieving an empy array in PHP

I have a "form" with this code:
<div class="form-wrap" id="contact-form">
<div class="form-innerwrap">
<div class="text-input">
<input type="text" name="name" id="name" required />
<label for="name"><?= CONTACT_FORM_NAME ?></label>
</div>
<div class="text-input">
<input type="email" name="email" id="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<label for="email">E-mail</label>
</div>
<div class="text-input">
<input type="text" name="contact" id="contact" required />
<label for="name"><?= CONTACT ?></label>
</div>
<div class="text-input text-textarea">
<textarea type="info" id="info" name="info">
</textarea>
<label for="email"><?= CONTACT_FORM_MENSSAGE ?></label>
</div>
<input type="hidden" name="lang" id="lang" value="<?= $_SESSION['language'] ?>">
<div class="form-button">
<button type="submit" class="btn contacts-button btn-gowe" id="btn-info" data-btnhover="<?= CONTACT_FORM_BTN ?>"> <span><?= CONTACT_FORM_BTN ?></span> </button>
</div>
</div>
</div>
Then I have a ajax request to sent the input values to php:
$("#btn-info").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var contact = $("#contact").val();
var info = $("#info").val();
var lang = $("#lang").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email +'&contact='+contact+'&info='+info+'&lang='+lang;
$.ajax({
type: "POST",
url: "includes/sendEmail.php",
data: dataString,
cache: false,
success: function(result){
var result = result.split("||");
if (result[0]== "true"){
$("#contact-modal").show();
}
}
});
return false;
});
However when I make a var_dump of $REQUEST the return is an empty array.
Can anyone help me with this problem?
I had already spent several hours to try to understand what is wrong in my code.
Thanks for helping.

How to make jquery script work for new generated form

I have one script which display the form on click response
$(".table th .glyphicon-edit").one('click', function(){
var $this = $(this);
var sectionName = $(this).attr('data-sectioname');
var courseId = $(this).attr('data-courseid');
var sectionId = $(this).attr('data-sectionid');
$.get('/edit_section', { section: sectionName, id: courseId, sectionid: sectionId}, function(response) {
$this.closest('thead tr').after(response);
});
});
"edit_section" page
<form method="POST" action="http://localhost:8000/managecourse/162" accept-charset="UTF-8" id="edit" class="form-horizontal">
<input name="_method" value="PUT" type="hidden">
<input name="_token" value="duTA8TbvmYeJWUA21VTGqZYisQZu1ouuhvbXCouv" type="hidden">
<input name="sectionid" value="1" type="hidden">
<input name="courseid" value="162" type="hidden">
<div class="form-group">
<label for="section_name" class="col-md-4 control-label text-right">Name sectiton</label>
<div class="col-md-6">
<input class="form-control" name="section_name" value="Name_section" id="section_name" type="text">
</div>
</div>
<div class="form-group text-center">
<input name="edit" class="btn btn-primary" value="Save" type="submit">
</div>
</form>
And then I have script to submit this form but it doesn't work
$('#edit').submit(function(e) {
e.preventDefault();
var sectionName = $('input#section_name').val();
var sectionId = $('input[name=sectionid]').val();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: '/managecourse/update',
data: $('#edit').serialize(),
success:function(data){
console.log(data);
},
});
});
It just display new page with json data but would like to display this data at the same page without reload.
Delegate your submit method. it will work on dynamically added elements.
$(document).on('submit','#edit',function(){
// code
});

file not uploaded to the server with ajax

This is my form source:
<form id="createProject" name="createProject" class="form-light" method="post" enctype="multipart/form-data" target="upload_target">
<div class="col-md-10" id="sandbox-container1">
<label>Project duration</label>
<div class="input-daterange input-group" id="datepicker">
<input type="text" required class="input-md form-control" id="start" name="start" />
<span class="input-group-addon">to</span>
<input type="text" required class="input-md form-control" id="end" name="end" />
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label>Project attachment's</label>
<input type="file" class="form-control" id="projectFile" name="projectFile" placeholder="Select project attachment's">
</div>
</div>
<input type="hidden" id="ownerid" name="ownerid" value="<?php echo $userid; ?>">
<div class="col-md-10">
<div class="form-group">
<button class="btn btn-two pull-right btn-lg" form="createProject" type="submit">Submit</button>
</div>
</div>
</form>
File is not uploading to the server.
I use ajax function to submit.
$.ajax({
url:'ajaxcalls/createprojectfunction.php',
data:$(this).serialize(),
type:'POST',
beforeSubmit: function()
{
/* Before submit */
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
},
success:function(data){
console.log(data);
},
error:function(data){
}
});
Firebug console this error occur.
Notice: Undefined index: projectFile.
but all other input element are accessable in ajax URL php file.
You'll have to use a FormData object to upload a file via ajax,
$.ajax({
url:'ajaxcalls/createprojectfunction.php',
data: new FormData(this),
type:'POST',
processData: false,
contentType: false,
beforeSubmit: function()
{
/* Before submit */
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
},
success:function(data){
console.log(data);
},
error:function(data){
}
});

Ajax call won't pass - form always submitted by php

I've a form which is submitting with php uri_request by default.
Now i was trying to add an ajax call to submit the form, but it's still submitting with php
The ajax call for submitting the form is:
$(document).ready(function() {
$("#contactform").submit(function(e) {
e.preventDefault();
});
$.ajax({
cache: false,
type: 'POST',
data: ("#contactform").serialize(),
url: 'formfiles/submit.php',
// for ajax the submit.php is on a
success: function() {
// separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
return false;
});
and the html form attributes are:
<form action="#n" class="active" method="post" name="contactform" id="contactform">
Also the
e.preventDefault
at the beginning of the ajax call won't work, but without the ajax it work (only the prevent default!)
What is wrong with the code? Why it doesn't work?
Thanks in advance for any help
EDIT here is the html {in an include file ( the hole site is a php dynamic structure)}
<form action="#n" class="active" method="post" name="contactform" id="contactform">
<div class="column">
<div class="obb" style="<?php echo $color[11];?>">
All fields are mandatory
</div>
<div >
<label style="<?php echo $color[0]; ?>"> Name:</label>
<input class="con_campo required" name="name" value="" id="name" type="text" />
</div>
<div >
<label style=""><?php echo $color[8]; ?> </label>
</div>
<div class="fieldcontent prod" id="pr">
<label style=""> <?php echo $color[2]; ?></label>
<select name="prod" value="" id="products" class="selectx required">
<option value=""> -- Select -- </option>
<option value="1"> ITA</option>
<option value="2">DE</option>
<option value="3"> FR</option>
<option value="4">EN</option>
</select>
</div>
<div class="fieldcontent prod" id="in">
<label style="<?php echo $color[4]; ?>"> Address:</label>
<input name="address" value="" id="address" class="required" type="text" />
</div>
<div class="fieldcontent prod" id="ci">
<label style="<?php echo $color[6]; ?>"> City:</label>
<input name="city" value="" id="city" class="con_campo required" type="text" />
</div>
<div class="fieldcontent info help" id="me" >
<label style="<?php echo $color[10]; ?>">Message:</label>
<textarea id="message" name="message" value="" class="cs_comment required" ></textarea>
</div>
<div id="code" style="margin-bottom:25px;">
<label style="<?php echo $color[11]; ?>; width:340px;"></label>
<input type="text" name="code" class="chapta" size="10" maxlength="7" id="code"/>
</div>
</div>
<div class="column" >
<div class="obb"> </div>
<div class="fieldcontent prod" id="co">
<label style="<?php echo $color[1]; ?>">Surname:</label>
<input name="surname" value="" id="surname" class=" required" type="text"/>
</div>
<div >
<label style="<?php echo $color[9]; ?>">Email: </label>
<input name="email" value="" id="email" class=" required email" type="text" />
</div>
<div class="fieldcontent help prod" id="do">
<label style="<?php echo $color[3]; ?>">Domain:</label>
<span style="font-size:20px; margin-left:30px;"> http://</span>
<input name="domain" id="domain" class=" required" type="text" value="" />
</div>
<div class="fieldcontent prod" id="re">
<label style="<?php echo $color[5]; ?>">Region:</label>
<input name="region" value="" id="region" class=" required" type="text" />
</div>
<div class="fieldcontent prod" id="pa">
<label style="<?php echo $color[7]; ?>" >State:</label>
<input name="state" value="" id="state" class="con_campo required" type="text" />
</div>
</div>
<div>
<div class="bottom">
<input type="submit" id="submitButton" name="submit" value="submit" />
<br /><br /><br />
</div>
</form>
</div></div>
<script>
$(document).ready(function() {
$("#contactform").submit(function(e){
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function() { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
});
});
You can restructure your code to fix the problem as below. You don't need return false; since e.preventDefault(); is gonna take care of it.
$(document).ready(function () {
$("#contactform").submit(function (e) {
e.preventDefault();
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(), //note that $ mark is added
url: 'formfiles/submit.php', // for ajax the submit.php is on a
success: function () { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
});
});
You have an error in the ajax call in the line data: ("#contactform").serialize(). It should be data: $("#contactform").serialize()
Try this :
$(document).ready(function() {
$("#contactform").submit(function(e){
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function() { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
},
error: function(error_response){
console.log(error_response);
}
});
});
});
Update :
I see some issues with your code.
Is the required jQuery library loaded ? I don't see that in the html you had pasted. Hopefully you have included it in the header or so.
Add an e.preventDefault (); to prevent the form's default action since the input type is submit. If you don't put that the form will be submitted by default method.
I don't see the script tag closed. You should close the script tag else it will not work. Please see below the updated code:
<script type="text/javascript">
$(document).ready(function() {
$("#contactform").submit(function(e){
e.preventDefault();
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function() { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
});
});
</script>
New Update
Here your ajax call is returning no data. So the server will not know whether the call is success or not, it will always go to the success function. So you have to check whether the response is success or not. From the PHP page return some string like success to show whether the validation or form submission and its processing has been success or else return the error. Also on success callback you are submitting form again, so this will continue as a never ending loop.
Please make the below changes :
<script type="text/javascript">
$(document).ready(function() {
$("#contactform").submit(function(e){
e.preventDefault();
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function(response) { // separate page
if (response == 'success') {
//write what you want to do on success
$('#success').delay(200).fadeIn(200);
} else {
//show error
}
}
});
});
});
</script>
Hope this helps

jquery ajax just isn't working

Ok, thats basically what i got. I also tried static values.
$('#submitForm').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
What i get as response is this:
Object {readyState: 0, responseText: "", status: 0, statusText = "error"}
The php script (just a simple echo) runs as normal after that ajax call. What am i doing wrong? My submit script doesn't look all that wrong to me and i'm not doing XSS. : - (
My HTML Form looks like this:
<form action="http://dev.xxxxxxx.de/users/register" method="post" accept-charset="utf-8" class="form-horizontal" id="submitForm"> <div class="control-group">
<label class="control-label" for="inputUsername">Nickname</label>
<div class="controls">
<input type="text" name="username" id="inputUsername" value="" placeholder="Nickname" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">E-Mail</label>
<div class="controls">
<input type="text" name="email" id="inputEmail" value="" placeholder="E-Mail" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Passwort</label>
<div class="controls">
<input type="password" name="password" id="inputPassword" value="" placeholder="Passwort" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn" value="Account erstellen" />
</div>
</div>
</form>
You need to tell the browser not to submit the form by default with:
e.preventDefault();
So:
$('#submitForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
Otherwise, your form will submit according to the "action" attribute, before your AJAX returns.

Categories