Cannot prevent POST form from executing PHP code and image processing - javascript

UPDATED
CONTEXT:
I have a form that is editing event data: event photo, title, description, etc. When the user opens the edit form, all of the data is in the form fields. The user can choose to edit the data and update, or not to.
PROBLEM:
If the user does not change the photo and presses 'submit', the photo disappears.
DESIRED RESULT:
I want the photo to be updated if the user chooses to change the photo, and I want the existing photo to remain if the user doesn't change the photo.
** UPDATE**
I previously thought this was a PHP isset() / empty() check but it's not. It's a javascript problem, which I'm not experienced with. I believe the submit button and submit id is causing the javascript to fire regardless of the php.
CODE of HTML image input form.
<div class="row">
<div class="col-md-12">
<div id="event_picture" style="width:350px"></div>
</div>
<div class="col-md-12" style="padding-top:30px;">
<strong>Select Image:</strong>
<br/>
<img width='100' src="images/<?php echo $e['event_picture'];?>" alt="">
<input type="file" id="upload" class="form">
<br/>
<input type="hidden" name="event_picture" id="event_picture_base64">
</div>
</div>
SUBMIT BUTTON
<input type="submit" name="submit" class="upload-result" value="Update Event" class="btn btn-primary btn-lg">
JAVASCRIPT
<script type="text/javascript">
$uploadCrop = $('#event_picture').croppie({
enableExif: true,
viewport: {
width: 300,
height: 300,
type: 'square'
},
boundary: {
width: 350,
height: 350
}
});
$('#upload').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
document.getElementById("event_picture_base64").value = resp;
});
});
</script>
I think the problem is I need a conditional to prevent the javascript from firing when I press submit button. I'm searching online now, but I really don't know how to write that conditional.
Any help is appreciated.

Related

Cant detect input box when nothing is entered

I have the following form and input box. However, when there is nothing in the input box, the javascript doesn't execute. I need to detect if someone clicked "submit" without filling in the form. I have tried many things I've found on SO and none have worked. When there is an input value, everything works perfectly to execute the js. However, when there is nothing, the console.log(bidz) doesn't produce anything and it appears as if the script quits. From what I've read, I understand that the input box doesn't exist without a value in it. But then I tried to say if it doesn't exist, then something, but that also didn't work.
Perhaps this has to do with the fact that I give it a placeholder value of "enter something?"
<form action="" method="post">
<div id="<?php echo $this->item['id']; ?>">
<div class="ab">
<label for="ab_input"><?php echo $this->translate('To get the auction started, you must enter a starting bid.'); ?></label>
<span class="auction_bid_container">
<input id="ab_input" type="text" maxlength="12"
class="middle nmr event-clear-focus"
name="bidz" value="Enter something" />
<input id="updateBidButton" type="submit"
class="button grey-button num-items-button"
name="bidz"
value="<?php echo $this->translate('submit'); ?>"/>
</span>
</div>
</div>
</form>
<div class="clear mb20"></div>
and here is my js function. I have tried all kinds of things but it appears "this.value" results in an error if there is no value:
$('input[name="bid_amount"]').live('change', function () {
var bidz = this.value;
console.log(bidz);
$.ajax({
type: 'post',
url: "?module=is&controller=index&action=syy",
dataType: "text",
data: 'bid=' + bid_amount + '&id=' + id,
beforeSend: function () {
$('.ab').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
console.log(bid_amount);
$('.ab').animate({
'backgroundColor': '#A3D1A3'
}, 300);
} else {
$('.ab').animate({
'backgroundColor': '#FFBFBF'
}, 300);
}
}
});
});
You are submitting the form either way, that's why! So, what you have to do is to stop the form from being submitted. How?
You can add onsubmit=" return false; " to your form
<form action="" method="post" onsubmit=" return false; ">
</form>
submit.addEventListener("submit", form, function(){
e.preventDefault(); /* This will prevent the form from being sent until you explicitly send it. */
});
If you are sending the form through ajax there is no need to submit the actual form (meaning form.submit() )

how to upload an image using ajax

I want to upload an image without refreshing the page,But my page still refresh when i hit submit button to upload image. what is wrong with my ajax code. This works when am submitting form with plain text but not with image file.
test.php
<div class="preview_d_p" id="preview_d_p">
<div class="preview">
<div class="p_preview">
<div id="p_p_image"><div id="myimage"></div></div>
</div>
<div id="lab"> <label for="photo_upload">upload</label></div>
<form enctype="multipart/form-data">
<input type="file" id="photo_upload" name="image_upload">
<input type="submit" value="save" id="insert_img" onclick="return loadimage()">
</form>
</div></div>
<script>
function loadimage(){
var image = documentElement('photo_upload').value;
$.ajax({
type:'post',
url:'profile.php',
data:{
image:image
},
cache:false,
success: function(html){
}
});
return false;
}
</script>
my advice is changing the input to a button (type="button") - I prefer buttons to inputs as they're more easily stylable.
But you can do something like this to govern submitting data without page refresh:
HTML EXAMPLE (NOT A COPY OF YOUR HTML):
<div id="container">
<form action="" method="post" id="myForm">
<input type="text" value="hello world!" />
</form>
<!-- what's great about buttons, is that you don't have to place inside the form tags -->
<button type="button" id="submitBtn">
JS To match
$(document).ready(function()
{
$('#submitBtn').on('click', function()
{
//ajaxy stuff
//will show the success callback function though:
success: function(res)
{
$('#container').html(res);
}
})
});
if your post script returns html then this should work. Let me know if otherwise :)
I solved this problem using formdata to send my image file to server
$(document).on("submit","form",function(e){
e.preventDefault();
var file = $("#product-file-i").val();
var p = $("#product-upload-f").children("input[name=name]").val();
$.ajax({
type:"post",
url:"profile.php",
data:new FormData(this),
contentType:false,
processData:false,
cache:false,
success: function(feedback){
alert(feedback);
},
error: function(){
}
});
});

Reload a single DIV on a page using onClick

In my page there are several DIVs, which are supposed to show different news items depending on the user selection and a press of a submit button.
Am I able to refresh only a single DIV when the relevant submit button is clicked?
I tried <input type ="button"> instead of <input type="submit"> but that didn't work as expected. My code is below:
<div class="dloader"></div>
<div class="search">
<form action="" method="post">
Furniture:
<input type="text" name="val1" id="val1" value="<?=$_POST['val1']?>" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php
if( isset($_POST['submit']) ){
$postItemHeader = htmlentities($_POST['val1']);
}?>
<script>
$(window).load(function() {
$(".dloader").fadeOut("slow");
})
</script>
Take One Button For Post Event
<input type="submit" id="add" name="add" />
If You want to pass the Text Data, so a text value from the Text to fetch the particular data
<div id="result">Result should appear here</div>
Use Javascript To POst The Text Data To Back End
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#add').val,
success: function(data, status) {
$("#result").html(data)
}
});
});
});
What you need is AJAX. (read the documentation). A simple example is here.
The HTML
<div id="target_div"></div> <!-- Here is where you gonna place your new content -->
<input type='button' id='trigger' onClick="get_new_data()" value="Get new Content"> <!-- When this button is pressed get new content -->
The Javascript
function get_new_data()
{
$.ajax(
{
type: POST,
url: "you-url-here.php",
dataType:"HTML", // May be HTML or JSON as your wish
success: function(data)
{
$('div#target_div').html(data) // The server's response is now placed inside your target div
},
error: function()
{
alert("Failed to get data.");
}
}); // Ajax close
return false; // So the button click does not refresh the page
} // Function end

Submit 2 forms with 1 button, form1 after form 2 is complete

I have the following problem:
2 forms that need to be submitted with one button. I will explain how it should work.
And of course my code so far.
#frmOne contains a url field where I need to copy the data from to my #frmTwo, this works.
(it forces the visitor to use www. and not http:// etc)
When I press 1 submit button
Verify fields #frmOne (only url works now, help needed on the others)
Call #frmTwo and show result in iframe. result shows progress bar (works)
But Div, modal or any other solution besides iframe are welcome.
Close #frmOne (does not work)
Finally process (submit) #frmOne if #frmTwo is done (does not work)
Process completed code of #frmTwo in iframe =
<div style='width' id='information'>Process completed</div>
<ol class="forms">
<iframe width="100%" height="50" name="formprogress" frameborder="0" scrolling="no" allowtransparency="true"></iframe>
<div id="txtMessage"></div>
</ol>
<div id="hide-on-submit">
<form id="frmOne" method="post">
<input type="text" name="company" id="company" >
<input type="text" name="url" id="url" >
<input type="text" name="phone" id="phone" >
<input type="text" name="occupation" id="occupation" >
<textarea rows="20" cols="30" name="summary" id="summary" >
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
<form id="frmTwo" method="post" target="formprogress"></form>
<script>
jQuery(document).ready(function(){
//Cache variables
var $frmOne = $('#frmOne'),
$frmTwo = $('#frmTwo'),
$txtMessage = $('#txtMessage'),
frmTwoAction = 'http://www.mydomainname.com/form.php?url=';
//Form 1 sumbit event
$frmOne.on('submit', function(event){
event.preventDefault();
var strUrl = $frmOne.find('#url').val();
//validation
if(strUrl === ''){
$txtMessage.html('<b>Missing Information: </b> Please enter a URL.');
}
else if(strUrl.substring(0,7) === 'http://'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>http://</b> is not supported!');
}
else if(strUrl.substring(0,4) !== 'www.'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>Invalid URL</b> Please enter a valid URL!');
}
else{
//set form action and submit form
$frmTwo.attr('action', frmTwoAction + strUrl).submit();
$('#hide-on-submit').hide(0).fadeIn(1000);
$('form#frmOne').submit(function(e) {
$(this).hide(1000);
return true; // let form one submit now!
}
return false;
});
});
</script>
read here https://api.jquery.com/jQuery.ajax/. basically you need to submit the first one with $.ajax and then, when you get the server response (in the success() function ) you need to send the second form, again width ajax().
Something like:
$form1.on('submit', function(e) {
e.preventDefault(); //don't send the form yet
$.ajax(
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize()
).success(function(data) {
alert('form one sent');
$.ajax(
url: $('#form2').attr('action'),
type: $('#form2').attr('method'),
data: $('#form2').serialize()
).success(function(data) {
alert('form two sent');
})
});
});
This code isn't ready to be copy/pasted, it's just to give you a guideline of how I would solve it. It's a big question, try going with this solution and come back with smaller question if you find yourself blocked.

How to add before send function to current return ajax function?

i have a main form on my main page, the form get an email address from the user and check if the email exist.
My target is to show the results on the same page with bootstrap collapse.
I am using this code in the javascript side:
$(".emailCheckForm").bind("submit", function () {
return $.ajax({
type: "POST",
width: "auto",
height: "auto",
padding: 10,
cache: !1,
url: "_/php/checkemail.php",
data: $(this).serializeArray(),
success: function (t) {
$(".res").append(t).collapse();
},beforeSend: function(){
$( "#message" ).empty();
}
}), !1
}),
my html code:
<form action="" method="post" class="col-md-8 centered emailCheckForm">
<div class="input-group">
<input type="email" name="email" class="form-control checkFrame" placeholder="you#youremail.com">
<div class="input-group-btn">
<input type="submit" value="answer me!" class="btn btn-default checkFrame" tabindex="-1" />
</div>
</div><!-- /.input-group -->
</form>
<div class="res"></div>
Now this working but the problem is that if i want to check another email i get the same results until i will refresh the page.
So i want to implement a before send function that will remove\empty the div results.
I cant make this happen because that every time that i insert the beforsesend function the post not working, any suggestions to make proccess like that in the right way?
How about this one. On every successful callback it will clean up results from previous request and re-populate latest:
...
success: function (t) {
$(".res").empty().append(t).collapse();
}
...

Categories