I'm trying to integrate juqery fileupload with an ajax form submit. The ajax form sends the text and returns the ID of the newly created event, This is necessary to know which event to link with when uploading.
The simple upload demo uses the following code
Here's the ajax that first upload the non-file fields
$.ajax({
type: 'post',
url: '/whats-on/upload-event/',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (return_data) {
console.log(return_data)
}
});
It returns the following json
Object {status: true, id: 17162}
However the fileupload sends the files without declaring data: data,
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" data-url="server/php/">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
//Returns ID as e['id'] and 200 status also with e['status']
}
});
});
</script>
</body>
</html>
You first need to get the event Id with an ajax post:
function uploadClick(){
var eventId = getEvent();
uploadFile(eventId)
}
function getEvent(){
// make an ajax and return your id
}
One you got it, then create an URL with a query string indicating the eventId. this URL is where you want to post your file:
function uploadFile(eventId){
// attatch the id to the URL with query string
url = url + '&eventId=' + eventId;
// submit here your file
}
This way you can post in the same ajax call the file itself and the event id. In you server side action you need to get this query string and then pick the posted file.
You may have to handle callbacks for fileupload plugin like:
$('#fileupload').fileupload({
url: <url>,
type: <HTTP_VERB>,
other configurations...
}).bind('fileuploadadd', function (e, data) {
//fires when you select a file to upload
}).bind('fileuploaddone', function (e, data) {
//fires when upload completed successfully. equivalent to done call back of jQuery ajax
}).bind('fileuploadfail', function (e, data) {
//fires when upload fails
});
For complete reference please take a look at the following link .
Related
I have an ajax get request that has a data of an input. I want to pass this data into a variable and use it in my query.
index.handlebars
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="hidden" class="test" name="test" value="sample"/>
<script type="text/javascript">
$( document ).ready(function() {
var username = $('.test').val();
$.ajax({
type : 'GET',
url: '/users//welcome',
data : {
wew: username
}
});
alert(username); //correct output
});
</script>
</body>
</html>
and in my users/welcome
router.get('/welcome', ensureAuthenticated, function(req, res){
var test = req.query.wew; //data from ajax request
Item.find({username: test},function(err, docs, test){
//where username is the data
console.log(test);
res.render('welcome', {docs:docs});
});
});
This code is not working. Please help :/
You could use socket.io. I use it for bi-directional communication between the browser and node.js server.
On the client side you would do:
function movePlayer () {
socket.emit ('doSomethingServerSide', {numVal: 4, usrName: 'KaiserSolze'});
}
And server side you would have:
// A FUNCTION THAT LISTENS FOR A CALL FROM BROWSERS CONNECTED VIA SOCKET
socket.on ('doSomethingServerSide', function (msg) {
// THEN YOU COULD REPORT TO ALL BROWSERS / CLIENTS THAT SOMETHING WAS DONE
io.sockets.emit ('reportToClients', msg);
});
If you decide to go this route there are lots of posts here to help you get started with socket.io.
Try giving your website full URL with http and replace double (//) with one
$.ajax({
type : 'GET',
url: 'http://<your application full url>/users/welcome',
data : {
wew: username
}
});
Or you can try below
$.ajax({
url: "/users/welcome?wew="+username,
type: "GET",
contentType: "application/json",
dataType: "json",
});
var test = req.query.wew; //data from ajax request
Just change to this one with this one:
var test = req.body.wew
Also you need to import body parser to your project for getting req.body.keynames
I have this code in my JS function, I need to call a PHP file "valiadte-attrib-form.php" this PHP script returns a variable.
This is my HTML page:
<form method="post" id="form1" name="form1" action="<?php echo $editFormAction; ?>">
<script>
$(function() {
$('#form1').submit(function() {
return validateForm();
});
});
</script>
This is my JS code:
function validateForm() {
var form = $("#form1");
$.ajax({
context: form,
type: 'GET',
url: 'validate-attrib-form.php',
data: params,
success: function(response){
alert(response);
result=response;
return result;
}.bind(form)
});
This is my PHP code:
<?php
echo "false";
But my problem is when a I see alert(response); I see full HTML codelike this:
<!doctype html>
<html lang="es">
<head>
<meta charset="iso-8859-1"/>
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1"/>
.....
.....
What's wrong in my code? I need that alert(response) shows false not HTML code.
Thanks for your help!
You're getting a server error like a 400 or 500-series error ... Sometimes, depending on how the server is configured, this may look like a re-direct, at which point you may see a full HTML page without any error codes, like the main page of the site if the redirects are being done to suppress errors to end-users.
I'm also a little confused at the structure of your $.ajax call. You may want to change it to the following:
function validateForm() {
var form = $("#form1");
$.ajax({
/* context: form, //not sure you need that */
type: 'GET',
url: 'validate-attrib-form.php',
data: form.serializeArray(), /* turn the form data into an array */
dataType: "text",
success: function(response){
alert(response);
/* do other stuff... */
}
});
}
$("#form1").on("submit", function(ev) {
ev.preventDefault();
validateForm();
};
You don't need to specify a form action attribute if you are attempting to make an AJAX call to an endpoint.
I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
Just trying to learn using ajax with appengine,started with the post method,but it does not work.
This is my HTML Code for the page
<html>
<head>
<title> Hello </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
success: function(data,status){
alert("Data" + data +"status"+status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="/test">
<input type="submit" id="subbut">
</form>
<div id="success"> </div>
</body>
</html>
Here goes my python code to render the above html code , its handler is /test1
from main import *
class TestH1(Handler):
def get(self):
self.render('tester.html')
And this is the python script to which AJAX request must be sent to,handler is /test.
from main import *
import json
class TestH(Handler):
def post(self):
t=self.request.get('name')
output={'name':t+" duck"}
output=json.dumps(output)
self.response.out.write(output)
Expected behavior is that when i click on submit button,i get an alert message saying "Hola duck" , get nothing instead.
Any help would be appreciated as i am just starting with AJAX and Jquery withGAE
At first, I suppose you should suppress default behavior of form submitting when you press submit button by adding "return false" to the .click function. But I suppose it would be better to use just
<input type="button" id="subbut">
instead (even without form).
Then you should add "dataType: 'json'" to your ajax call to tell jQuery what type of data you expect from server. Doing this you will be able to get response data by property names like "data.name". So:
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
dataType: 'json',
success: function(data,status){
alert(data.name);
alert("Data" + data +"status"+status);
}
});
return false;
});
});
and it would be better if you set appropriate content type header to your response:
response.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.response.out.write(output)
I'm trying to implement voting very similar to Stack Overflow's. There are multiple items that all have a vote button next to it. Currently, I have it working, but it's done server side, posts back, and takes a while to reload the data. Here is the flow:
You click the vote button,
it fires a javascript function which clicks a hidden ASP.NET button (did it this way because there are multiple vote buttons per page),
the button fires,
it updates the database, and then
the page posts back and refreshes, showing the update.
How do I leverage javascript and AJAX to eliminate this bad user experience? I want it to work like Stack Overflow's, but I'm not using MVC. Any help, examples, suggestions would be great. Thanks.
Update:
I have this implemented, but when I place breakpoints on the Web Method it doesn't even fire and I always get the error alert. Any ideas?
javascript:
<script type="text/javascript">
$(document).ready(function () {
$("[id^=VoteMeUp]").click(function (event) {
var dta = '{ "VoteId":' + $(event.target).val() + '}';
$.ajax(
{
type: 'POST',
data: dta,
url: 'Default.aspx/SaveUpVote',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//$(event.target).text("Vote Casted");
alert("Vote Casted");
},
error: function (x, y, z) {
alert("Oops. An error occured. Vote not casted! Please try again later.");
}
}
);
});
});
</script>
Code Behind (you can use C#, I'm familiar with both):
Imports System.Web.Services
Imports System.Web.Script.Services
<WebMethod()>
Public Shared Function SaveUpVote(ByVal VoteID As Integer) As Boolean
Dim test As Boolean = False
Dim mySQL As New SQLHandler
test = mySQL.UpdateVoteByID(VoteID)
Return test
End Function
HTML:
<input type="image" src="images/vote.png" id="VoteMeUp1" value="321" />
When a vote is cast for a given button, call the server method using ajax (for aspx) as follows:
$(document).ready(function() {
$("[id^=VoteMeUp]").click(function(event) {
var dta = '{ "VoteId":' + $(event.target).val() + '}';
$.ajax(
{
type: 'POST',
data: dta,
url: 'Default.aspx/SaveUpVote',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$(event.target).text("Vote Casted");
},
error: function(x, y, z) {
alert("Oops. An error occured. Vote not casted! Please try again later.");
}
}
);
});
});
In Default.aspx.cs
[WebMethod]
public static void SaveUpVote(int VoteId)
{
string UpdateSQL = "UPDATE TableName SET Votes = Votes + 1 WHERE PKID = #VoteId";
//do DB stuff
return;
}
Sample HTML:
...
<body>
<button id="VoteMeUp1" value="817">1 - Vote for this</button>
<button id="VoteMeUp2" value="818">2 - Vote for that</button>
</body>
...
the easiest method to do this would be WebMethods.
Add a ScriptManager to your page with EnablePageMethods set to true
aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Assign a web method attribute to the method which increments the votes in your (c# here) code behind:
c# code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string ChangeVote(string Arg){
...logic to change votes
}
in your javascript event, you can then access the code behind via pagemethods, and define functions to call on success and fail cases:
javascript:
PageMethods.ChangeVote("sent item", OnChangeVoteComplete,OnChangeVoteFail);
function OnChangeVoteComplete(arg){
//arg is the returned data
}
function OnChangeVoteFail(arg){
//do something if it failed
}
the success function receives the data returned by the WebMethod. You can use this to update the display on the page.
When use clicks on the UpVote button, make an ajax call to the server where you execute a query againist the database to increment the vote.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
Vote UP
</body>
<script type="text/javascript">
$(function(){
$("#aUpVote").click(function(){
$.post("myajaxserverpage.aspx?qid=12",function(data){
alert(data);
});
});
});
</script>
</head>
and in the server page (myajaxsever.aspx), read the values and execute your query to increment the Vote column value. value of qid is the question id this you can read from the page because it is going to be dynamic.