I'm trying to validate a simple form, but somehow it's not happening. I need to validate the form at the client side ( server side - I'm able to do, but that's not efficient ) and then pass it onto a php file for necessary action.
The code that I'm trying thus far is:
abc.js
$("#makeproj-nav").click(function()
{
s = "<div class='create_project_card'><div class='new_project_title'><span>New Project</span></div>";
// project form starts
s += "<form id = 'create_new_form' name = 'new_form' method='post' action='insert_new_project.php'><div class='project_form'><span>";
s += "<div class='Form_contents'> <div> Project Name: <input type='text' size='100' name='project_name'></div>";
s += "<div class='Form_contents'> <input type='submit'> </div>";
s += "<span></div>";
$("#card-wrapper").html(s);
$('#create_new_form').on('submit', function(e) {
e.preventDefault();
var x = document.forms["new_form"]["project_name"].value;
if (x==null || x="")
{alert("Not Valid"); return false;}
else
{
$.ajax({
url : 'insert_new_project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
$("#card-wrapper").html(response.reply);
}
});
}
});
});
Am I missing anything ?
Related
When I add if(isset($_POST['uplprofimg'])), I get the error:
parsererror SyntaxError: Unexpected end of JSON input
If I exclude the php if isset post function, the code works perfectly.
So, PHP:
if(isset($_POST['uplprofimg'])){ //← This if broke my code >:(
//Works if I remove the ↑
if($_FILES['imagefile']['size'] > 5242880){
$ress = "<div class='error'>Max file size is 5MB</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}else{
$imgtype = pathinfo($_FILES['imagefile']['name'],PATHINFO_EXTENSION);
if(!in_array($imgtype,array('jpg','jpeg','png','gif'))){
$ress = "<div class='error'>Only <b>jpg</b>, <b>jpeg</b>, <b>png</b> and <b>gif</b> files are allowed (".$imgtype.")</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}else{
$newimgname = "/profile_picture/".random_num($length = 8).time().random_num($length = 8).".".$imgtype;
$newimgnameserv = $_SERVER['DOCUMENT_ROOT'].$newimgname;
if(move_uploaded_file($_FILES['imagefile']['tmp_name'],$newimgnameserv)){
$upuser = $mysqli->prepare('UPDATE accinfo SET profilepic = ? WHERE username = ?');
$upuser->bind_param('ss',$newimgname,$username);
$check = $upuser->execute();
if($check == true){
echo json_encode(array('response' => true));
}else{
$ress = "<div class='error'>SQL Error</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}
}else{
$ress = "<div class='error'>Couldn't move the file. Please try again later.(".$newimgname.")</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}
}
}
}
and JS:
$("#uploadimgform").on("submit",function(event){
event.preventDefault();
var formData = new FormData(this);
$("#uploadlistener").html("<img src='/images/load.gif' width='50px' />");
$.ajax({
type: 'POST',
url: "/system/requests.php",
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function(data){
if(data.response === true){
$("#bodyfader").fadeOut("slow");
$("#expandedupl").fadeOut("slow");
$("#uploadlistener").html("");
}else{
$("#uploadlistener").html(data.ress);
$('#profilepic').css('background', 'url(/images/defaultprof.png)');
$("#profilepic").css("background-size","cover");
$("#profilepic").css("background-position","center");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
If I remove the if(isset($_POST['uplprofimg'])){...}, the code works. But if I add it there, I get the json error. What is going on?
HTML Form:
<form method='POST' enctype="multipart/form-data" id='uploadimgform' style='display: none;'>
<input type='file' id='upload' name='imagefile' accept="image/x-png,image/gif,image/jpeg" />
<input type='submit' id='uploadconf' name='uplprofimg' />
</form>
This is how the form is submitted:
$("#upload").change(function(){
if(this.files[0].size > 5242880){
$("#uploadlistener").html("<div class='error'>Maximum file size is 5MB.</div>");
$("#upload").val("");
}else{
$("#uploadimgform").submit();
readURL(this);
}
});
I have no idea why, but I did this:
formData.append('uplprofimg',1);
and the code works. Someone can explain this?
I think the issue here is that you are using FormData to send the submit button value to the server.
The submit element is not added to the entries.
I have not found clear details in the submit specification or in the construction of the formData.
Indeed, when running this snippet we can see that the submit value is not appended to the FormData.
var formData = new FormData(document.querySelector('#myForm'));
for (var p of formData.entries()) {
console.log(p[0] + " " + p[1]);
}
<form id="myForm">
<input type="text" name="sometext" value="This is submitted" />
<input type="submit" name="Submit" value="someSubmitValue" />
</form>
I would suggest you to use a hidden input if you need to send some additional data that is not part of the displayed input elements.
You need to set the upload_max_filesize option in the php.ini file.
The default max size is 2M. You need to set a higher value:
upload_max_filesize = 32M
I have a form with two select html tags and an input submit. To populate the value of option tags and to display the equivalent values of selected option tag, I use PHP, please see snippet below.
Now, I want to use AJAX using JS to avoid the reloading of the browser when the user clicked the button. But I don't know how. Please help me
Here's the link
Snippet:
if(isset($_POST['mall_list'])){
$mall_list= $_POST['mall_list'];
$malls= $wpdb->get_results($wpdb->prepare("SELECT stores FROM tablename WHERE malls = '" . $mall_list. "' GROUP BY stores ORDER BY stores", OBJECT));
echo '<div class="\record\">';
foreach ($malls as $record){
echo '<div>' . $record->stores . '</div>';
}
echo '</div>';
} elseif(isset($_POST['store_list'])){
$store_list= $_POST['store_list'];
$stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= '" . $store_list. "' GROUP BY malls ORDER BY malls", OBJECT));
echo '<div class="\record\">';
foreach ($stores as $record){
echo '<div>' . $record->malls. '</div>';
}
echo '</div>';
}
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
</form>
JAVASCRIPT
//callback handler for form submit
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
if you want to post data through ajax jquery. this code work for you.
$( "form" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "your post url",
data: $('#yourformname').serialize(),
success: function (data)
{
}
});
});
javascript
$("#form").submit(function(e){
var data = $(this).serialize();
var url = $(this).attr("action");
$.post({
url,
data,
function(res)
{
if(res.code == 0)
{
//success
//code somthing when the server response
alert(res.message);
}
}
});
})
server
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
#is ajax request
# code your business logic
#response data
$response = [
'code' => 0,
'message' => 'success',
'data' => []
];
echo json_encode($response);exit;
} else {
#is normal request
}
Current Scenario :
Right now I have a form in which you can edit and save each records of input fields. i.e. firstName, lastName, email etc..
I do not get any errors and everything is working fine.
Requirement :
Now what I want to save & edit firstName and lastName input fields together instead is to edit and save firstName and lastName input field separately.
Right now they are all different input id's.
Question :
How can I achieve this by calling the same class for firstName and lastName if I want to edit them at the same time with a button ?
Is this a way to do it ? Thanks...
Code :
$("#inputFirstName,#inputLastName,#inputEmailAddress,#inputPassword,#inputZipCode").on('keypress',function(e){
if(e.which == 13) {
var field = $(this).attr("id");
var data = {};
data['ajax']=true;
data[$('#'+field).attr('name')]=$('#'+field).val();
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][firstName]') {
$('#userfirstname').text($('#'+field).val());
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][lastName]') {
$('#userlastname').text($('#'+field).val());
}
});
$('#'+field+'-edit').show();
$('#'+field+'-save').hide()
$('#'+field).attr('disabled',true);
}
});
first of all. save on every keypress is bad and will exhaust your server.
I recommennd you use onChange or make a submit button
submit button is a better solution.
lets assume that we have this html:
<form id="updateForm">
<input type="text" id="firstN" name="firstName" data-val="Ris" value="Ris">
.
.
.
<input type="button" value="submit" id="goBtn">
</form>
first set a data-val equal to the value
then in your javascript
$("#goBtn").click(function(){
var data = {};
data["ajax"] = true;
$("#updateForm input").each(function(){
var $this = $(this);
var type = $this.attr('type');
if(type != "button" && $this.val() != $this.attr("data-val"))
data[$this.attr("name")] = $this.val();
});
if(data.length > 0){
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
} else {
$.each(data, function(index, value){
$('updateForm input[name="'+index+'"]').attr("data-val", value);
});
}
// then do things
});
}
});
first it checks every input for changes (data-val is holding the original value) and it adds it to data if there is any changes at all it calls the ajax and if it was successful it updates the data-vals of each changed value else it leave it for another submission
I am having issues figuring out how to submit a form via ajax that has items with the same name(this form is dynamically created and has to use the same names for some fields).
This is the JS code that I have
<script>
var toggle123 = function() {
var chair = document.getElementsByName('chair[]');
var item1 = document.getElementsByName('item[]');
var price = document.getElementsByName('price[]');
var table = document.getElementById('table');
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'table='+table+'';
for(i=0;i<item1.length;i++)
{
dataString += + '& item1[]' + '=' + item1[i];
}
for(i=0;i<chair.length;i++)
{
dataString += + '& chair[]' + '=' + chair[i];
}
for(i=0;i<price.length;i++)
{
dataString += + '& price[]' + '=' + price[i];
}
if (chair == '' || item1 == '') {
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
var mydiv = document.getElementById('table1');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
I want it to submit to submit.php and also to hide the div that is open (table1).
I can get it to go to submit.php but I am not sure if the data is actually getting sent there or if it is just blank. It tells me there was an invalid argument for the foreach loop in submit.php.
Here is submit.php
<?php
include('dbconfig.php');
// Fetching Values From the post method
$table = $_POST['table_id'];
foreach($_POST["item1"] AS $key => $val) {
$chair = $val;
$price = $_POST['price'][$key];
$chair = $_POST['chair'][$key];
$query = mysqli_query($dbconfig,"insert into orders(table_id, price, item, chair) values ('$table', '$price', '$item', '$chair')"); //Insert Query
echo "Form Submitted succesfully";
}
?>
This is the javascript for the dynamic form....each time a button is clicked, this adds onto the form:
listholder.innerHTML += "Chair "+row.chair+"-<input type='hidden' id='chair' name='chair[]' value='"+row.chair+"' /><input type='hidden' id='table' name='table' value='"+row.table_id+"' /><input type='hidden' id='item' name='item[]' value='"+row.item1+"' /><input type='hidden' id='price' name='price[]' value='"+row.item1+"' />" + row.item1 + " - " + row.chair + " (<a href='javascript:void(0);' onclick='deleteCar(" + row.id + ");'>Delete Car</a>)<br>";
I think my main issue is probably forming the datastring that gets passed to submit.php. If anyone could help me figure this out, that would be great!
(P.S. toggle123 is activated via a button click (that works fine)
So I have a form as such:
<form action="URL" name=myform method=post onsubmit="return validateFormOnSubmit(this)" autocomplete=off>
When the form is submitted, it checks for validation.
Earlier though, I have code like this:
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function() {
var fname = $("input#first_name").val();
var lname = $("input#last_name").val();
var email = $("input#email").val();
var leadsource = $("input#leadsource").val();
var country = $("input#country").val();
var phone = $("input#phone").val();
var oid = $("input#oid").val();
var retURL = $("input#retURL").val();
var crazy
= $("input#00N40000001mCkP").val();
var dataString = '&email=' + email + '&phone=' + phone + '&oid=' + oid + '&retURL=' + retURL + '&leadsource=' + leadsource + '&country=' + country; //alert (dataString);return false; $.ajax({
type: "POST",
url: "MYURL.php?first_name="
+ fname + "&last_name=" + lname,
data: dataString,
success: function(response) { $(myform).submit(); }
});
return false; });
}); </script>
Essentially whats happening is, the form data is initially sent to a different url through an AJAX submit prior to completing the real form. On success of the ajax push - the form is submitted, and then the form is validated.
I need the form validation to have right when #submitbutton is clicked though - prior to the ajax request. Any ideas?
That code should work just fine. If you want to add it to a onclick= property on the element (I wouldn't, but if you insist), you can use this syntax to reference the form:
<input type="submit" onclick="return validateFormOnSubmit(this.parentNode)" />
And you'd have to do an e.preventDefault() and return false (maybe just one?) from the validateFormOnSubmit() function.
Take a look at preventDefault . Also, you can call validateFormOnSubmit in the anon function above and return false if it validation doesn't pass.
you should put some " " around your form tags attributes, and give it an id!
just call your validate function as the first line in your button click handler :)
$("#submitbutton").click(function(e) {
if( validateFormOnSubmit($('#myform'))){
//do all the posting stuff
}
else{
e.preventDefault();
return false;
}