I desire to upload files asynchronous when the user select a file in a input file, with $.ajax. But the php that recive the call return index undefined.
The jquery code is the next:
$("#urlimatge").change(function(){
var filename = $("#urlimatge").val();
$.ajax({
type: "POST",
url: "utils/uploadtempimg.php",
enctype: 'multipart/form-data',
data: {'urlimatge' : filename },
success: function(response){
alert(response);
}
});
});
and the php that recibe the call:
$image = new gestorimatges();
$target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']);
Thanks
you cannot pass the $_FILE from AJAX to PHP.
I would suggest use a plugin
It will make your life easier :) Here is a video tutorial to help too
You might wanna use tools like uploadify for that.
You can't upload files with AJAX, but you can use an iframe so you don't have to refresh the current page.
Many people go strait to plugins but you can do this yourself pretty easily, and with all the functionality of an AJAX request.
Instead of using an AJAX function, have a form submit to a hidden iframe that has a load event handler attached to it so when the form is submitted, you have a callback function that actually includes the server response (the HTML of the iframe after it loads).
Example:
HTML --
<form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" >
<input type="file" name="file" />
<input type="submit" />
</form>
<iframe id="workFrame" src="about:blank" style="display:none;"></iframe>
JS --
$(function () {
$('form').on('submit', function () {
//check if the form submission is valid, if so just let it submit
//otherwise you could call `return false;` to stop the submission
});
$('#workFrame').on('load', function () {
//get the response from the server
var response = $(this).contents().find('body').html();
//you can now access the server response in the `response` variable
//this is the same as the success callback for a jQuery AJAX request
});
});
Related
I was wondering how I could go about sending a .csv file from a file input container in HTML to another .php file in ajax.
Here's my code:
$(document).ready(function () {
$(".Rsubmit").click(function () {
?????What would I declare to contain the .csv file?
var checkurl = './CSVRemove/getAccountsCSV.php';
runCSVcheck(checkurl);
});
});
function runCSVcheck(checkurl)
{
$.ajax({
type: "POST",
//dataType: "json",
url: checkurl,
data:
{
???? what would I put here?
},
success: function(response) {
code....
});
}
HTML:
Input boxes.....
<span>Enter .csv File: </span><input type="file" name="file" value="" />
Please let me know if there is a solution!
David
If you're planning on sending a file upload via Ajax, I suggest using a jQuery form plugin that support file uploads.
There are a number of them available, but I've had good success with this one: http://www.malsup.com/jquery/form/
It allows you to post a form via Ajax, even if the form includes file upload fields. PHP will receive the form post exactly as it would have done normally if it had been posted via a regular form submit.
Alternatively, you could use HTML5's file API, but only if you don't need to support older browsers like IE8. The jQuery form plugin is probably the safer way to go for now.
hope that helps.
I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.
Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});
If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault
Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.
I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.
Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.
This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.
If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});
If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}
First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});
After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).
First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});
Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.
I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.
I am attempting to submit a form via jQuery. My form contains fields and a file that must be uploaded. It is of type ENCTYPE="multipart/form-data".
I can receive all my field values using: post = $('#myForm').serialize();
But how do I receive the $_FILES array? I need this to process the uploaded file.
Is this possible using jQuery, and if so how? Or do I need to use a special upload plugin for jQuery?
jquery form is the best way to do it,
you can add it to any normal form,
<form method="post" action="URL">
<input type="file" name="file">
<input type="text" name"text">
<input type="submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
$(form).ajaxForm();
})
</script>
will work as expected, but with ajax.
http://malsup.com/jquery/form/#code-samples
You cannot upload files through javascript.
Check out this related question:
Is it possible to use Ajax to do file upload?
Essentially, the two most popular ways of "faking" AJAX for file uploads is using a Flash plugin such as SWFUpload or submitting the form to a hidden iframe that processes the request.
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent
Use FormData
<form>
<label for="imageToSend">Cargar imagen a la galeria</label>
<input type="file" name="imageToSend" id="imageToSend" value="Cargar imagen" />
</form>
<script>
$('#imageToSend').on('change',function(event){
var dialog = $('#dialog');
var Data = new FormData();
Data.append('imageToSend',$('#imageToSend')[0].files);
$(this).val('');//Clear input file
$.ajax({
url: "/upload",
data: Data,
processData: false,
contentType: false,
type:'POST',
success: function(data){
if(data.success){
//success handler
}else if(!data.success){
//error backend handler
}
},
error: function(data){
//error handler Ej:404 status
}
})
});
</script>
If you can control the environment, like, say, you're writing an admin app for an intranet in which you recommend the browser, then real AJAX file uploads are possible with Firefox 3 and above. In all other cases, the iframe workaround or a Flash based uploader is the way to go.
It's possible, but not working in Google Chrome )
Look!
...
<form method='post' enctype='multipart/form-data'>
<input type="file" id="imf" name="imf"/>
<input type="button" id="Save"/>
</form>
...
$("#Save").live("click", function(){
var photo = document.getElementById("imf");
var file = photo.files[0];
$.post('/user/saveNewPhoto', {'imf':file.getAsDataURL(), fname:file.fileName }, function( data ){
alert ( data );
});
});
upload side script
need decode base64 ) and that is all
but i don't test this script on big size file