Send data to PHP with ajax using formdata - php

SOLUTION: I had to drop the sumbmit button and use a regular button. The rest of this code works. I also dropped the HTML form.
I'm trying to send an image + some text to my php script with ajax using formdata.
This is what i got:
$ajax_uploadImage = function (form)
{
var data = new FormData();
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);
$.ajax({
url: '../php/upload_image.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('something');
}
});
}
The form in the function parameters is a normal html form, here is the form in html:
<form enctype="multipart/form-data" id="upload_image">
<label for="title">Title:</label>
<input type="text" id="title" name="title" />
<br />
<label for="comment">Comment:</label>
<input type="text" id="comment" name="comment" />
<br />
<label for="image">Image:</label>
<input type="file" id="image" name="image" />
<br />
<input type="submit" value="Upload picture" name="submit">
<hr />
</form>
The alert in success never triggers, can anyone help?
EDIT: Adding the PHP, even though it doesn't do anything:
<?php echo 'something'; ?>

Right now you are storing a jQuery object in the FormData which cannot work. Use the values of those elements instead. In case of the file input you need to use the File object in the files property of the DOM element:
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);

Try adding form action like:
<form enctype="multipart/form-data" id="upload_image" action="upload_image.php">

Related

How to pass a form with an array of images to php using ajax

PFB my Html code :
<form id="form" enctype="multipart/form-data">
<label>File One</label>
<input type="file" name="file[]" id="file[]">
<br/>
<label>File Two</label>
<input type="text" id="name" name="name">
<input type="file" name="file[]" id="file[]">
<br/>
<label>File Three</label>
<input type="file" name="file[]" id="file[]">
<input type="submit" id="submit" name="submit" value="Submit">
</form>
I am trying to submit this form using ajax as below :
<script type="text/javascript" >
$(function() {
$('#form').submit(function(event) {
var name = $("#name").val();
var file[] = $("#file[]").val();
var dataString = 'name='+name+'&file[]='+file[];
$.ajax({
type: "POST",
url: "k.php",
data: dataString,
success: function(data123){
alert(data123);
}
});
return false;
});
});
</script>
But its not working. i:e the below line :
var file[] = $("#file[]").val();
var dataString = 'name='+name+'&file[]='+file[];
Any help would be highly useful.
I need to submit multiple photos along with text fields using ajax function but I am stuck in this issue from the past many days.
For uploading files using ajax, you need to do some extra work using the FormData object.
Check out http://blog.teamtreehouse.com/uploading-files-ajax for an example of how to do this.

PHP image upload through Ajax serialize()

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.

AJAX isn't getting applied to form

I'm not sure what's wrong with my code but my AJAX isn't working. I've included the jQuery library file but the program just won't load up the PHP file when I call on AJAX. As you'll see below, the .ajax call has a URL to "mail.php" but on submit, this file never loads. I can manually name the action tag for the form to "mail.php" but that just loads up "mail.php", which defeats the point of AJAX. What am I doing wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form method="post" name="myForm" action="tac.php">
<label>Name:</label> <br />
<input name="sender">
<br /> <br />
<label>Email address:</label><br />
<input name="senderEmail">
<br />
<label>Message:</label> <br />
<textarea rows="5" cols="20" name="message"></textarea>
<br /> <br />
<input type="submit" name="submit">
</form>
<script>
$(document).ready(function() {
$("#myForm").submit(function() {
var roy = new Object();
roy.sender = $('#sender').val();
roy.senderEmail = $('#senderEmail').val();
roy.message = $('#message').val();
var jo = JSON.stringify(roy);
$.ajax({
type: "POST",
url: "mail.php",
data: {roy: jo},
success: function(msg){
alert(msg);
}
});
return false;
});
});
</script>
Change
<form method="post" name="myForm" action="tac.php">
To
<form method="post" id="myForm" action="tac.php">
This code
$("#myForm")
is looking for an element with id="myForm" not name="myForm"
Cheers
It's not working because you are trying to trigger an event of an id that doesn't exist.
$("#myForm").submit(function() { the id "myForms" it doesn't exist on < form > tag
put id="myForm" in < form > and it will work fine.
Like this: <form method="post" id="myForm" action="tac.php"> and also remove the name="myForm" because it has no use on form tags ...

Using jquery ajax to update dynamically created image by GET

My current working situation looks something like this:
<!-- collect user info -->
<form method="GET">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<!-- display image based on user info -->
<img src="color.php?param1=<?php echo $_GET['param1']; ?>param2=<?php echo $_GET['param2']; ?>" alt="" />
This is working perfectly. Now I would like only the image being updated by ajax, while the rest of the HTML remains unchanged. I tried this:
<form method="GET" id="formId">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<div id="result"></div>
<script type="text/javascript">
var frm = $('#formId');
frm.submit(function(){
$.ajax({
type: 'GET',
success: function () {
$('#result').html('<img src="color.php?' + frm.serialize() + '" />');
}
});
return false;
});
</script>
In fact this solution works more or less. However, I have some issues here:
Is this good jquery / ajax code or is it silly (yes, I am new to jquery)?
The field "result" does update only if one of the fields changes. Can I make it update whenever the submit button is being klicked?
I would like to display a spinning load.gif while the color.php calculates the picture. I tried it this way, without success:
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
$('#result').html(ajax_load).html('<img src="color.php?' + frm.serialize() + '" />');
Thank you!
To the jQuery ajax call add the parameter cache : false, to force to refresh the image. To use the loader, just play with the attributo src. Copy / paste the code:
<form method="GET" id="formId">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<div id="result">
<img id="preview" src="img/load.gif" />
</div>
<script type="text/javascript">
var frm = $('#formId');
frm.submit(function(){
$('#preview').attr('src', 'img/load.gif' );
$('#preview').attr('src', 'color.php?' + frm.serialize() + '&_' + new Date().getTime() );
return false;
});
</script>

Avoid form action call to php file from loading new page

I have a form that's calling a Post a .php file, which i though was the basis of ajax pushing (as opposed to retrieving data with ajax). Unfortunately, my browser will always load my called .php file instead of staying on the page containing the form. I' thinking there's a specific line of code I'm forgetting somewhere. What should I be looking for?
<form id="form-upload" enctype="multipart/form-data" action="_scripts/ajax/cropImage.php" method="post" onsubmit="return checkCoords();" style="min-height:450px; position:relative;">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" id="ht" name="ht" />
<input type="hidden" id="wt" name="wt" />
<div style="position:absolute">
<h2>Upload a picture</h2>
<input id="input-upload" name="input-upload" type='file' onchange="readURL(this);" /><br/>
<img id="upload-preview" src="" alt="" />
<div style="position:absolute; bottom:0;">
<input type="submit" value="Upload" />
<input type="button" value="Cancel" onclick="$('#fancybox-close').trigger('click');"/>
</div>
</div>
<img id="spinner" style="position:absolute; background-color:transparent; left:49%; top:50%;" src="_images/uploads/ajax-loader.gif" height="32" width="32"/>
</form>
Seems that your understanding of AJAX is a little wrong, don't take me wrong, I suggest you to read more about it and try to implment it using Jquery libraries for Ajax. Those functions are very well documented and have great examples.
I would not use form tag while using ajax.
This is an example function you would use when use "submit" the data:
$.post("_scripts/ajax/cropImage.php", {
"y": yValue,
"x": xValue,
"h": hValue,
...
"input-upload": inputUploadValue
});
Explaining: You will send all values at the object ("y", "x", etc) to "_scripts/ajax/cropImage.php", as POST variables. You can also create a callback function, to receive data from the URL you sended those values, and validate if everything ran well.
It seems you're using the action attribute of your Form and submiting it. Show us all your related code, please. (Text before showing the code)
You can post data the same way you can retrieve data with jquery's ajax library.
See the .post() method.
You can get the contents of your input fields and then send them with ajax. If you want to keep your current form structure, you can use doSubmit(); return false; in an onsubmit event to cancel the original submit, and use your ajax method.
You are using a submit type button.
Change the type to "button", and make the onclick event something like:
onclick="sendData();"
Your sendData() function should contain the proper AJAX.
I see you are using jQuery, so just use the built-in ajax functions:
$.ajax({
url: "_scripts/ajax/cropImage.php",
context: document.body,
success: function(html){
alert(html);
}
});
$('#btnSubmit').click(function() {
// we want to store the values from the form input box, then send via ajax below
var comment = $('#comments').val();
var name = $('#Name').val();
$.ajax({
type: "POST",
url: "contactus.php",
// data: "fname="+ fname +"& lname="+ lname,
data: "name="+ name +"& comment="+ comment,
success: function(response){
$('#mail_sent').html(response);
}
});
});

Categories