Having issues uploading an image via ajax - javascript

Sorry if the title isn't descriptive enough!
The idea is to have a div popup and allow users to type in their feedback and possibly submit a screenshot.
This is the javascript inside the page (which is called via ajax into a div).
Javascript
$("#submitFeedback").click(function(){
//Check if the form is valid
if($("#form").valid()){
$("#form").hide(); //Hide the form
$("#feedbackReport").append("<h2 style='color:white'>Submitting!</h2><hr />" +
"<div style='text-align: center'><img src='images/loader.gif' /></div>");//Display loading spinner
$.ajax({
type: "POST",
url: "ajax/submit_feedback.php",
cache: false,
data: $("#form").serialize(),//serialize form for submission
success: function(data) {
$("#feedbackReport").empty();//Clear form after submission
$("#feedbackReport").append("<h2>Thank you!</h2><span id='close'>✖</span><hr />"
+"Your feedback has been submitted successfully!"
+"<br /><br /><span id='cancel'>Close</span>");
$("#cancel,#close").click(function(){
$("#feedbackReport").parent().hide();
});
}
});
return false;//Prevent page from changing
}
});
Now, if point my browser to the actual ajax page (ajax/feedback.php) and submit an image, it works fine! When I run it from index.php and call the feedback window via ajax, it wont submit my picture, only the text.
I know my submit_feedback.php page works fine because of this, I just have no idea why it won't post the image properly.
Any tips or help would be greatly appreciated!

Ajax can't do file uploads. You have to use something different such as https://github.com/valums/file-uploader

Ajax does not allow file uploads however the neat trick is to use an iframe that holds the file upload form and auto submit it when a file is selected.
This way only the iframe is redirected and it gives it an ajax feel.
Read more here

Related

When I disable submit button (after form submit) the page does not load

I have an HTML form which submits to another page via POST. Nothing special about it, except that after the form validates I try to hide and/or disable the submit button so that it cannot be double-submit, while also telling the user the next page might take a while to load.
The relevant code is:
jQuery(document).ready(function () {
jQuery("form#form").submit(function() {
var result = validate();
jQuery(this).find('input[type=submit]').prop('disabled', true);
jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html()+
"<br/><br/><span style='margin: 25px; padding: 5px; background: yellow; "+
"width: 100%; font-weight: bold;'>Loading... this may take a few minutes! "+
"<i class='fa fa-spinner fa-spin' style='color: blue;'></i></span>");
return result;
});
});
function validate() {
return true; // Does stuff, then returns a simple true or false
}
By request, here is the (very simple) button wrapper HTML:
<div class="col-sm-12" id="submit-button-wrapper">
<input type="submit" value="One More Step" />
</div>
When the I remove the which changes the button wrapper's HTML, the form submits just as you'd expect. When I have that line in, however, it still calls the next page and executes that code, without the displayed page ever changing.
I have tested in both Chrome and Firefox, so I know it's not a browser issue, but this is really weird behavior. What am I doing wrong?
My goal: (1) validate the user's input, (2) give the user a clue that the page is going to take a while to load and (3) display the output from the action="complete.php" page once the PHP on it has run.
Maybe you can achieve this with $ajax and show results on the same page.
Send POST data to /some.php
After sending data, give feedback to user changing button behavior
When the task is complete, receive data and verify success or error and act accordingly. If OK, change button text to "complete!" or something else, and append response data to some div. If NOT OK, give feedback as well.
In code:
$("form#form").submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "some.php",
data: $(this).serialize(),
dataType : 'json',
timeout: 2000,
cache: false,
afterSend: function() {
/*change button behavior here*/
},
success: function(result) {
if (result === "ok"){
/*maybe append data to div and update button text to complete*/
} else {
/*if result not ok, send feedback*/
}
}
});
});
BTW: ajax documentation http://api.jquery.com/jquery.ajax/
When you return true (if validated) then the form is submitted. However, you're changing the DOM / submit button wrapper and essentially removing the submit button, right? Likely that is what is causing your problem. Leave the submit button wrapper alone. If you want to display a message display it as an overlay or hide the submit button wrapper and show the message wrapper in its place, don't remove the submit button altogether.
I know that you're just showing a slight jQuery and HTML portion of the script, but that isn't quite enough to figure out your problem. Since not all of it seems to be there because you mention action="complete.php" but I don't see that within your jQuery or HTML sample of code. So I have a few questions of my own.
Is the form small or large. If it's a small form then why aren't you displaying the output on the submit page? You could do that with what you currently have but a single PHP or ASP page could save you on amount of pages to make and what not. As a side note, depending on size of the form, you can do the validation on same page or continue to use action="" for it if large.
Do you have need for a database file or are you saving to one? If you do/are, you could write to the DB file, have the submit open the next page and view what was saved in the database on that new page. Again, you can probably use a single PHP or ASP page.
This last part sounds more valid for your purpose. You could use location.href="http://www.domain.com/home.html";
or use window.location("http://www.domain.com/home.html"); to redirect to the new page.
On another matter about some of the comments others made.
You don't exactly need the + unless you're dividing each of those out into their own separate lines when you could just use one line to do that. That's probably what confused Rajesh about the '. In fact I'm not sure why you yourself mentioned the + when referring to Rajesh comment about "concat string" and "append" ,because those two have nothing to do with the +. In fact to take a guess, he might have been referring to your jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html() which kinda looks like a concat string.
Speaking about append, not really needed unless for example you're doing something like giving the user the option to add rows to a form question.

PHP Private Chat Long polling integration

i've got a simple question here,
Ive got this form thats inside my chat html:
<form action="../addchat.php" method="POST" enctype="multipart/form-data">
<textarea id="textarea" style="border-radius:0px; border:none; background-color:rgb(243,243,243); min-height:100px;"name="comment" rows="4" cols="50"></textarea><br>
<input height="25px" width="20px" style="float:right;" type="image" src="../arrow.png" name="submit" value="Comment">
</form>
This form is for users to submit their chat messages. and after which, form post will direct the information to addchat.php, which contains the following code:
<?php
ob_start();
session_start();
include_once("config.php");
$reply=mysqli_real_escape_string($mysqli,$_POST['comment']);
$cid=mysqli_real_escape_string($mysqli,$_SESSION['cid']);
$uid=mysqli_real_escape_string($mysqli,$_SESSION['userid']);
$time=time();
$ip=$_SERVER['REMOTE_ADDR'];
$q= mysqli_query($mysqli,"INSERT INTO conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$cid')") or die(mysqli_error($mysqli));
?>
This script obviously adds the data into the tables and after which another script on the chat html page will display out the chat messages.
However, the current issue is that firstly, after user click submit, page will redirect to another blank page and show success message. Secondly, user need to refresh to see the new chat messages.
This chat application is a private chat (similar to Facebook), so not very sure how to do it? Would appreciate some help:)
If you do not want it to redirect. Move the PHP code to the same file as the form. You could use include for this.
Then make the form action="".
Then around the PHP, you need to check that the POST exists so it only runs when the form submits:
e.g.
if (!empty($_POST))
As for the refresh problem. You may want to look into AJAX or even socket.io.
It is not simple to answer this question, as it belongs to how hard/complex you want in your chat application.
If you don't want to get redirect when submitting, you can use AJAX to post the form Submit a form using jQuery
If you don't want to refresh the page to load new chat messages, you can use AJAX call to get new messages in interval of time http://www.w3schools.com/jsref/met_win_setinterval.asp.
If you want to receive new chat messages at the time they are sent from sender (who is chatting with current user), you might consider about using push server like NodeJS (http://nodejs.org) or Socket.io (http://socket.io/)
I wouldn't use PHP for that purpose if I were you, or if you do, you'll need lot of ajax to make this chat working.
ajax request to send... ajax request every n milliseconds to fetch new messages. you should also use an api instead of a webpage to interact with your server-side app. Your server will need to be highy available and respond really fast.
You should choose a language that support websockets (take a look at python with django, for example, or java, or whatever...) if you want this chat to be really efficient.
While writing these lines I found something (Ratchet library)to use websocket in php (I don't know how it works but maybe you'll get problems with the max_execution_time of your server if it works with a "while true" loop)
Edit: as Tuan Duong suggests, nodejs is another good alternative
standard html form submissions always will submit (and redirect) to the page defined in the action attribute of the form. with jquery you can prevent this default behavior plus send the form-data with ajax:
$("form").on("submit", function(event){
event.preventDefault();
$.ajax({
url: "../addchat.php",
type: "POST",
cache: false,
data: {
comment: $("#textarea").text()
},
success: function(data){
//something you could do on success of your ajax call.
//you might not need it in this case.
}
});
});
secondly, you'll need some procedure that refreshes your output-area automatically. create a div in your html to show the chat-output:
<div id="chat_content_div"></div>
then you'll have to do something like this in your javascript to refresh it automatically:
var refresh_time = 500; // chat refresh time in ms
setInterval(function(){
$.ajax({
url: "chat_output.php",
type: "GET",
dataType: "html",
cache: false,
success: function(data){
$("#chat_content_div").html(data);
}
});
}, refresh_time);
in the "chat_output.php" you only display (html) data from the database to be displayed in this div.

Reload only specific input fields of parent page after close child page

I have HTML form where I open a new popup and insert some data and refresh the
complete page and close the popup.
But my problem is: I want to refresh only specific input field data not whole page.
Kindly also send some links for details and demo.
Thanks in advance
Use ajax (maybe jquery, if you are already using it)
$.ajax({
url: "http://url_to_get_input_field_data",
}).done(function( data ) {
$("input_field_id").val(data);
});

jQuery ajax Upload $_FILE

I'm using jQuery plugin with $.ajax() functions.
There is some way to upload a file with POST and do some function when is it done?
here my code.... what i do wrong?
$.ajax({
url: "../index.php?rqst=upload",
type: 'POST',
data:{
'fileToUpload': $("#fileToUpload").val()
},
success: function(data) {
alert("file upload");
}});
and this is the file input:
<input class="form-control" type="text" name="fileToUpload" id="fileToUpload">
and there is a way to display a gif during the load???
thanks in advance
File uploads must be enctype='multipart/form-data' and you can't mix GET and POST like you're doing. Since this is POST, remove the ?rqst=upload from the url. Also $("#fileToUpload").val() is only going to give you the name of the file, not the actual file. You need a specialized javascript library to do file uploads with Ajax. Also, for a file upload, your input's type must be type='file' not type='text'.
It's much easier to use $.post() than $.ajax().
You have it almost right. Instead of success use complete.
Just before running $.ajax(), add some simple dom manipulation code that puts a spinning gif somewhere. Then in the success callback handler add code to remove it.
Also, there is a javascript library for making spinning loading icons: http://fgnass.github.io/spin.js/#!
firstly i would check you are able to connect to the file directly,
comment out your data section and the change the url to a page holding an echo only.
then if the page can be found connected to you will get the alert.
on another note ensure "index.php?rqst=upload" has an echo in it so the success function picks it up. i usually use echos within if else statements so i can see if an error occurs and what error, then i can use the js to display the necessary message

Refreshing div content (php content) with ajax

i am trying to be able to edit my custom cms blog posts without leaving the page.
The way it works is each post has a edit button which when clicked hides the post text, and displays a ckeditor and also a save button.
All the code works correctly behind the scenes as to say, when saved an ajax call is made to another php page which updates the posts content. Now the issue is i want to on save, show again the text and hide the editor.
I can get this working, but i cant get the div text to update to the new content until the page is refreshed.
So the ajax looks like so:
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$targetForm.find('.editor').toggle('hide'),
$targetForm.find('.buildtext').load('http://localhost/buildsanctuary/viewbuild.php?id=134 +bt+'),
$targetForm.find('.buildtext').toggle('show'),
$targetForm.find('.edity').toggle('show'),
$targetForm.find('.saveupdatebutton').toggle('hide');
else
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
and this is how im trying to use a variable in the selector...
var bt = $(this).attr(".buildtext");
hope this all makes sense?
Craig.

Categories

Resources