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
Related
I have the following icon present in my system, which on click, should allow the user to delete a post:
<span id='remove' class='glyphicon glyphicon-remove' aria-hidden='true'></span>
clicking on the icon should then perform a PHP query which will drop the row from the table, removing the post from the database.
But I am unaware and want to discover if making an icon perform an action is possible?
The process
There are essentially five steps to take :
1) You can send a HTTP request to an url http://www.example.com/post/15 when you click your remove button :
$("#remove").click(function(){
$.ajax({
type: "DELETE",
url: "http://www.example.com/post/1",
data: [],
success: function() {
console.log("Yey!");
},
dataType: "json"
});
});
3) On the server, you could use .htaccess to forward all your requests to index.php.
4) In index.php, you could use eg. $_SERVER['PATH_INFO'] to know that post/15 is the final part of your url http://www.example.com/post/15. From this, your code in index.php should conclude that that you're trying to do something with the post that has an id with value 15, and from the request type it can conclude that you want to delete it.
5) Once you know that, you can just delete the post with id 15 from the database and echo whatever response you want to send back to the client.
Some sources to check out
How to Use jQuery’s $.ajax() Function
A Beginner’s Guide to HTTP and REST
Httpful: The REST Friendly PHP HTTP Client Library
You can use javascript to bind an action to a browser event (such as a 'click'). In your case, look at the onclick event in javascript.
It may be easier to use jQuery:
https://api.jquery.com/click/#click-eventData-handler
Then you will need to use ajax to submit the form to the server (your php script). jQuery provides functionality for this as well:
http://api.jquery.com/jquery.ajax/
what you could do is make a button in the same form and hide it by using css, then you could activate this button on clicking the span tag:
Html:
<input type="submit" id="#hiddenButton" style="display:none;"/>
Jquery:
$("#remove").click(function(){
$("#hiddenButton").click();
});
I created a submit form with JS simply to post a variable to PHP:
entry.innerHTML= ' <form action="eLoad.php" method="post"> <input class="submitLink" type="submit" name="name" value='+uploaded[i][1]+'> </form>
It works but in my php i want to send back a variable to JS. I'm using Json but every time I submit, the form submits to my browser and ouputs the php file and echos whatever JS text I have on the browser. I want to redirect to another page after the php and the JS (json) in my php loads.
Any help? Thanks
Sounds like sending an AJAX request and redirecting on the callback function is what you need.
As suggested here, I also strongly recommend using an existing library.
To use jQuery for example, you'll first have to include it by adding:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
Once you've done that and can use the library, try something like this:
$.ajax({
url: "eLoad.php"
}).done(function() {
window.location = <url-to-redirect-to>;
});
One last thing to mention, there are many useful params you can use when calling the jQuery's ajax function, take a look at http://api.jquery.com/jQuery.ajax/
What you are looking here is for async submition of forms, otherwise known as AJAX.
I suggest you adopt an existing library to do the boring part for you.
Visit this Lightweight JS AJAX library , you will need to use ajax as suggested, implementing and using jQuery will be the fastest way, but do go for other options like zepto.js, mootools, etc. Also if you want to build your own solution for your problems do a little research on xmlhttp, refer to this link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
You wont have to write a lot of code to do this, but using readily available libraries wont hurt.
I recommend an AJAX solution. Take a look at the JQuery JavaScript library at http://api.jquery.com/jQuery.ajax/. With AJAX you can load content (and post forms) dynamicly into your webpage without refreshing the page.
Edit: Example code:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).on('submit', 'form#my-form', function() {
$.ajax({
type: "post",
data: $(this).serialize(),
url: "my_page.php",
success: function(response) {
alert(response);
}
});
});
</script>
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
I am trying to do a simple query for info from a database through an html page. I've got all the backend stuff working fine, but I'm having trouble on the client side. I currently have a form where the user submits their ID# to get some info on their case.
But with my current setup, it returns an entirely new page and I just want to read in a text string, process it and update the content on the current html page without opening up a new one and replacing the old one. How can this be done?
Here's my code so far:
function showInfo() { } // I want to make the request here instead
<form name="register" action="http://localhost:8080/testapp/authenticate" method="get">
<p><label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
<button id="checkButton" type="submit" onClick="showInfo()">Enter</button>
</p>
</form>
My guess is that you're actually submitting the form, which is posting back to the server. What you will want to do is cancel the form from submitting and submit it using AJAX (which is what I believe you want?).
To do so, your showInfo() function should do one of these three things (I can never remember which one)
return false;
cancel the event, something like e.preventDefault()
stop the propagation, something like e.stopPropagation()
Once you've successfully prevented the form from hard-submitting, you can then do what you'd like by submitting your data via AJAX and manipulating your response however you'd like.
1st - Jason is absolutely right that what you want for this situation is AJAX, below is an example in motion.
2nd - You should be using a Javascript library such as jQuery, which might look intimidating (as it did for me at first), but it is really easy and completely worth the small effort to get it going.
3rd - With jQuery, your application tidbits should look something like this, using the example you provided:
HTML -
<p>
<label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
// Please note that I removed the onClick section from the line below.
<button id="checkButton" type="button">Enter</button>
</p>
JQUERY -
// The default function you described to take information and display it.
function showInfo(data) {
// Insert your function here, probably using JSON as the Content Type
}
// This is the key AJAX function, using jQuery, that takes your info and gets a
// response from the server side, the sends it to the function above in order for it
// to be displayed on the page.
function processIdInfoCheck() {
$.ajax({
type: 'post',
url: '/http://localhost:8080/testapp/authenticate',
data: {
'id': $('#badge').val();
},
dataType: 'json',
success: displayIdInfoReturn,
error: function () {
alert("There was an error processing your request, please try again");
}
});
}
// When the page loads, the code below will trigger, and bind your button click
// with the action you want, namely triggering the AJAX function above
(function ($) {
$('#checkButton').bind('click', processIdInfoCheck);
})(jQuery);
Just remember, AJAX takes some effort to get the desired effect, but when you look at page load times, request numbers, etc... It is totally worth it. Please let me know if this was helpful and if you need any specifics.
I was trying to upload file(s) using PrototypeJs request method but I failed.
The code I am using,
<form enctype="multipart/form-data" id="form1" runat="server" action="ajax.aspx"
onsubmit="upMe(this);return false;" >
If I make return true instead of false, the file is uploaded but that makes postback which I dont want as I am using the method request from PrototypeJs.
And the function upMe is very simple,
function upMe(frmEle) {
$(frmEle).request({
method: 'post',
parameters: {},
onComplete: function() { alert('file has been uploaded'); }
});
}
What I am missing to upload file in the above way?
Thank you so much.
The problem is you're using AJAX instead of normal submission methods to post the form. This would require JavaScript to read the file and include it in the submission, but as you can imagine the ability for a script to read a local file from the client would be rather a large security risk :-)
The answer to this problem is to use a hidden <iframe> element instead, and submit the request to that. You can register event handlers to the iframe's onload event for an oncomplete style callback.
http://www.openjs.com/articles/ajax/ajax_file_upload/