I'm working with html/php/ajax/jquery and today I pointed out a little issue that is driving me crazy.
I've got an html form:
<form method="POST" enctype="multipart/form-data" name="myForm" id="myForm" action="">
<label class="form-label">Nome</label>
<input name="nome" type="text" class="form-control"><br>
<label class="form-label">Descrizione</label>
<textarea name="descrizione" id="text-editor" placeholder="" class="form-control" rows="10"></textarea>
<label class="form-label">Stato</label>
<select name="stato" id="source" style="width:30%">
<option value="1">Abilitato</option>
<option value="0">Disabilitato</option>
</select>
<h4>Foto profilo</h4>
<input type="hidden" name="MAX_FILE_SIZE" value="20400000" >
<input style="border:0px;" type="file" name="user_foto" id="file">
<div class="form-actions">
<div class="pull-right">
<button type="submit" class="btn btn-success btn-cons"><i class="icon-ok"></i>Inserisci</button>
<button type="button" class="btn btn-white btn-cons" onclick="window.location.href='index.php'">Indietro</button></a>
</div>
</div>
</form>
I'm working with a JQuery+Ajax script that is able to fire a php script without reloading page, and insert form's data into a table in my database:
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
var formData = new FormData(this);
$.ajax({
url:'inserisciProfessionisti.php',
data: formData,
type:'POST',
async: false,
cache: false,
contentType: false,
processData: false,
success:function(data){
window.location = 'listaProfessionisti.php'
},
error:function(data){}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
Here my php code:
<?php
session_start();
session_cache_limiter('nocache');
if(!isset($_SESSION['mail'])){
header("location:login.php");
}
include("include/connect.php");
$conn=mysql_connect($HOST, $USER, $PASSWORD);
$db_ok=mysql_select_db($DB, $conn);
$nome=$_POST['nome'];
$descrizione = $_POST['descrizione'];
....
$comando="INSERT INTO professionisti('nome','descrizione',...)VALUES('$nome','$descrizione',...)";
$ris=mysql_query($comando, $conn) or die("Errore connessione database: " . mysql_error());
...
Everything works like a charm apart textarea content. It seems that textarea content wouldn't be passed to my php script.
Issue solved.
I add this onclick="tinyMCE.triggerSave(true,true);" to submit button and everything works like a charm.
I think It should be a tinyMCE bug.
Related
I need to create a Form Post (Ajax) inside KendoUI Template, unfortunately without success.
<form id="commentSubmit">
<div class="form-group">
<textarea class="form-control k-textbox" name="body" id="bodyComment"></textarea>
<input type="hidden" name="post_id" id="post_idComment" value="#= id #" />
</div>
<div class="form-group">
<button class="k-button k-primary" type="submit">Add Comment</button>
</div>
</form>
We have a script for the Ajax post with id #commentSubmit but it's not working.
$(document).ready(function() {
$('#commentSubmit').submit(function() {
$.ajax({
url: "url.to.post",
method: "POST",
dataType: "json",
data: {
"body": $("#bodyComment").val(),
"post_id" : $("#post_idComment").val()
},
....
We found on internet something like
<form action="http://url.to.post" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="\#template" id="form0" method="post">
But it redirects to the URL and that's something we don't want to.
Any advise please?
Change this:
id to class:
<form class="commentSubmit">
Here too:
$(document).on('submit', '.commentSubmit', function() {
Prevent form's submission:
$(document).on('submit', '.commentSubmit', function(e) {
e.preventDefault();
This should make any form's submission added with template with class commentSubmit to be intercepted and handled with an ajax request.
Tip: Use jQuery's serialize to get the whole form data:
$.ajax({
data: $(this).serialize() // Being 'this' the form when inside the 'submit' event
Try this:
<form method="post" id="commentSubmit" name="commentSubmit" action="#" autocomplete="off" enctype="multipart/form-data">
<div class="form-group">
<textarea class="form-control k-textbox" name="body" id="bodyComment"></textarea>
<input type="hidden" name="post_id" id="post_idComment" value="#= id #" />
<button type="submit" class="k-button k-primary" id="btnSubmit" form="commentSubmit">Add Comment</button>
</div>
</form>
$("#commentSubmit").submit(function (e) {
e.preventDefault();
$.ajax({
url: "url.to.post",
type: "POST",
data: {
"body": $("#bodyComment").val(),
"post_id": $("#post_idComment").val()
}
});
}
I have form which is used for sending sms now am sending the data on submit to sms.php page and executing the process. Now I need to submit the data in form without moving to sms.php page. It should be executed in the form page itself by using ajax method I have done that but also it redirects to sms.php. I need it to be done and the same page and the json response obtained should be stored in the database.
How can I do this? Help me Thanks in advance.
Form used for sending sms:
<form role="form" method="POST" action="sms.php">
<div class="form-group row">
<label class="col-sm-4 form-control-label">Select Date Range<span class="text-danger">*</span>
</label>
<div class="col-sm-7">
<div class="input-daterange input-group" id="date-range">
<input type="text" class="form-control" name="start" />
<span class="input-group-addon bg-custom b-0">to</span>
<input type="text" class="form-control" name="end" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 form-control-label">Select Brand<span class="text-danger">*</span>
</label>
<div class="col-sm-7">
<select class="form-control" name="brand" id="brand" required>
<option value="">Select Brand</option>
<option value="3">test1</option>
<option value="2">test2</option>
<option value="1">test3</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-8 col-sm-offset-4">
<input type="submit" class="btn btn-primary btn-sm" value="Submit">
</div>
</div>
</form>
Ajax used to send data
$('sms').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'sms.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
sms.php
<?php
if(isset($_POST['submit'])){
$senderid =$_POST['senderid'];
// echo $senderid;
$message = rawurlencode($_POST['message']);
$mobile = isset($_POST['mobilenumber']) ? $_POST['mobilenumber'] : '';
sendSMS($mobile,$message,$senderid);
}
function sendSMS($mobile,$message,$senderid){
$user = "asdhaskbdjasdjbfjk";
$url = 'http://login.smsgatewayhub.com/api/mt/SendSMS?APIKey='.$user.'&senderid='.$senderid.'&channel=2&DCS=0&flashsms=0&number='.$mobile.'&text='.$message.'&route=16;';
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,"");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,2);
$data = curl_exec($ch);
print($data); /* result of API call*/
}
?>
Response obtained:
{"ErrorCode":"000","ErrorMessage":"Success","JobId":"112591825","MessageData":[{"Number":"0123456789","MessageId":"mU9WfV6hLEyNAQQI63BzNw"}]}
Your selector in jquery code $('sms') is wrong. And to stop changing the page, you should use click event and stop actually submitting the form like this:
$('.btn-sm').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'sms.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
You can see from the above given code snippet that, I have used click event of the submit button, and also written e.preventDefault() in first line, so it will stop the form to submit but it will just initiate ajax call. So SMS will be sent and you will be on the same page. No redirection will be there.
In your code I found that you added action in your page:
<form role="form" method="POST" action="sms.php">
remove that action and post from form as because you included inside your script tag
I have some experience in JAVA GUI programming and I want to achieve the same in a PHP form.
Situation: I want to have a php form with a submit button. When the button is pressed an ActionEvent should be called to update another part of the form.
How to implement such a feature with HTML,PHP,JAVASCRIPT ?
Load latest version of jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
HTML code:
<form>
<button type="button" class="formLoader">Click button</button>
<div id="formContentToLoad"></div>
</form>
jQuery code:
<script type="text/javascript">
$(function(){
$(".formLoader").click(function(){
$("#formContentToLoad").load("scriptToRun.php");
});
});
</script>
Whatever markup you need to update in the form, can be put into scriptToRun.php
Use jQuery
Javascript
$(document).ready(function() {
$(".myForm").submit(function() {
$.ajax({
type: "POST",
url: "myForm.php",
data: $(this).serialize(),
success: function(response) {
// todo...
alert(response);
}
})
})
});
Html
<form method="POST" class="myForm">
<input type="text" id="a_field" name="a_field" placeholder="a field" />
<input type="submit" value="Submit" />
</form>
PHP
<?php
if(isset($_POST)) {
$a_field = $_POST["a_field"];
// todo..
}
If you want to use PHP and HTML to submit a form try this:
HTML Form
<form action="" method="post">
<input type="text" placeholder="Enter Name" name="name" />
<input type="submit" name="sendFormBtn" />
</form>
PHP
<?php
if(isset($_POST["sendFormBtn"]{
$name = isset($_POST["name"]) ? $_POST["name"] : "Error Response Here";
//More Validation Here
}
I'm having a brain freeze at the moment..
I have a variable here in this bit of JavaScript code...
<script type="text/javascript">
$('#menuNameEdit').val(reservationId);
</script>
I have managed to use #menuNameEdit in form input as below but I don't know how to use it as a normal variable in PHP. For example if I want to compare it's value against another variable. Mind Block!
<input id="menuNameEdit" name="reservationId" type="text"
class="form-control" disabled>
You can't. It's just not possible. If JS starts with its work, PHP is already done.
The only way to do that - though its extremely vulnerable - is via AJAX:
$.ajax({
type: "POST",
url: "your_php_script.php",
data: {var: your_variable},
success: function() {
console.log("ajax successful!");
}
});
Without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'your_php_script.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(your_variable);
This needs to be in your_php_script.php:
$jsVariable = $_POST['var'];
This is extremely vulnerable though - always sanitize input via filter_var() or htmlspecialchars() which could be modified by the user!
<?php
if (isset($_POST['submit'])) {
$reservationId = $_POST['reservationId'];
$reservationId2= $_POST['reservationId2'];
//comparison
}
?>
<form class='addcategory' method="post" enctype="application/x-www-form-urlencoded">
<input id="menuNameEdit" name="reservationId" type="text"
class="form-control" disabled>
<input id="another" name="reservationId2" type="text"
class="form-control" >
<input name="submit" type="submit" value="submit">
</form>
If your form gets submitted you can access the below code:
PHP
if(isset($_POST['reservationId'])){
echo $_POST['reservationId'];
}
HTML
<form method="" action="" id="form-id">
<input id="menuNameEdit" name="reservationId" type="text" class="form-control" disabled>
<input name="submit" type="submit" class="form-control">
</form>
Jquery
var menuNameEdit = $('#menuNameEdit').val();
$.ajax({
type: "POST",
url: "index.php",
data: {menuNameEdit : menuNameEdit },
success: function() {
console.log("Success!");
}
});
index.php
echo $_POST['menuNameEdit'];
I have this bit of code:
<form name="myUploadForm" method="post" action="/scripts/upload.do" enctype="multipart/form-data" id="fileUpload">
<table width="100%" border="0">
<tr>
<td>
<input type="file" name="xlsFile" size="60" value="test.xls">
<input type="button" value="Upload File" name="upload_xls">
</td>
</tr>
</table>
</form>
Right now I can upload the file with Struts but it refreshes the page. How do I do this without the page refreshing?
What worked for me:
On the form tag, I have target="hidden-iframe"
the hidden i-frame on the page looks like this:
<iframe name="hidden-iframe" style="display: none;"></iframe>
The important thing to underline here is that the form is referencing the name attribute of the frame and not the id.
You can post form with jQuery and get the result back.
$('#formId' ).submit(
function( e ) {
$.ajax( {
url: '/upload',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(result){
console.log(result);
//$("#div1").html(str);
}
} );
e.preventDefault();
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formId" action="/upload" enctype="multipart/form-data" method="post">
<input type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
<div id="div1">
</div>
There are two methods:
HTML5 supports File API.
Create a hidden iframe, point the property 'target' of the form to the iframe's id.
If you can use jQuery, you can use something like jQuery File Upload.