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.
Related
I don't know if it is possible or not. I referred some site, but I didn't get exact answer.
I am using
click
When I send this request to server in the response page easily I can see "id=4" in address bar, obviously which is not secure, But in post request we cant see this.
So can we convert a get request to post or ant other way is there to hide this from address bar.
Thanks in advance.
Firstly, to convert GET to POST, simply change the link to a form:
<form id="myForm" action="xyz" method="post">
<input type"hidden" name="id" value="4"/>
</form>
This form will not be visible and you can easily auto-submit it using JavaScript in your link:
click
Secondly and more importantly, both GET and POST are equally not secure over HTTP. To secure them, use HTTPS and they will be both equally secure, so no need to change if GET is working for you.
click
Dynamically create a from and post it.
function postForm() {
var form = $('<form method="POST" action="xyz"></form>');
$(document.body).append(form);
form.append('<input type="hidden" name="id" value="4"/>');
form.submit();
}
As Racil suggested in comments, you can also do the following
click
and then
$('#postLink').click(function(e){
e.preventDefault();
//create form and post
});
Call a java script function on onclick which will make the form submission using post method or you can use ajax call to post the data and get your desired results.Use id as a parameter in function.
<a href="#" onclick="postData(4)">
/// Javascript function for ajax call
function postData(id){
var param = { "Id": id};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "xyz.aspx",
data: JSON.stringify(param),
success: function (data) {
/// Recive data here or do your stuff here
}
}
Make a form having single input type hidden and onclick set value of that input type hidden element and submit form using jquery.
<form id="target" action="destination.html">
<input type="hidden" id="hiddenValue">
</form>
/// Javascript function for setting value of hidden element and form submission using jquery
function postData(id){
$("#hiddenValue").val(id);
$("#target").submit();
}
Hopefully this will solve your problem.
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.
I need refresh <myDiv> on my webpage when the Submit button is clicked.
I created an example of what I need. I want to display the user input text inside <myDiv> when the Submit button is clicked. Currently it's not showing anything. How can I fix this?
http://jsfiddle.net/NathaliaZeed/8dn5j/2/
Thanks everybody.
You need to use complete: not done:, then, assign your val1 variable to myDiv.
Working fiddle: http://jsfiddle.net/8dn5j/14/
See below:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
e.preventDefault();
$.ajax({
type: 'post',
data: {'val1':val1},
complete: function(jqXHR, textStatus){
$("#myDiv").html(val1);
}
});
});
The code in your example is good, except you forget to load the jQuery library.
If you make sure you include jQuery, the javascript code should work.
Also, your example should run on a PHP server. JSfiddle does not interpret PHP code, so that is also why the example does not work.
If you don't have a PHP server, Google for WAMP for Windows or MAMP for Mac.
Not Sure why you need php and ajax if there is only need to update the div on button click and not doing any server side processing for the need you described in question this code will work
<div class="myDiv" id="myDiv"></div>
<div class="sear">
<form action="" method="post">
Search Word: <br />
<input type="text" name="val1" id="val1" /><br />
<input type="button" value="Submit" id="btn" />
</form>
</div>
Js
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$("#myDiv").html(val1);
$("#myDiv").toggle("slow");
});
By the way, you don't need to use the form-tag..
I would do it this way:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$.ajax({
type: 'post',
data: {val1:val1},
success: function(data) {
$("#myDiv").text(data);
}
});
});
For me it doesn't do anything with Ajax request.
$('#btn').click(function(e) { e.preventDefault();
$("#myDiv").html($('#val1').val());
//..ajax stuff..
});
In my jquery mobile web app I include a Login-Form on every page the user is navigating to. I do that so that the user could login at every time he wants to, not just on the start page.
Since I do the Form submitting procedure with my very own Ajax logic, I disabled the Jquery Mobile Ajax logic with data-ajax="false" on the Form. The Ajax logic is implemented with JavsScript. On the start page everything works fine, but if I navigate to another page (through a link on the start page), my JavaScript is not firing anymore, but the form is submitted via the Jquery mobile own Ajax logic (and therefore it don't works).
The code (which I include at every page) looks like this:
<div data-role="fieldcontain">
<form id="loginForm" data-ajax="false" onsubmit="login();return false;">
<div data-role="fieldcontain">
<h2>Login</h2>
<label for="textinput1">
Email
</label>
<input name="emaillogin" id="textinput1" placeholder="Email" value=""
type="text">
<label for="textinput2">
Password
</label>
<input name="passwordlogin" id="textinput2" placeholder="Password" value=""
type="password">
</div>
<input type="submit" data-icon="ok" data-iconpos="left" value="OK">
<input type="hidden" name="inputCase" value="login">
</form>
</div>
The JavaScript (which is just at the end of the Code stated above) looks like that:
<script>
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
Maybe I got the Jquery Mobile "we replace just the page-div with the other page-div from the new URL" thing wrong, but I understand it in that way that my whole JS logic will also be pulled from the new ressource.
EDIT Thanks. I have updated my JS code, which looks now like that:
<script>
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
login();
});
});
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
BUT. Now when I navigate to 3 pages, and then submit the login Form, I will get 3 alerts (even when I navigate to just 1 site) of the request.fail function... after that the login goes correctly!
Ajax is still your problem. You have disabled ajax form submition but ajax is still used to load additional pages. This is just my assumption because you didn't mentioned that ajax is turned off all together.
If ajax is still used to load pages all your other pages are loaded into the DOM. Because of this you will have multiple forms with a same ID. When your first page is loaded there's only 1 form in a DOM and that form is used. But when another pages is loaded then additional form (with a same id) is added to the DOM. And whey you click a submit button jQuery will find first form with that ID from the DOM. And because there are 2 of them it will submit first for, same form loaded with an initial page.
That is why you NEVER use inline javascript with jQuery Mobile.
Instead of
onclick="..."
Your submit button should have an id and make it type="button".
<input type="button" data-icon="ok" data-iconpos="left" value="OK" id="submit-btn">
Put a click event on every button and use a $.mobile.activePage selector to find a form on an currently active page.
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
Also everything should be wrapped inside a correct jQuery Mobile page event:
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
});
I'm currently using Prototype, but I'd like to rewrite this function to jQuery:
function post(div,url,formId) {
new Ajax.Updater(div, url, {
asynchronous:true,
parameters:Form.serialize(formId)
});
}
HTML example that goes with it:
<form method="post" action="" id="foo"
onsubmit="post('result','getdata.php','foo');return false;">
<input type="text" name="data" />
</form>
<div id="result"></div>
I've been looking at jQuery.load() and jQuery.post(), but I'm not sure which one to use and how exactly.
Thanks in advance for your help.
With this HTML:
<form method="post" action="getdata.php" id="foo">
<input type="text" name="data" />
</form>
<div id="result"></div>
You can do this with jQuery:
$(function() { // wait for the DOM to be ready
$('#foo').submit(function() { // bind function to submit event of form
$.ajax({
type: $(this).attr('method'), // get type of request from 'method'
url: $(this).attr('action'), // get url of request from 'action'
data: $(this).serialize(), // serialize the form's data
success: function(responseText) {
// if everything goes well, update the div with the response
$('#result').html(responseText);
}
});
return false; // important: prevent the form from submitting
});
});
The reason I got rid of the onsubmit code is because it is considered bad practice to have inline JavaScript like that. You should strive to make your forms free of JavaScript and then bind all the JavaScript away from it. This is known as unobtrusive JavaScript and it is a Good Thing.
EDIT:
Since you have that code in many pages, this is a function that will do what you want using the same signature you currently have on the post function. I recommend you take a few hours to update all your forms over keeping this, but here it is anyways:
function post(div,url,formId) {
$.post(url, $('#' + formId).serialize(), function(d) {
$('#' + div).html(d);
});
}
As far as your problem, the livequery plugin could help you there. Alternatively, it is as simple as encapsulating the binding code in a function and calling it whenever a form is added.
Use this and get rid of the onsubmit attribute in your HTML:
$(document).ready(function() {
$("#foo").submit(function() {
$.post($(this).attr("action"), $(this).serialize());
return false; // prevent actual browser submit
});
});
jQuery serialize method docs
You can't send "multipart/form-data" forms with jquery because of security problems. You must do it with flash or iframe...