Call AJAX to send value with button - javascript

I read a lot of similar questions, and I tried all solutions but nothing seems to work. I want to send an AJAX request by clicking a button and send what the user typed in a textarea and display it in a div(chatbox). When I click the button, nothing happens. It never calls the function that has the AJAX code. Do you have any ideas what is going on?
P.S. I included the JavaScript files but nothing's changed.
<form action="ajax()">
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
//AJAX function
function ajax() {
alert("insert");
var txtArea = $("#txtArea").val();
$.ajax({
type: "POST",
url: "InsertMessage.php",
data: {
txtArea: txtArea
}
success: function(data) {
alert(data);
$("#chatbox").load("DisplayMessages.php")
$("#txtArea").val(""); //Insert chat log into the #chatbox div
}
error: function() {
alert('there was an error, write your error handling code here.');
}
});
}
$(document).ready(startAjax);
//setInterval(function(){
// $("#chatbox").load("DisplayMessages.php");
//}//,1400);
</script>

Your question is not so clear, But for sending data in post method when submiting a form and then show result in a div, try something like this:
html:
<form>
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit">
</form>
<div id="resultDiv">
</div>
js:
$( "form" ).submit(function( event ) {
var txtArea = $("#txtArea").val();
$.ajax({
type:"POST",
url:"InsertMessage.php",
data:{txtArea:txtArea}
success: function(data){
alert(data);
$("#resultDiv").html(data);
}
error: function(){
alert('there was an error, write your error handling code here.');
}
});
});

The action attribute has to contain a URL, not Javascript. You can use:
<form action="javascript:ajax()">
or:
<form onsubmit="ajax(); return false;">
or you can bind the event in jQUery:
$(document).ready(function() {
$("form").submit(function() {
ajax();
return false;
});
});

Related

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

Classic ASP + Ajax Form - success function not working, complete is ok

With Ajax and JS/Jquery I'm trying to send a simple Contact form to a Classic ASP (aspemail) and sent a messagem from a page without reload.
<form id="form-submit" action="ASPEmail.asp" method="post">
Name<br>
<input id="name" type="text"><br>
E-mail<br>
<input id="email" type="text"><br>
Message:<br>
<textarea id="msg"></textarea><br>
<input type="submit" id="btn" value="SEND">
<img src="loading.gif" class="loading">
</form>
My ASPEMAIL.ASP is only test asp and I write only:
<%
Response.Write("ok")
%>
And my JQuery Script:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(function() {
$("#form-submit").submit(function() {
var data = $(this).serialize(),
action = $(this).attr("action"),
method = $(this).attr("method");
$(".loading").show(); // show loading div
$.ajax({
url: action,
type: method,
data: data,
success: function(data) {
if(data === "ok")
{
document.location = "final.asp";
}
},
error: function(err) {
// there was something not right...
},
complete: function() {
$(".loading").hide(); // hide the loading
}
});
return false; // don't let the form be submitted
});
});
</script>
I put a redirect on success to test (My objective is a message only) - but nothing happens.
But after send the "LOADING" appears on screen and hide and then the submit and "complete" is working.
Any idea what is wrong?
you have 2 variables named data, try using a different variable here, as I believe you're "confusing" javascript here :)
success: function(dataReturned) {
if(dataReturned === "ok")
{
document.location = "final.asp";
}
},

PHP and Ajax posting

I'm using jQuery form plugin to send ajax requests. Which you can find on below url
http://malsup.com/jquery/form/
This is my jQuery code
$(document).ready(function()
{
$('#SubmitForm').on('submit', function(e)
{
e.preventDefault();
$('#submitButton').attr('disabled', '');
$(this).ajaxSubmit({
target: '#output',
success: afterSuccess //call function after success
});
});
});
function afterSuccess()
{
$('#submitButton').removeAttr('disabled'); //enable submit button
}
This code is displaying out put on the div id output and each time i submitted code will remove the old out put and display the new one. What i want to do is, keep the old out and display the new out put on top of the old output. Can someone tell me how to do this.
What you could do, is alter your afterSuccess method a little bit. What I did was:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
The whole fiddle is available here
The whole code of javascript:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
$(document).ready(function()
{
$('#submitButton').click(function(e)
{
$('#submitButton').prop('disabled', true);
$('#SubmitForm').ajaxSubmit({
data: {
html: "<p>Text echoed back to request</p>",
delay: 1
},
success: afterSuccess,
url: '/echo/html/'
});
});
});
and of course assuming following html structure
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<body>
<form id="SubmitForm" method="POST">
<input type="button" id="submitButton" value="submit"/>
</form>
<div id="output">
test
</div>
</body>

jQuery.post() has a side-effect of changing my URL parameters

I have a page with multiple forms. When the users fill in one of the forms, I want to send it to a server. However, I need the browser to keep displaying the original page, so that the users can submit other forms, if they wish to. Hence I cannot use the "action" attribute in the form and a "submit" type of button.
After consulting the jQuery.post docs, I arrived to the following solution:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button" onclick="submitForm();"> Submit </button>
</form>
<script>
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
</script>
</body>
</html>
The above code does what I want it to do, but it has a very peculiar and disruptive side-effect of modifying my URL to include the parameters I'm posting.
So when I fill in my name and email, I'm "redirected" to myself, but with the name and email parameters appearing in the URL:
http://localhost:8080/Prototype/TestPost.html?name=Lev&email=Storytime%40gmail.com
Now, I definitely do not want "name=Lev&email=Storytime%40gmail.com" to be a part of my URL. These parameters are also not intended for TestPost.html but rather to SaveForm.jsp, so it's all very wrong.
I also want to mention that SaveForm.jsp works as expected. It receives the parameters, saves them to the database and returns a success response.
What am I missing?
Thanks.
EDIT
Thanks, everybody. I could not avoid the refresh using the "return false" statement, so I had to use jQuery's "on click" option. I also don't understand how using ajax explicitly would make any difference, since jQuery's documentation seems to say that the post is just a syntactic sugar for Ajax.
The complete code which worked for me was:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
If you don't especify the method attribute on the form it will be GET by default, that's why you get the URL params. Also, because you aren't not stopping the default action, your form is being submitted (the reloading effect), so I recommend you the following code to help you:
<script>
$(function() { //executes js code after html has been loaded
$("#button").on("click", function(e) {
e.preventDefault(); //avoids to reload the page
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
});
</script>
And remove the onclick at the button to have a cleaner HTML:
<button id="button"> Submit </button>
If you do not want to use jQuery's on click and still stick to the submit function you can just add return false; in the end to prevent the form from submitting.
Like below
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
});
.fail(function() {
alert("Error submitting the form.");
})
return false;
}
Hope this helps.
I guess, you are not submitting the form by ajax.
Add return false;, to that it does not redirect and submit via ajax.
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData, function() {})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
return false;
}

AJax not calling php file correctly, html forms

UPDATE:
This is the error:
412 (Precondition Failed)
I am trying to call a php script from ajax, I currently have the below ajax, which when the button in the form (also below) is clicked will call a php script passing it the form data, which will then be submitted to the database.
However, it is not working; and what's more I am just getting a blank error back, so I do not even know what is going wrong.
Could someon please point me in the right direction?
Thanks.
HTML form:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<!--<input id="report-submit" value="" name="submit" type="submit" onclick="submitReport()"/> -->
<button id="report-submit" name="submit" onclick="submitReport()"></button>
</form>
AJax call:
function submitReport()
{
var ID=$('#reportedID').val();
var reason=$('#reason-box').val();
var formData = "ID="+ID+"&reason="+reason;
alert(formData);
//This code will run when the user submits a report.
$.ajax(
{
url: 'submit_report.php',
type: "POST",
data: formData,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
}
Now I have already tested the php script, and that works fine, the problem started when I added the ajax call so I know it is something to do with the ajax not the php.
This should correct the problem with submitting:
Your jQuery Ajax call won't succeed because the POST data isn't supplied in the correct format.
If the ajax should succeed the form is also posted resulting in a 405 error.
<button id="report-submit" name="submit" onclick="submitReport(event)"></button>
function submitReport(event)
{
event.preventDefault();
....... // your code
}
Now the default action of your form will be prevented (resulting in a 405 error). And only the ajax request is submitted.
In the button element we pass the event object on to the function. We use event.preventDefault() to make sure the button doesn't run it's default action, which is submitting the form.
You could also prevent this by deleting the form element as a wrapper, but maybe you want to use other features (like validation) on the form.
Form data in a jQuery ajax request needs to be an object called data:
var formData = {"ID" : ID, "reason" : reason};
jQuery will reform this to a correct query string for the submit.
I would do it like this:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160"></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" type="submit" name="submit" value="submit"></button>
</form>
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
url: "submit_report.php",
data: data,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
return false;
});
});
</script>
and then use $reason=$_POST['reason-box']; and $ID=$_POST['reportedID']; inside your PHP script
this is optional to choose the form for submitting data or you can do it without the HTML form this is what i do
<textarea id="reasonbox" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" ></button>
and the using folloing javascript and jquery style
<script type="text/javascript">
$(function() {
$("#report-submit").click(function(){
try
{
$.post("your php page address goes here like /mypage.php",
{
//in this area you put the data that is going to server like line below
'reasonbox':$("#reason-box").val().trim(),
'reportedID':$("#reportedID").val().trim()
}, function(data){
data=data.trim();
//this is data is sent back from server you can send back data that you want
//like message or json array
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I hope it helps

Categories