I am having some trouble with my file upload script. The HTML is as follows:
<form method="post" name="imgsubmit" id="contact_form" action="PHP/imgupload.php" enctype="multipart/form-data">
<label id="namelabel" for="username">Your name:</label><input id="username" type="text" name="username" rel="req">
<label id="labelemail" for="imgemail">E-mail:</label><input id="imgemail" type="email" name="imgemail" rel="req">
<label id="filelabel" for="file">Your photo:</label><input id="file" type="file" name="file">
<input id="imgsubmit" type="submit" name="submit" value="SUBMIT"></form>
I have a jquery validation script as which checks the username and email fields to see if they are valid, and returns a white border around them if they are not entered:
$(function () {
$('#contact_form').submit(function (e) {
e.preventDefault();
var form = $('#contact_form');
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
var req_fields = $('input[rel=req]');
var field, pcount = 0;
req_fields.each(function () {
field = $(this).val();
if (field == '' || field == 'Required') {
$(this).css('border', '1px solid white').val('');
pcount += 1;
} else {}
});
if (pcount == 0) {
submit_form = true;
}
if (submit_form) {
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function (msg) {
$(form).fadeOut;
form.html(msg).fadeIn();
}
});
}
});
});
The problem is that the username gets submitted to the php script, the email gets submitted to the php script, but the image doesn't get uploaded. I'm aware that AJAX now supports image uploading and that the form.serialize() is likely the root cause of the problem, but have not been able to edit this code correctly to support the image submission.
How can I adjust this code to include the image to be submitted to the php?
`if (window.FormData)`
check this and file must be `
file = $('#elemet').files.
and ajax option should be data: FormData,
where formdata = new FormData();
I like to use the jQuery Form Plugin for this kind of stuff, you just need to bind your form submittal when the DOM is ready for it to work. The example bellow is providing a success callback, but there are other events you could use, like error, beforeSubmit, and so forth:
$('#contact_form').ajaxForm(function() {
alert("Thank you for your data!");
});
It supports both regular input values and also file uploads (in older browsers it will fake an ajax file upload using iframes), and if your browser can handle it you can even display a progress bar.
Related
I am using jquery to get the state of the toggle, I want to send that variable to my controller using twig, this is what I had done
<form method="post" enctype="multipart/form-data">
Sync: <br><div class="toggle-switch toggle-switch--green">
<input type="checkbox" class="toggle-switch__checkbox" id="togBtn" value='{{switchstatus}}' name = "sync">
<i class="toggle-switch__helper"></i></div><br>
<input type="submit" value="Update">
In Jquery
var switchStatus = false;
$("#togBtn").on('change', function() {
if ($(this).is(':checked')) {
switchStatus = $(this).is(':checked');
}
else {
switchStatus = $(this).is(':checked');
}
console.log(switchStatus);
$.ajax({
type: "POST",
url: 'name.html.twig',
data: switchStatus
});
});
I am getting value as empty
How do I pass my value of switchStatus in jquery to value option in twig HTML?
You need to send information to the PHP script via jQuery AJAX, the PHP script to sanitize user input/ do user check ups and then save the information into the database.
I have been searching through examples for days trying to troubleshoot my simple email signup form. I am trying to just submit an email to a database without leaving or reloading the current page. I am able to insert new data to my database, but not through my Ajax function. I am starting to think that my Ajax function is not being called, because even with the event.preventDefault(); function, my page is redirected to the .php file. I have listed my script below which currently resides in the <head></head> section of my HTML.
<script type="text/javascript">
$(document).ready(Function() {
$("#submitbtn").click(function(event) {
event.preventDefault();
var form = $(this),
emailcode = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
/* responseMsg = $('#signup-response') */
if ( formData.length===0 ) {
function(msg){
alert('Invalid Email');
}
return false;
} else {
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: emailcode,
success:function(data){
alert('Email Saved');
}
return false;
});
};
});
});
HTML
<form class="col-lg-5 form-group pull-right well" id="emailform" action="collector.php" method="POST" style="padding-top:6px;">
<label for="email-input">Sign up to receive updates</label>
<input type="email" class="form-control" id="emailcode" placeholder="Email" name="emaildata" autofocus></input>
<button type="submit" id="submitbtn" class="btn btn-success" style="width:60%">Sign Up</button>
</form>
PHP
$emailcode = $_POST['emailcode'];
//Fetching from your database table.
$query = "INSERT INTO EmailCollector (EmailID, EmailCode, Active)
VALUES (NULL,'$emailcode', 0)";
$result = mysql_query($query);
mysql_close();
?>
A quick thing i noticed.
form = $(this) //it is holding submit button, not the form
emailcode = form.serialize(),
formUrl = form.attr('action'), //there is no attribute `action` to select because form is holding submit button
formMethod = form.attr('method'); //similarly, there is no attribute method
change your form selector to:
form = $('#emailForm')
I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information
I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');
I'm trying to make an AJAX form that will update a twitter status when updated. I have the form working currently with php, but am not sure how to add AJAX functionality.
Here's the form:
<form id = "yourwhisper" method = "post" >
<label for="whisper">Enter your status update</label>
<textarea id="whisper" name="whisper" rows="2" cols="50" required></textarea>
<label class="error" for="whisper" id="whisper_error">Must be no more than 140 characters.</label>
<input id="lat" name="lat" style = "display:none"></input>
<input id="lon" name="lon" style = "display:none"></input>
<button type="submit" id = "submit">Pass it on</button>
</form>
This is the php which I had as the form action (it calls a php function from a twitter api library). I've now moved it to form-manager.php:
$t->update($_POST["whisper"], false, $_POST["lat"], $_POST["lon"]);
Finally, this is the jQuery code that adds the AJAX functionality. It takes the text for the update, along with the geolocation data, and passes it to the form-manager.php file in the form of the 'dataString'.
<script type="text/javascript" charset="utf-8">
$(function() {
$('.error').hide();
$(".submit").click(function() {
// validate and process form here
$('.error').hide();
var whisper = $("textarea#whisper").val();
var lat= $("input#lat").val();
var lon = $("input#lon").val();
if (whisper == "") {
$("label#whisper_error").show();
$("textarea#whisper").focus();
return false;
}
var dataString = 'whisper='+ whisper + '&lat=' + lat + '&lon=' + lon;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "form-manager.php",
data: dataString,
success: function() {
// alert ("form sent");
});
}
});
return false;
});
});
</script>
My problem is, how do I then get form-manager.php to take that info and put it into the 3 variables it needs to update twitter?
the dataString should be available to PHP as $_POST['dataString']. It is only a single var that contains a string. You should explode it.
Or if you want you can set the data property of the ajax method like { whisper: "Foo", lat: "fooLat" } so they will show up like $_POST['whisper'] and $_POST['lat']