I'm new to AJAX programming, but I found an example on jfiddle that is very close to what I'm trying to accomplish. I can't make it work, however. I put a reference to the same version of jquery in the header, but the page doesn't do anything when I hit the submit button on 'my version'. Also, the animated loading cursor spins forever. Here is the jfiddle reference:
http://jsfiddle.net/clickthelink/Uwcuz/1/
Here is what I think is the same version. I must be doing something wrong, but I'm really not sure what. I can't seem to make it work in StackOverflow either.
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
$("#loadingimg").hide();
}
});
});
});
body{
font-family: 'Open Sans', 'Helvetica Neue', 'Arial', sans-serif;
font-size: 13px;
}
form span{
display: block;
margin: 10px;
}
label{
display: inline-block;
width: 100px;
}
input[type="text"]{
border: 1px soild #ccc;
width: 200px;
padding: 5px;
}
input[type="submit"]{
padding: 5px 15px;
}
span#result{
padding: 5px;
background: #ff9;
}
img#loadingimg{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form method="post" action="/echo/html/" ajax="true">
<span id="result">jQuery + AJAX form submit script.</span>
<span>
<label>Message: </label>
<input type="text" name="html" placeholder="Howdy..." />
</span>
<span>
<label><img id="loadingimg" src="http://dev.cloudcell.co.uk/bin/loading.gif"/> </label>
<input type="submit" value="Submit" />
</span>
</form>
SO is sandboxed and will not allow the ajax to go through.
As for the original example, jsFiddle has a "fauxjax" kind of setup that will simulate ajax responses when you use action="/echo/html/" which is why the original example appears to work (though it is just simulated):
See the Jsfiddle Docs for more info on this feature
If you are trying to run this example on your own server etc, make sure to update the action attribute in <form method="post" action="/echo/html/" ajax="true"> to point to the file, on your server or elsewhere, that will receive and respond to your ajax call (like a php script)
Since you're new to Ajax, it may also be helpful to learn about CORRS (Cross Origin Resource Sharing) which will apply if you are ever trying to send an ajax request from one domain and have it received and/or responded to from another domain.
it doesn't work here because http://stackoverflow.com cannot make cross origin requests to http://stacksnippets.net/echo/html/
it probably doesn't work for you because you don't have /echo/html service in your backend
Related
I am working on a resume generator and I want to be able to save the
input form data into a .yml file but I can't seem to find any article
to give me some clues. I want that once the submit button is clicked, the data is automatically written in the .yml file
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<div class="biography">
<h2>Fill in your education information</h2>
<label for="degree">Degree</label>
<input id="degree" type="text">
<br/>
<label for="from">From</label>
<input id="from" type="date">
<br/>
<label for="to">To</label>
<input id="to" type="date">
<br/>
<button id="submit" type="submit">Submit</button>
</div>
</template>
<script>
export default {
name: "Education"
}
</script>
<style scoped>
input {
margin-left: 100px;
margin-bottom: 10px;
border: 2px;
width: 300px;
height: 3em;
display: inline-block;
}
button {
font-size: 16px;
padding: 10px;
background-color: #004d4d;
color: white;
border-radius: 6px;
}
button:active {
background-color: #00e6e6;
}
label {
position: absolute;
}
</style>
If you write a function that will turn the input values into a string that represents valid YAML text, you can use the Blob API to turn it into a file.
As media type, use the same type as the other YAML files your company uses ( text/yaml, application/yaml, text/vnd.yaml, etc ) since we ( afaik ) do not have a standard type yet for YAML files.
To actually save the file, you'll need to create a url from that Blob the user can click to download. ( See the multitude of other questions about that here on SO or any JS blob-to-url tutorial. )
If you are actually submitting a form to a serverside script, there's probably a bunch of server libraries that can create a YAML file you can return as the response to a form POST request.
I'm a beginner in Js and i checked many times on google devs for the Google + Sign-in.
I got my id etc. What the button does right now, it opens a window of Google but nothing appears in the window and it closes. What i want :
People get connected if the accept the conditions, etc. If not, get back to the index.
If it succeed, i want to get the email of the user in my google email.
Please check out my code :
(JS in head)
<head>
<script type="text/javascript">
function signinCallback(authResult) {
if (authResult['access_token']) {
Successfully authorized;
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatially log in the user
console.log('There was an error: ' + authResult['error']);
}
}
</script>
<script type="text/javascript">
function disconnectUser(access_token) {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' +
access_token;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
},
error: function(e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
//https://plus.google.com/apps
}
});
}
// Could trigger the disconnect on a button click
$('#revokeButton').click(disconnectUser);
</script>
</head>
<body>
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="id" (I got mine, it is not the problem)
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<!-- Place this asynchronous JavaScript just before your </body> tag -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async =
true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</body>
oh i saw i've got a </div> before the </body> maybe it cause problem, i'll try to
put the </div> before the script, then </body>.
This is the url of google devs , Google + Sign-in button for the web :
https://developers.google.com/+/web/signin/
Thanks in advance for help!!
Official Google docs
For future reference, here is the official documentation on the Google Developers site. There is even a Javascript sample on the site.
Javascript example & JSFiddle
Here is a javascript example (and jsfiddle of the same example) shamelessly taken from the Google developer site. (Note that the jsfiddle does work because the clientId needs to be updated)
Place this asynchronous JavaScript just before your </body> tag:
<link href="http://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js?onload=render';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
function render() {
gapi.signin.render('customBtn', {
//'callback': 'signinCallback',
'clientid': '841077041629.apps.googleusercontent.com',
'cookiepolicy': 'single_host_origin',
'requestvisibleactions': 'http://schemas.google.com/AddActivity',
'scope': 'https://www.googleapis.com/auth/plus.login'
});
}
</script>
Here are some styles used for the sample:
<style type="text/css">
#customBtn {
display: inline-block;
background: #dd4b39;
color: white;
width: 165px;
border-radius: 5px;
white-space: nowrap;
}
#customBtn:hover {
background: #e74b37;
cursor: hand;
}
span.label {
font-weight: bold;
}
span.icon {
background: url('/+/images/branding/btn_red_32.png') transparent 5px 50% no-repeat;
display: inline-block;
vertical-align: middle;
width: 35px;
height: 35px;
border-right: #bb3f30 1px solid;
}
span.buttonText {
display: inline-block;
vertical-align: middle;
padding-left: 35px;
padding-right: 35px;
font-size: 14px;
font-weight: bold;
/* Use the Roboto font that is loaded in the <head> */
font-family: 'Roboto',arial,sans-serif;
}
</style>
In the callback, you would hide the gSignInWrapper element on a successful sign in:
<div id="gSignInWrapper">
<span class="label">Sign in with:</span>
<div id="customBtn" class="customGPlusSignIn">
<span class="icon"></span>
<span class="buttonText">Google</span>
</div>
</div>
What's actually happening? OAuth.
The button triggers an OAuth 2.0 sign in flow. It may be helpful for you to understand OAuth 2.x. Here is the Wikipedia article.
UPDATE 10/16
Updated HTML
Updated AJAX
Attached
Issue: The form technically "submits", however a) my form no longer refreshes itself which tells me my php file is not being called/executed properly and b) the info is not being posted to the DB. I think this has to do something with the conten-type: false, but I am not completely sure...
Let me start by saying, I've read and read about how to go about doing this. Some posts I've read this can't be done and then others prove them wrong. I tried to implement some examples, but for some reason all of the examples laid out do not work for me. I thought I'd see if someone can solve my specific issue.
Essentially, I have a semi-html/jquery form that I post via AJAX. I did this because a) I essentially have 3 separate forms (not shown in this example) on the page and b) I need to return the same form to the page without reloading the page...
My problem is that when I select my image and click on my button, the ajax DOES NOT send the image to PHP, although it does send the other fields. What am I doing wrong here? Any updates to my code would be most useful as again, I've attempted to implement several different answers in the past with no luck.
Any assistance would be MUCH MUCH appreciated. I am on the cusp of finishing this project and this is one of two major barriers for me.
html (please forgive the inline styles...I haven't yet finished my CSS files)
<div style="position: relative; float: left; width:275px;">
<div id="valuebox" style="position: relative; float: left; width:275px; border: solid #0096D6; border-width: 1px; padding: 10px;">
<H2>Step 3: Enter Value Level Data</H2>
<form enctype="multipart/form-data">
<span style="position: relative; float: left; display: inline-block; margin-top: 7px; font: 12px Lucida Grande,Helvetica,Arial,Verdana,sans-serif; padding-right: 60px;">
<p>Add Value Challenger Screenshot:</p>
<input id="file" type="file" name="valueimage">
</span>
<span style="float: left; clear: right; margin-top:8px; padding-top: 10px; width: 235px;">
<label class="fieldlabel"><span>Value Lift (%):</span></label></br>
<input id="valuelift" type="text" name="valuelift" class="textfieldshadowsmall" style="width: 150px;">
</span>
<span style="position: relative; float: left; margin-top: 25px; font: 12px Lucida Grande,Helvetica,Arial,Verdana,sans-serif;">
<input id="valuesignificant" type="checkbox" name="valuesignificant" value="1">Significant?
</span>
<span style="position: relative; float: left; margin-top: 25px; font: 12px Lucida Grande,Helvetica,Arial,Verdana,sans-serif;">
<input id="valuewinningcreative" type="checkbox" name="valuewinningcreative" value="1">Winning Creative?
</span>
</form>
</div>
<span style="position: relative; float: left; margin-top: 25px; font: 12px Lucida Grande,Helvetica,Arial,Verdana,sans-serif;">
<a href="#" id="valuesubmit" />+ add another value</a>
</span>
</form>
</div>
jquery/ajax
$(function(){
$('#valuesubmit').click(function(event) {
var formData = new FormData($('form')[0]);
$.ajax({
url: 'post_value_dummy.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
//if(myXhr.upload){ // Check if upload property exists
// myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
//}
return myXhr;
},
// Form data
enctype: 'multipart/form-data',
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
});
php
//This is the directory where images will be saved
$target = "/screenshots/";
$target = $target . basename($_FILES[valueimage][name]);
$picchallengervalue=($_FILES['valueimage']['name']);
$con=mysqli_connect("x","y","z","a");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO value (valueimage, valuelift, valuesignificant, valuewinningcreative, variableid)
VALUES
('$picchallengervalue','$_POST[valuelift]','$_POST[valuesignificant]','$_POST[valuewinningcreative]','$_POST[variableid]')";
//some php that sends the same form back to the browser - code not necessary to show
if(move_uploaded_file($_POST[valueimage][tmp_name], $target))
{
echo "ok";
}
Try this
$(function(){
$('#valuesubmit').click(function(event) {
var formData = new FormData($('form')[0]); // okay I just saw the form, assuming there is only one form on the page
$.ajax({
url: 'post_value_dummy.php', //Server script to process data
type: 'POST',
/* This is just looks like bloat
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
//if(myXhr.upload){ // Check if upload property exists
// myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
//}
return myXhr;
},*/
// Form data
// enctype: 'multipart/form-data', <-- don't do this
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
//cache: false, post requests aren't cached
contentType: false,
processData: false
});
});
});
I am making a forum that does not require page refreshing. It is coming along swimmingly, except for the fact that on a failed login attempt, the page reloads.
I've done all the googling, and found that my jQuery "return false" on the .submit event should prevent the reload, but it doesn't! Here is the code:
HTML:
<div id='sidebar'>
<p>Login</p>
<form id='login'>
<input class='logininfotext' type='text' id='login_username' placeholder='username'/>
</br>
<input class='logininfotext' type='password' id='login_password' placeholder='password'/>
</br>
<input name='loginbutton' type='submit' value='login'/>
</form>
</div>
CSS:
#sidebar {
font-size: 12px;
position: fixed;
color: white;
top: 227px;
left: 90%;
width: 9.5%;
background-color: rgba(12,35,44,0.6);
border: 2px solid #3D89A4;
font-family: Minecraft;
}
.logininfotext {
width: 100px;
}
.error {
padding: 6px;
border: 1px solid rgba(123, 29, 29, 0.7);
border-radius: 4px;
background-color: rgba(245, 83, 83, 0.5);
font-size: 10px;
color: #916E6E;
}
Javascript/JQuery:
//saves all userdata of current session to the user object.
function saveuserdata() {
var session_user_data = JSON.parse(get_data("#sidebar", "php/sqlquery.php", "session_user_data"));
user.username=session_user_data[0];
user.password=session_user_data[1];
var session_user_data2=JSON.parse(get_data("#sidebar", 'php/sqlquery.php', 'Userdata', user.username));
user.picture=session_user_data2[0]['Picture'];
user.posts=session_user_data2[0]['Posts'];
//reprints the login form, supposedly adding whatever html to the end I want for error support
function loginform(extrastring) {
var loginform = "<p>Login</p><form id='login'><input class='logininfotext' type='text' id='login_username' placeholder='username'/></br>";
loginform += "<input class='logininfotext' type='password' id='login_password' placeholder='password'/></br><input id='loginbutton' type='submit' value='login'></form>";
if (typeof(extrastring)=='string') {
loginform += extrastring;
}
$("#sidebar").html(loginform);
}
$('#sidebar').submit(function() {
var test=true //normally, this would be a call to php to check if the user logged in successfully or not. I know my php is working, but my problem is I don't want the page reloading
user.username=$('#login_username').val();
user.password=$('#login_password').val();
if (test=true) {
saveuserdata();
$("#sidebar").html("<p class='username'>"+user.username+"</p><img width='125px' height='125px' src='"+user.picture+"'/><p>Posts: "+user.posts+"</td><div id='logout'>logout</div>");
} else {
loginform("<p class='error'>Username or Password incorrect!</p>");
}
return false;
});
Help is much appreciated. I realize it is hard to figure out just what is happening here. If you want to see the full thing, be my guest: http://lampitosgames.com/forum/index.php
Try preventDefault instead
$('#sidebar').submit(function(e) {
e.preventDefault();
var test=true //normally, this would be a call to php to check if the user logged in successfully or not. I know my php is working, but my problem is I don't want the page reloading
user.username=$('#login_username').val();
user.password=$('#login_password').val();
if (test=true) {
saveuserdata();
$("#sidebar").html("<p class='username'>"+user.username+"</p><img width='125px' height='125px' src='"+user.picture+"'/><p>Posts: "+user.posts+"</td><div id='logout'>logout</div>");
} else {
loginform("<p class='error'>Username or Password incorrect!</p>");
}
});
The question might not be clear, so i will explain further.
I saw some page like wordpress new post tag, they have something like
[input]
x tag | x tag | x tag
or Facebook Notes when you post a image...
the when you input a tag and press enter, a new tag is insert in to element in the page...
I don't quite understand how can you parse that out and then submit to the form.
if anyone know please give me an idea.
Thanks
If I am getting it right, you are talking about sending AJAX-based post requests "under the hood" and get "dynamic reflections" back on the same page.
Well, if this is the case, there are actually more than just submitting data to the server.
Here is the big picture:
You need a javascript which is loaded in the page that has the form to submit.
Inside that script, you need to define the event which will trigger the AJAX-based post request. Basically you would love trigger such an event when the content in that particular field has been just changed (an onChange event, that is).
Then you can use script like the following:
$.ajax
({
type: 'POST',
cache: false,
async: false,
timeout: 10000,
url : '/path/to/your/serverside/function',
dataType : 'json',
data:
{
'tag' : //whatever you want to be used as the tag
},
success : function(message)
{
//this will be called when this post was successfully been carried out.
//you should update the view (the same page) here using some jQuery script.
//such as : $('#tag').html(message.tag);
},
error : function(message)
{
//this is for displaying error messages (perhaps due to networking problems?)
}
});
Since there are really a lot to write about. I suggest you post whatever you have finished up here so we can give it a check.
At least from my consideration, this scenario require the following knowledge to get everything right(though you can always choose to use less tech):
onChange event triggered
|
|
jQuery =====sending JSON formatted tag info ======> serverside function
|
|
decode JSON tag info
|
|
process(saving it into database?)
|
|
encode feedback info
|
jQuery callback function <===== JSON info==================
|
|
update the view(the same page)
.
.
.
.
.
aforementioned process is before form is submitted via normal POST/GET.
One way is to keep track of the tags you add in a hidden form field, but actually display using divs or spans or whatever UI you want. In the case of facebook, I'd imagine they're doing something somewhat similar, though I guess they could actually be adding form elements dynamically. Forgive the nasty code/css - just tossed it together. If you add tags and then hit submit, you'll see the querystring that all the values are there.
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btnSuggest").click(function(){
var $tagSuggest = $("#tagSuggest");
if($tagSuggest.val() != "")
AddTag($tagSuggest.val());
});
$("#tagSuggest").keyup(function(e){
if(e.keyCode == 13 && $(this).val() != "")
AddTag($(this).val());
});
});
function AddTag(tag){
$("<div>").text(tag).appendTo("#tags").click(function(){
$(this).remove();
UpdateTags();
}).hover(function(){
$(this).addClass("over");
},function(){
$(this).removeClass("over");
});
UpdateTags();
}
function UpdateTags(){
var allTags = "";
$("#tags div").each(function(){
allTags += "," + $(this).text();
});
$("#hidTags").val(allTags.substring(1));
$("#tagSuggest").val("");
}
</script>
<style type="text/css">
.main
{
width: 400px;
padding: 10px;
margin: auto;
border: 1px solid black;
background-color: #e6e6e6;
height: 600px;
}
#tags div
{
padding: 3px;
border: 1px solid black;
background-color: #e6e6e6;
margin: 3px;
height: 15px;
width: auto;
float: left;
cursor: pointer;
}
#tags div.over
{
background-color: red;
}
</style>
</head>
<body>
<div class="main">
<form action="" method="get">
<input type="hidden" name="hidTags" id="hidTags">
<textarea name="Wallpost" style="width: 390px; height: 100px;"></textarea>
<br />
<input type="text" id="tagSuggest" style="width: 280px;" />
<input type="button" id="btnSuggest" value="Add Tag" style="float: right;"/>
<br />
<input type="Submit" name="cmdSubmit" value="Share" style="float: right;"/>
</form>
<div id="tags">
</div>
</div>
</body>
</html>