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
Related
I am working on a form which need to insert some data with an image without reloading the page. In my side everything is working fine when there is no image filed in the form, but if there is an <input type="file"> in my form, then my code is not passing the file/image information. Can you guys please teach me what to add in my code to upload or pass image please?
My Code
HTML Form
<form action="action.php" method="POST" enctype="multipart/form-data" id="myform">
<input type="hidden" value="access" name="label">
<input type="text" name="one">
<input type="text" name="two">
<input type="file" name="image">
<button type="submit" id="mybtn">Add Data</button>
</form>
<div id="myresult"></div>
My JavaScript
$('#mybtn').click( function(){
$.post(
$('#myform').attr('action'),
$('#myform:input').serializeArray(),
function(result) {
// Some Stuff...
}
);
});
My PHP
include 'database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$label = ["access"];
if (in_array($_POST['label'], $label)) {
switch ($_POST['label']) {
case 'access':
$one = $_POST['one'];
$two = $_POST['two'];
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_temp = $_FILES['image']['tmp_name'];
$error = [];
$valid = [];
$flag1 = $flag2 = $flag3 = false;
if (!empty($one)) {
// Some validation
$flag1 = true;
} else {
$flag1 = false;
}
if (!empty($two)) {
// Some validation
$flag2 = true;
} else {
$flag2 = false;
}
if (!empty($file_name)) {
// Some validation
$flag3 = true;
} else {
$flag3 = false;
}
if ($flag1 && $flag2 && $flag3) {
// move_uploaded_file() + Insert All data
if ($result) {
$valid[] = "Data added successfully!";
} else {
$error[] = "Please try again later!";
}
} else {
$error[] = "Something went wrong!";
}
// ALERT MESSAGE [error] and [valid]
if (!empty($error)) {
foreach ($error as $value) {
echo json_encode($value);
}
}
if (!empty($valid)) {
foreach ($valid as $value) {
echo json_encode($value);
}
}
break;
default:
# code...
break;
}
}
}
This code works perfectly without reloading page while there are no input type file. I want to know what code I have to add in my JavaScript section to execute the code successfully with an input type file.
$('#dataBtnIMG').click( function(){
var form = $('#dataFormIMG');
var formData = new FormData($('#dataFormIMG')[0]);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: formData,
cache: false,
contentType: false,
processData: false,
success:function(result) {
// Some Stuff
}
});
});
I have an HTML form that I'm trying to read data from and write into a database. A sample of the HTML for the form is shown below:
<div id="form">
<div class="container-tabby1">
<div class="wrap-tabby1">
<form class="tabby1-form validate-form">
<span class="tabby1-form-title">
New Form
</span>
<div class="wrap-inputtabby validate-input bg1" data-validate="Internal Error">
<span class="label-inputtabby">Change Request Number</span>
<input id="ChangeRequestNo" class="inputtabby" type="text" name="ChangeRequestNo" onload="onLoad" readonly>
</div>
<div class="container-contact100-form-btn">
<input id="submitRequest" type="button" class="contacttabby-form-btn" value="Submit Request" onclick="SaveChangeRequest()"/>
</div>
The ajax used to write this to the database is as follows:
function SaveChangeRequest() {
var o = form.getData();
var errorMsg = "";
msg = mini.loading("Submit...");
var jsonform = mini.encode(o);
debugger;
$.ajax({
url: urlCR,
type: "post",
data: { CR: jsonCR },
cache: false,
success: function (text) {
debugger;
if (text != null && text != '') {
mini.hideMessageBox(msg);
onOk();
}
else {
jAlert("Submit failed", "Error Message");
}
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
})
Every time I attempt to submit to the database I get the "Submit failed" error message. I have another form as shown below that works perfectly fine:
<div id="form" style="margin-left:5px;margin-right:5px;">
<table width="100%;" align="center">
<tr>
<td width="100px;"><label>Applicant:</label></td>
<td width="300px;"><input id="ApplicantEmail" name="ApplicantEmail" class="mini-textbox" allowinput="false" style="width: 290px;" /></td>
<td align="center">
<input type="button" class="searchsubmit" value="Submit" onclick="SaveForm()" style="width:120px;" />
<script type="text/javascript">
mini.parse();
SecurityLog_PageLoad();
var urlPersonInfo = "data/AjaxSecurityService.aspx?method=Sec_CurUserLoginInfo";
var urlFormGetItem = "Data/ajaxservice.aspx?method=CSC_Form_GetWholeFormo&FormID=";
var urlFormUpdateWithNotice = "Data/ajaxService.aspx?method=CSC_Form_UpdateChanges";
var form = new mini.Form("#form");
var searchGrid = mini.get("dgSearchResult");
var applyGrid = mini.get("dgApplyResult")
function SaveForm() {
var o = form.getData();
form.validate();
if (form.isValid() == false) return;
var errMsg = '';
if (o.RequestComments == null || o.RequestComments == '')
errMsg=".Justification is empty.\n";
if (applyGrid.data.length < 1)
errMsg+= ".At least apply one report before you submit.\n";
if (errMsg != '')
{
jAlert(errMsg, "Validate Error");
return;
}
$.ajax({
url: urlFormUpdateWithNotice,
type: "post",
data: { dataForm: jsonClaim, dataList: jsonList },
cache: false,
success: function (text) {
var impactID = mini.decode(text);
if (impactID != null && impactID != "") {
SecurityLog_Submit('Submit',impactID);
CloseWindow("ok");
};
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
});
</script>
Why does the latter form work while the first form does not?
This is not a answer as such at this stage, but a few points of note that might help reach an answer:
the code that displays the "Submit failed" message is actually in the success response section. It shows the message if there is a non-null, non-empty string returned by the AJAX call. It would help if the string was output to help debug if it's an actual failure to save the data, or not
following on from the above, check if the data submitted has been saved or not - that will help establish what is actually happening
In the second form, we can see the URL (urlFormUpdateWithNotice) but in the first we can't, so it's hard to tell if that is a problem (e.g. there could be a typo in the URL)
Ideally you need to include as much detail as possible, including any critical data, so that diagnosing the problem is easier and quicker.
In any case the best place to start is to see what text is in success: function (text) {... and take it from there.
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
}
I've created a simple poll that would be sent to the server side using AJAX JSON jQuery and would be echoed back. It's not properly working. Please tell me where i've gone wrong. I'm new to jQuery and JSON.
JavaScript
<script>
function sendVote(){
var voteS = $("#vote").val();
$(document).ready(function(){
$("#vote").click(function(){
$.ajax({
type : "POST",
url : "poll_vote.php",
data : "vote="+voteS,
dataType: "JSON",
success : function(data){
concole.log("Data Submitted " + data);
$("#result").html(data);
},
complete :function(data){},
error : function(error, data){
console.log("Error. not Working" + error+" "+ data);
alert("Error. not Working"+ error);
$("#result").html(error+ data);
}
});
});
});
}
</script>
PHP
<?php
$vote = $_POST['vote'];
if (isset($vote)) {
$list = array('vote' => $vote);
$encode = json_encode($list);
echo $encode;
}
?>
HTML
<body>
<h3> What is your Gender? </h3>
<form>
Male :
<input type = "radio" name = "vote" value= "0" id="vote" onclick = "return sendVote()" />
<br />
Female :
<input type = "radio" name = "vote" value = "1" id="vote" onclick = "return sendVote()">
</form>
<p><div id= "result"></div></p>
</body>
You have picked ambiguous selector, having used invalid markup with non-unique id.
Change this:
var voteS = $("#vote").val();
to:
var voteS = $("input[name='vote']:checked").val();
And, as you specified by dataType: "JSON", you are expecting an json object in success section, so you only need to access this object's vote attribute here:
$("#result").html(data.vote);
Also in success you have typo: concole.log instead of console.log
And in your PHP file, you should check if $_POST['vote'] is set:
if (isset($_POST['vote'])) {
$vote = $_POST['vote'];
$list = array('vote' => $vote);
$encode = json_encode($list);
echo $encode;
}
And remove $(document).ready(function(){ from this function, it will not bind this event to that element before you actually call this function it is in.
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 ?