I have a page with a form that contains many fields and an image:
<form method="POST" action="http://project.dev/model/useradd" accept-charset="UTF-8" autocomplete="off" id="AddModel" enctype="multipart/form-data">
<input name="_token" type="hidden" value="yeq4iLVIyXiYyMbORaY5fA6zxIYDFWNJTqNVYiP9">
<div class="form-group">
<label for="material">Material</label>
<input type="text" class="form-control" name="material" maxlength="30" style="width:30ch">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="text" class="form-control" name="color" maxlength="10" style="width:20ch">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" name="description" maxlength="500">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input id="modelpic" name="image" type="file">
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show the preview of the image through javascript */
<div class="form-group">
<input id="AddBtn" class="btn btn-default" type="submit" value="Submit">
</form>
here is the javascript that shows the image preview in the form after selection:
$(document).ready(function() {
$('#modelpic').on("change", function () {
//shows image preview in DOM
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(this.files[0]); // read the local file
reader.onloadend = function(){ // show image in div
$('#imagePreview').show().html('<img id="theImage" src="' +this.result+ '" class="img-fluid" alt="Your Image" />');
}
}
})
});
What I need to do is show a preview of the post as it will appear before confirming submission.
How can I do it with jquery? My guess is I also have to modify the action part of the form code action="http://project.dev/model/useradd" in the html to something like self or something? Is it correct?
How do I get the submitted form data along the picture after hitting submit in jquery and use that to output the html to a preview div?
--- I also thinked to send the data to the server, save the image temporarily in public then load it in the preview. The problem is that if I use ajax to intercept the submission the image is not submitted. I think it's a problem of specyfing the data. My JS script code is like this:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
I think this is wrong probably in the datatype or something.
Related
I made a comment column by putting process.php in the page header, but when I want to load a #comment-list, 1 page entered into the div.
I've tried changing ajax.url and it works, but it will affect the entire system that was created.
I want to load this part when ajax is successful
HTML
<div id="comment-list" class="widget-body">
<?php news_comment($server_conn,$id_news); ?>
</div>
FORM
<form action="<?php echo FullURL() ?>" method="post" id="newcomment">
<div class="form-group">
<label for="comment">* Comment:</label>
<textarea class="form-control" rows="3" name="text_comment" placeholder="Your Comment" required></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit-comment" name="submit-comment" value="<?php echo $row['id_news']; ?>">Post Comment</button>
</form>
AJAX
$("#submit-comment").click(function(event){
event.preventDefault();
var submit = $(this).attr('value');
var post_url = $("#newcomment").attr("action");
var request_method = $("#newcomment").attr("method");
var form_data = $("#newcomment").serialize();
$.ajax({
url : post_url,
type: request_method,
data : form_data + '&submit-comment=' + submit,
success: function(){
$("#newcomment")[0].reset();
$("#comment-list").load(post_url + "#comment-list");
}
})
});
When Ajax responds successfully, I want #comment-list loads automatically, without entering a 1-page display
I want to save an image and two text field using JQuery,Ajax. here, i'm using bootstrap modal. But when I submit the modal form it's show MethodNotAllowedHttpException Exception.
My Ajax Method.
$(document).ready(function(){
$('#advisoradd').on('submit',function(){
var name=$('#adname').val();
var title=$('#adtitle').val();
var img=$('#adfile').val();
$.ajax({
url:"{{route('add.advisor')}}",
type:'post',
data:{
'_token':"{{csrf_token()}}",
'name':name,
'title':title,
'img':img,
},
success:function(data)
{
console.log(data);
}
});
});
});
My view Modal code.
<form method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<div class="img_upload_team">
<button class="btn">+</button>
<input type="file" name="myfile" id="adfile">
</div>
<h2>Add A Profile Photo</h2>
<p>Click “+” Sign to Add</p>
</div>
<div class="form-group">
<input type="text" name="adname" class="form-control" id="adname" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="adtitle" class="form-control" id="adtitle" placeholder="Title">
</div>
<button type="submit" class="btn btn_modal_submit" id="advisoradd">Add</button>
</form>
My controller and Route for this Request.
public function addadvisor(Request $request)
{
$advisor=new Advisor();
$advisor->name=$request->name;
$advisor->title=$request->title;
$file = $request->file('img') ;
$fileName = $file->getClientOriginalName();
$destinationpath=public_path().'/images/';
$file->move($destinationpath,$fileName);
$advisor->image=$fileName;
$advisor->save();
return response()->json($advisor);
}
Route::post('/advisor','ImageController#addadvisor')->name('add.advisor');
You've mixed up button and form events. Buttons don't have a submit event, forms do. Since you're adding the event on the button, change it to click.
We should also add a preventDefault() to stop the button from submitting the form.
(We could also add the type="button" attribute on the button element to stop it from submitting the form).
This should work:
$(document).ready(function() {
// Add a 'click' event instead of an invalid 'submit' event.
$('#advisoradd').on('click', function(e) {
// Prevent the button from submitting the form
e.preventDefault();
// The rest of your code
});
});
This is my registration form located in login.html:
<form action="Registar.php" method="post">
<input type="text" name="user" placeholder="Username (Sem espaços)" maxlength="25">
<input type="text" placeholder="Email" name="email" maxlength="31"/>
<input type="text" name="nome" placeholder="Nome" maxlength="31"/>
<input type="text" name="morada" placeholder="Morada" maxlength="120"/>
<input type="hidden" name="action" value="login">
<input type="number" name="telefone" placeholder="Telefone" maxlength="15"/>
<button type="submit" class="btn btn-default" name="submit">Signup</button>
</form>
It goes to "Registar.php" and runs the verification's i want like if the fields are empty or if the username already exists and show's that verification's in a jquery dialog.
Heres my Jquery script:
function alerta(msg,link){
var dialog = $('<div>'+msg+'</div>');
$(function() {
$( dialog ).dialog({
modal: true,
buttons: {
Ok: function() {
window.location = link;
}
}
});
})
};
The thing is it shows the dialog on the blank page of "Registar.php" and since i scripted some nice styles and overlays for my jquery dialog i want to show the jquery dialog verification messages in login.html and have that page in the background/overlay of the dialog.
Is there any way to do that but still running the action form to an external php script?
Thanks in advance!
One way to achieve this would be to use AJAX instead of sending the form via POST. Here's an example:
HTML
<form id="myForm" action="" method="post">
//your form content
</form>
JQuery
$('#myForm').on('submit', function(e) {
e.preventDefault(); //stop form submission
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "Registar.php",
data: formData,
success: function(result) {
//result is the value returned from Registrar.php
console.log(result);
//show the modal
}
});
});
JSFiddle
File upload through ajax serialize():
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
</div>
</form>
AJAX CODE using serialize():
$('#save11').click(function(){
$.ajax({
type : "POST",
url : "page/add-journal.php",
data :$('#addform').serialize(),
success : function(data)
{
alert(data);
window.location.href="home-page.php";
}
});
});
Here PHP code:
<?php
include '../dbConnection.php';
$tmp=$_FILES['file']['tmp_name'];
$serverpath="upload/".$_FILES['file']['name'];
$file=$_FILES['file']['name'];
move_uploaded_file($tmp,$serverpath);
$sql="insert into journal set file='".$file."'";
$query=mysql_query($sql);
?>
Only give me solution using serialize() only. If not so give me best solution.
I have made some changes in your code.. you can use below code for uploading images using ajax
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
<input type="submit" name="save" value="save" />
</div>
</form>
<script>
$('#addform').submit(function(e) {
e.preventDefault();
var data = new FormData(this); // <-- 'this' is your form element
$.ajax({
url: 'page/add-journal.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
alert(data);
window.location.href = "home-page.php";
}
});
});
</script>
Note:
you haven't provided that how you submit your form, so I have put a submit button
You are using mysql functions, but they are officially deprecated now from php, you should use mysqli or PDO.
Form id in HTML is addform and in ajax you are using #addformkey. You will have to change the id at one place. I doubt this will work though.
only give me solution using serialize () only
https://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>: $( "input, textarea, select" ).serialize();
I doubt it can serialize a file.
I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>