I have two functions one is PHP second is JQuery. I want them to activate on same button click. But I want fisrt to activate PHP function and then JQuery. How can I do this. Here is my code. The problem is this line in JQuery function
var imagename = "<?php echo $nameoffile ?>";
When I replace that with hardcoded variable everything work fine. How can I control order of execution ?
HTML :
<form id ="submit_leave_email" enctype="multipart/form-data" method="POST" >
<div class="form1">
<div class="radio-line" id="radio-manager" style="font-size:12px">
<input type="radio" id="rad-400" name="radio-manager" value="No"/> Registered
<input type="radio" id="rad-400" name="radio-manager" value="No"/> Unregistered
</div> <br>
<h4 class="manager" style="font-size:12px">ID of car is :</h4><br><br>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" class="input_1" />
<input id="fileupload" name="uploadedfile" type="file" class="input_1" /><br/>
<input id="brand" type="text" value="Name of car :" class="input_1" name="brand" /><br></div> <br>
<div id = "image" style="width:100px; height:100px"></div></div>
<input id="submit" type="submit" name="submit" value="submit">
</form>
PHP :
<?php
if(isset($_POST['submit'])){
$target_path = "images/";
$nameoffile = basename( $_FILES['uploadedfile']['name']);
$target_path = $target_path . $nameoffile;
echo $nameoffile;
if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "There was an error uploading the file, please try again!";
}
}
?>
JQuery :
<script type="text/javascript">
$( "#submit_leave_email" ).submit(function( event ) {
var brand = $('#brand').val();
var id = localStorage.getItem("id");
if($('#rad-400').is(':checked')){
var ide = 'reg';
} else {
var ide = 'unreg';
}
var imagename = "<?php echo $nameoffile ?>";
$.ajax({
type: "POST",
url: "updateCarSql.php",
data: "ide=" + ide + "&id="+ id + "&brand="+
brand+"&imagename="+imagename,
success: function(){
$("#submit_leave_email").fadeOut();
$("#update_success1").fadeIn();
}
});
});
</script>
PHP code runs at the server, jQuery runs at the client so the strict answer to your question is ISSET is executed before the jQuery; however that doesn't really help you.
It looks like you are trying to use PHP to get the file name for your jQuery code before submitting the form. This is a bit of a catch 22 as PHP code won't be run until after you submit the form.
If you want to get the chosen file name you'll need to use javascript. Look at this question - Use jQuery to get the file input's selected filename without the path
Also look at preventDefault as I suspect you don't want to do an ajax call and submit your form.
Related
<form method="POST">
<div id="showme">Show me <?php echo $_POST['name']?></div>
Send the value<input type="radio" name="name" value="ja"/>
<input type="submit" id="submit" name="submit" value="BEREKENEN! ">
</form>
<script>
$(document).ready(function () {
$('#showme').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#showme').fadeIn(5000);
});
});
</script>
This code won't send the value of the radiobutton to the showme div.
I can't receive the $_POST['name'] when I use hide() and fadeIn() between the <script> tags.
Whenever I don't use jQuery it sends the data - when using it , it won't let me send the value.
How do I fix this problem, this is just an example of 1 radio button. I have a list of 6 radiobuttons that need to be sent to PHP section in the same file, I don't want to make another file for this.
This code will FadeIn the requested div, it shows me Show me but it won't show the value where I ask for with the line <?php echo $_POST['name']?>
PHP is parsed on the server. <?php echo $_POST['name']?> has already been evaluated and echod to the page long before any of the submission stuff happens. What you need is to use AJAX.
You can replace the submit button with just a regular button, remove the <form> element entirely even.
jQuery:
$('#submit').on('click', function(evt) {
var e = evt || window.event;
e.preventDefault();
$.post('page.php', { name: $('input[name="name"]').val() }, function ( data ) {
$('#showme').append(data).fadeIn(5000);
});
return false;
});
(if you do what I did below turning submit into button, you dont need the e.preventDefault())
PHP:
if(isset($_POST['name'])) {
echo $_POST['name'];
return;
}
HTML:
<div id="showme">Show me </div>
<label for="name">Send the value</label><input type="radio" name="name" value="ja"/>
<input type="button" id="submit" name="submit" value="BEREKENEN!">
I'm not so sure you can get a non-BOOLEAN value from a radio button with PHP though. You're probably better off using <input type="hidden" value="ja" /> or maybe type="text".
I'm following the following tutorial to place a form on my website using PHP, AJAX, and JQUERY that will send the form information to my email:
http://www.spruce.it/noise/simple-ajax-contact-form/
The problem is, when I have the jquery outside the document ready I get no message at all, and when I place it in the document ready i get the error text, but when there is information in the fields nothing happens at all. Please, can someone look and see what might be the problem with my html, jquery, php, or AJAX? I'm about to pull out all of my hair. I'm testing it in Wampserver.
The HTML file is in the root directory with the PHP file. In the root directory there is a folder called "includes" that the Javascript is in. Here is the relevant code for each:
HTML:
<form id="repairform" method="post">
<p id="p1">Name:</p>
<input id="one" type="text" name="name" />
<p id="p2">How would you prefer to be reached?: </p>
<select id="two" name="Contact methods">
<option value="Phone">Email</option>
<option value="Email">Phone</option>
</select>
<p id="p3">What kind of computer are you having trouble with?</p>
<p id="p3-2">Give as much or as little info. as you'd like.</p>
<p id="p3-3">(Laptop PC, desktop Macintosh, etc)</p>
<textarea id="four" name="pc type" rows="3" cols="30"></textarea>
<p id="p4">What problems are you having with your computer/ what needs to be fixed?</p>
<textarea id="five" name="problem" rows="5" cols="30"></textarea>
<input id="three" type="submit" value="Submit Request" />
<p id="p5">What is your Email?</p>
<input id="six" type="text" name="Email/Phone" />
<p id="p7">What is your Phone Number?</p>
<input id="eight" type="text" name="Email/Phone2" />
<p id="p6">What time of day would you prefer to be reached?</p>
<input id="seven" type="text" name="Preferred Contact Time" />
</form>
JQuery:
$(document).ready(function () {
$("#repairform").submit(function (e) {
e.preventDefault();
if (!$("#six").val()) {
$("#six").val("shanew#ufl.edu");
}
var name = $("#one").val();
var email = $("#six").val();
var text = $("#five").val();
var reachpreference = $("#two").val();
var computertype = $("#four").val();
var phonenumber = $("#eight").val();
var timeofday = $("#seven").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text
+ '&reachpreference=' + reachpreference + '&computertype=' + computertype
+ '&phonenumber=' + phonenumber + '&timeofday=' + timeofday;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (text.length > 2) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "../functions.php",
data: dataString,
success: function () {
alert("Thank you! Your message has been delivered. I will be back with you shortly");
}
});
} else {
alert("Some of the form information was not filled out correctly. Ensure all of the correct fields are filled out.");
}
return false;
});
PHP:
<?php
// Email Submit
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text'])){
//send email
mail("shanew#ufl.edu", "Contact Form: ".$_POST['name'],
$_POST['text'], $_POST['reachpreference'], $_POST['computertype']
$_POST['phonenumber'], $_POST['timeofday'], "From:" . $_POST['email']);
}
?>
Use
data: $('#repairform').serializeArray()
instead of the datastring object you're creating.
The datastring will be treated as a String, and you'll never be able to access it using $_POST['text'] and all. You may try using using $_GET instead. The datastring will be accessible that way only.
I think you miss some of closing branch });
And I think you should use name attribute for variable name that will be used in php..
<form id="theForm">
<input type="text" name="email" />
</form>
and in javascript you can use serialize so less line and easier to read.
$.ajax({
type:'POST'
url:'../functions.php'
data:$('#theForm').serialize();
})
and in php
echo $_POST['email']
Here's my JS code...
function da(){
var a=document.forms["user"]["age"].value;
if(this.age.value < 18 || this.age.value > 85) {
alert('some text...');
this.age.focus();
return false;
}else{
window.location.href='file.php?&'+a;
}
}
It simply passes the parameters to the page where I'm standing...
Here's the form just in case (I'm a beginner keep in mind)...
<form name="buscar" method="GET"> Some text <input onmouseover="Aj2('d');document.getElementById('box').style.display='block';" onmouseout="clean();" type="number" name="age" id="age" > Age <div id="help" ><!-- --> </div><br />
<input type="button" value="Send" onclick="da()">
</form>
The Aj2 function is not the problem here...
Thanks for any help y might get...
Just a thought, if you don't actually have to reload the page and just want to get information to your javascript code from PHP, you could do something like
<script>
<?
$phpvariable = "my variable";
?>
var jsvariable = <?php echo json_encode($phpvariable); ?>;
</script>
Now the javascript variable, jsvariable, will hold the PHP variable's content.
Some thing like this I am not a expert.
$('button name').on('click', function() {
var age_ = document.getElemenetById('age');
$.get('path of your file', {'age' : age_}, function(resp) {
// code to pass parameter
alert(age_);
});
});
This is the first time I am trying to upload a file and for some reason my $_FILES array is empty. I have checked again and again my HTML and it looks okay to me. When i try to debug the below code in eclipse the $_Files array is empty when i check it. I have checked the php_ini file it has:
file_uploads = On
upload_max_filesize = 2M
The form is in a fancybox modal window.
My HTML looks like this:
<form action="/CiREM/attachments/addAttachmentsModal.php?requestId=120" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="120"/>
<input type='hidden' id='listScreen' name='listScreen' value=""?>
<input type='hidden' name='MAX_FILE_SIZE' value='4000000' /><br/> <strong>Max File size Allowed: </strong>4 Mb <br/><strong>File Formats Allowed: </strong>gif,jpeg,jpg,png<br/><hr/> <div class="control-group">
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
</div>
<div class ="clear"></div>
<input id="addAttachmentsBtn" type="submit" class="btn btn-primary btn-large" value="Add Attachments"/>
</form>
My php is
<form action="<?php echo $_SERVER['PHP_SELF']."?requestId=".$requestId?>" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="<?php echo $requestId;?>"/>
<input type='hidden' id='listScreen' name='listScreen' value="<?php echo $listScreen;?>"?>
<?php
if ($CIREM['MAX_IMG_NUM']>0){
echo "<input type='hidden' name='MAX_FILE_SIZE' value='".$CIREM['MAX_IMG_SIZE']."' />";
echo "<br/> <strong>Max File size Allowed: </strong>".($CIREM['MAX_IMG_SIZE']/1000000)." Mb <br/><strong>File Formats Allowed: </strong>".$CIREM['IMG_TYPES']."<br/><hr/>";?>
<?php for ($i=1;$i<=$CIREM['MAX_IMG_NUM'];$i++){?>
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
<?php }?>
<?php }
else{
echo "<p class='alert alert-info'>Attachment uploading is not allowed</p>";
}
?>
Any help will be greatly appreciated.
Thanks,
Shakira
Without looking through that spaghetti code, first check whether your $_POST is also empty.
If it is, make sure that post_max_size is larger than upload_max_filesize. The two settings have to be congruent.
First of all sorry for the late reply but since sometimes people stumble upon old topics on stackoverflow, I decided to write the way it works for me.
So, to send files via ajax you have to use FormData.
I'll paste a link to a github project I have to submit forms via ajax so you can check the working example and paste here the snippet.
Link: https://github.com/pihh/auto-ajax-form
Code:
$( "form" ).on('submit',function( event ) {
if($(this).attr('ajax')){
event.preventDefault();
var marianaFormUrl = $(this).attr('action');
var marianaFormId = $(this).attr('id');
var marianaFormMethod = $(this).attr('type');
var marianaFormSucess = $(this).attr('success');
var marianaFormComplete = $(this).attr('complete');
var marianaFormBefore = $(this).attr('before');
var marianaFormInputs = $('#' + marianaFormId +' :input');
var marianaEncType = $(this).attr('enctype');
var marianaFormData = {};
// Set enctype
if(marianaEncType === undefined || marianaEncType == ''){
$(this).attr('enctype','multipart/form-data');
}
// Run Ajax Call
$.ajax({
url: marianaFormUrl,
type: marianaFormMethod,
dataType: 'JSON',
data: new FormData( this ),
processData: false,
contentType: false,
cache: false,
success:function(data){
// Run success
if(marianaFormSucess !== undefined && marianaFormSucess !== ''){
var fn = marianaFormSucess;
var func = fn +'( data )';
eval(func);
}
},
complete:function(data){
// Run complete
if(marianaFormComplete !== undefined && marianaFormComplete !== ''){
var fn = marianaFormComplete;
var func = fn +'( data )';
eval(func);
}
}
});
}
});
This is it, using formData it sends the files just fine.
Currently i have a form which has an image as a submit. It works fine as in the form variables get passed through and gets processed. However, the page gets refreshed every time click submit for the form since the processing page has a header back to the form page.
I need a way to send the form variables without the refreshing. I understand it can be done via ajax. However, i am facing a prob since my submit button is an image. Any help as to how i can rectify my code to submit the form without refresh would be great
<form name ="nominate" action="" id ="nominate" method="POST">
<input type="hidden" name="id" value="<?php echo $id;?>">
<input type="hidden" name="screenName" value="<?php echo $author;?>">
<input type="hidden" name="course" value="<?php echo $course;?>">
//this is the image submit button
<input type="image" style="float: left;" onMouseOver="this.src='images/nominated.png'"
onMouseOut="this.src='images/nominate.png'" value="Place Order" src="images/nominate.png" width="60" height="20">
</form>
<script>
$(function() {
$(".button").click(function() {
var id = $("#id").val();
var screenName = $("#screenName").val();
var dataString = 'id='+ id + '&screenName=' + screenName + '&course=' + course;
alert (dataString);
$.ajax({
type: "POST",
url: "nominate.php",
data: dataString,
success: function(){
alert(dataString);
}
});
});
});
</script>
The code you've done should work, if you add the class of "button" to the image.
<input type="image" class="button"....
Firstly you need to add the id attribute as in jquery $("#") is the id of the element.
<input type="hidden" name="id" id="id" value="<?php echo $id;?>">
<input type="hidden" name="screenName" id="screenName" value="<?php echo $author;?>">
<input type="hidden" name="course" id="course" value="<?php echo $course;?>">
Then as said by Andrew either add the class="button" or use $("#some_id") and then give the button input an id="some_id".
$(".button").click(function(){
var url = "nominate.php";
var id = $("#id").val();
var screenName = $("#screenName").val();
var course = $("#course").val();
$.post(url,{id:id, screenName:screenName , course:course }, function(data){
alert(data);
});
});
This will alert whatever you send back from "nominate.php". Make sure you remove the header() from the script and send back a success or error message possibly.
Add the class 'button' to your image.
Also, you don't seem to have course defined anywhere. You might want to fix that, too.