ajax request on javascript not working - javascript

Here I create a form with iframe.
I want to save those data name and category using an ajax request.
Here's a google spreadsheet where I want to save those data https://docs.google.com/spreadsheets/d/1WXzTVsIAKsGvXgm4ivRzTPN2P8kupJDcnH5sHdc0Vhw/edit?usp=sharing
I'm using bookmarklet so this is a script of it.
when I do this nothing is done. No error and no console log? I don't get it? Please help me I'm new on this.
My code looks like this , this file is called script.js :
(function(){
var f = '<form action="" method="post"> Name: <input type="text" id="name" name="name">Category <select name="category" id="category"><option value="first">First</option><option value="second">Second</option><option value="third">Third</option></select><br><input type="submit"></form>';
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(f);
iframe.contentWindow.document.close();
$("#submit").click(function(){
var name = $('#name').val();
var category = $('#category').val();
console.log("po ajax" , name , category);
$.ajax({
url: "https://docs.google.com/spreadsheets/d/1WXzTVsIAKsGvXgm4ivRzTPN2P8kupJDcnH5sHdc0Vhw/edit?usp=sharing",
data: { "name": name,"category": category},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
// window.location.replace("ThankYou.html");
console.log("error");
},
200: function () {
// window.location.replace("ThankYou.html");
console.log("ok");
}
}
});
});
})()
EDIT:
here is my index.html page where I defined my bookmarklet:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<p> Bookmarklet</p>
</body>
</html>

You cannot bind event to element that is in iframe from parent page.
As you are adding your form in iframe, the javascript function for binding click event to submit button should be also in iframe.
And because you are using jquery, the Jquery reference should be also exists in iframe.

You are not making an ajax call, because your form is submitted the default way and therefore reloads the page before your js function. You need to prevent the form submission by changing $("#submit").click(function(){ to $("#submit").click(function(e){ e.preventDefault(); ...//continue with current code

$("#submit") wants an id to bind to so I suggest you rewrite <input type="submit"> to <input id="submit" type="submit">

Hmm. There are a whole lot of issues here.
the javascript code is separate from the iframe content. (This is the Sangram Parmar answer.)
I'd recommend getting rid of the iframe in test, and just add the <form> code block as raw html.
The jquery #submit identifier doesn't fit the situation. Personally, I'd add a <form id="form_id" ... term and then call it via $(#form_id)..click(function(e){... Oh, wait. This is the concern raised by P-A.
Good catch by Velimir Tchatchevsky on the prevent default behavior (but I do see action="" in the original code. I do think the prevent default behavior is a good practice.
Next we will start getting Cross-Origin Request (CORS) errors depending on which browser the user is using.
You can fix that by using jsonp instead of xml as the data type, but when you do that the error you will see is: Refused to execute script from 'https://docs.google.com/spreadsheets/d/1NTlfje4H-K3KyvBvUDqIA0z7pz_VQpijJV5…ery22304475027782793899_1462276071176&name=&category=first&_=1462276071177' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Sigh. Not sure what that is, yet...
Aha... I think this link will prove helpful. Look at the response by 'dev' and the links he has provided.

Related

Javascript POSTing HTML form

I need to post some data to a webservice using a single button click.
I don't want to show the reply received from the server, which a simple HTML form does. So I came up with the following code:
<!DOCTYPE html>
<html>
<head>
<script>
function sendData() {
var form = document.createElement('form');
form.action = "https://posttestserver.com/post.php";
form.method = 'POST';
var input = document.createElement('input');
input.type = 'hidden';
input.name = "args";
input.value = "on";
form.appendChild(input);
form.submit();
alert("Submited!");
}
</script>
</head>
<body>
<button onclick="sendData();">Click Me!</button>
</body>
</html>
Please enlighten me what exactly is going wrong, because its not posting any data.
Any reason you have to use JavaScript to create the form? Is it simply not posting the input or is the form failing to submit? You can always use your Web Inspect tool to see the request.
Try opening your web inspector and look at the console for any JavaScript errors.
your posted data found at
http://www.posttestserver.com/data/2015/12/16/21.17.23451563624
plz, see the image.
you can use ajax to post data instead of form submit.
params = {
'input':'on'
}
$.ajax(url,post,params,succ,err)
Solutions as per my understanding :
If you are placing script in head tag, refer 'Where should I put <script> tags in HTML markup?'. The conclusion is to put scripts in the head tag and use the async or defer attributes.
Append form to your body before submitting the form.
document.body.appendChild(form);
Place script before body tag.
Not sure why you want to create a form using JS just to post some data to server when you could have used ajax. As already mentioned in previous answers you can use jQuery. If you are reluctant to use jQuery, you could have used XML HTTP Request (XHR) object
A simple solution using jQuery would be
$.ajax({
type: 'POST',
url: 'https://posttestserver.com/post.php',
data: {'args': 'on'}
});
Since you want the data to send on clicking a button, you could trigger the event on button click
$('button').on('click', function() {
$.ajax({
type: 'POST',
url: 'https://posttestserver.com/post.php',
data: {'args': 'on'}
});
});
My main aim was
I don't want to show the reply received from the server
So I added an IFRAME in the page and then added it as the form's target
<form action="MYLINK" method="POST" target="hidden-form">
...
</form>
<IFRAME style="display:none" name="hidden-form"></IFRAME>
Now the reply from server is not visible

Form submition using AJAX is not working

Im tring to submit form to other page using ajax, but it doesn't send the post.
Javascript on top of page.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function(){
$(".button").click(function(){
event.preventDefault();
var name = $("#name").val();
var dataVar = "name=" + name;
$.ajax({
type: "POST",
url: "https://www.example.ee/index.php?e=area_sa&date=2010",
data: dataVar,
success: function() {
alert("works");
}
});
});
});
<script>
And HTML code:
<form>
<input type="text" name="name" id="name">
<input type="submit" name="submit" class="button" value="Add">
</form>
It's not working because you're trying to make a cross-domain AJAX request.
If you have a domain mywebsite.com, then all AJAX requests should be limited to this domain, e.g. mywebsite.com/example/ajax/request.
What you're trying to do (cross-domain request) is possible but involves a workaround that's a bit more complicated, and makes use of different library calls.
It seem that your click event is not bind to the .button,
That happen when the event is bind before the html element is loaded
few solutions :
1) encapsulate your JavaScript code inside an on-load event
2) place your JavaScript at the bottom of the page
3) use $(body).on('click', '.button' , function(){ /* your code here */})
also look like you posting to an external domain,
if you are the owner make sure you add the CORS policies.

jquery get method doesn't do anything, but doing it as a form does (java servlet)

I have a file called index.jsp which is where a user is directed to upon loading my website.
I want to send a get request to one of my servlets upon loading the page.
So my URL at the beginning is:
localhost:8080/Test/
The servlet will do something when the URL is:
localhost:8080/Test/MyServlet?action=fetchdata
I can get the servlet to perform fetchdata if in the html body i put this:
<form name="fetchdata" action="MyServlet" method="get">
<input type='hidden' name='action' value='fetchdata' />
</form>
and then run a script:
<script type="text/javascript">
document.fetchdata.submit();
var testresult = '${result}';
document.write(testresult);
</script>
However this does not look nice and it is also in the HTML body which seems very unprofessional. So I tried implementing the same function in JQuery by putting this in
the HTML head:
window.onload = function() {
$.get("MyServlet", { action : "fetchdata"});
};
and nothing happens when I load the page. I have tested to see that jQuery is working. Any idea on what is wrong? Thanks
Try this instead:
$("form[name='fetchdata']").trigger('submit');

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

jQuery - reset form after submit w/ form plugin

let me start by saying it may look simple but im finding it extremely difficult.
ive made a search script that uses PHP and to fetch a result would look like this
search.php?term=alice&submit=Submit
Standard stuff.. problem is, i use an SPI with AJAX and PHP so my results would have to load dynamically into a div, whilst still keeping the hash value, as not to lose the page the user had visited previous to searching.
jQuery.history.js is the plugin i use for back button support, which requires links to be like such:
Home Page
this would load 'home.html' into a div named pageContent. as far as i know theres no way to call php files unless you develop a little hack, which i have,
here is my JavaScript/jQuery for my search form:
<script language="JavaScript">
$(document).ready(function() {
// bind form using ajaxForm
$('#search1').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#pageContent',
// success identifies the function to invoke when the server response
success: function() {
$('#pageContent');
var hash = '#search.php?term='+($('#query').val()+'&submit=Submit').replace(/ /g, '+');
var stripped = hash.replace(/(<([^>]+)>)/ig,"");
update(window.location.hash = stripped);
}
});
});
</script>
Heres the form:
<form id="search1" action="search.php" method="post">
<input id="query" type="text" name="term" />
<input type="submit" name="submit" value="Submit" />
</form>
My problem is this:
ive tried this.form.reset(); this: Resetting a multi-stage form with jQuery , yet none of this works. please help me if you know a way of doing this..
$('#query').val(DefaultValue);
with this u can set your value to whatever you want, like blank: '';

Categories

Resources