Stop Page redirection on Form Submit - javascript

I've looked up a lot of tutorials and poked around on here but haven't found anything that addresses my specific issue. I am guessing I have a syntax error or logic error somewhere in my code. My issue is that whenever I submit the form, I get directed to the test.php page. The php is working correctly as it is returning the correct result but I just want that to run and display the submitted form information underneath. Any help would be greatly appreciated.
index.html
<html>
<head>
<title>Computer swap form</title>
</head>
<body>
<form method = "post" action = "test.php" id="computerForm">
Serial Number: <br>
<input name="serialnumber" type="text">
<button id = "sub"> Submit </button>
</form>
<!--display the response returned after form submit -->
<span id ="result"></span>
<script type="text/javascript" src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>
test.php
<?php
$sn = $_POST['serialnumber'];
if(!isset($sn))
{
echo "error serial number not set";
}
else {
echo "$sn successfully saved";
}
?>
my_script.js
$("#sub").click( function() {
$.post( $("#computerForm").attr("action"),
$("#computerForm").serialize(),
function(info){ $("#result").html(info);
});
});
$("#computerForm").submit( function() {
return false;
});

To achieve what you require put all your logic in the submit handler, and call preventDefault() on the event argument provided to the handler function:
$("#computerForm").submit(function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(info) {
$("#result").html(info);
});
});

Related

Ajax using GET to PHP

I have seen many posts close to this but not this specifically so I will still ask it. I have a simple webpage that I am using to pass a value from to a server and then based on the value pass a response to the original webpage. Right now for testing purposes I am just using an alert for the final value.
My client side code is as follows submitAjax.php:
<!DOCTYPE html>
<html>
<head>
<script src="./jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#thisForm").submit(function () {
processData();
});
function processData() {
$.get('ajaxSubmit.php', function(data) {
alert(data);
});
}
});
</script>
</head>
<body>
<form method="get" id="thisForm">
<tr>
<td><input type=text name=box ></td>
<td><input type=submit value=Add></td>
</tr>
</form>
</body>
</html>
Server side ajaxSubmit.php:
<?php
$value=$_GET["box"];
if ($value==2){
echo "This is the returned text.".$value;
}else{
echo "not sent";
}
?>
As you can see from the code, I am trying to print the text "This is the returned text.2" as the output but when I enter "2" into the textbox my failure case of "not sent" is returned.
Any help would be great. I am very very new to all things javascript so please point out anything else I am doing incorrectly as well.
You're not passing anything when you're requesting ajaxSubmit.php.
$.get('ajaxSubmit.php?box=' + $("[name='box']").val(), function(data) {
alert(data);
});
So you want to request, ajaxSubmit.php?box=value, where value is the value of the html element named box.

JavaScript/Ajax - How to run one PHP script before posting form to another one

I am almost at my wit's end trying to figure out why my code is not working.
Here is what I am trying to do:
1) Accept several variables in a form (myform).
2) Using an onsubmit, I want to use pass one or more of those variables to a script (process_info).
3) After process_info has executed, the form should be posted to the form's action URL ('save_info.php').
As you can see in the code below, I have tried several things:
Test 1: This simple alert is shown and the form is submitted to save_info.php.
Test 2: I copied and modified this jQuery script from another page on this site. No matter what I do, the script does not run. I know this because no alert message is shown.
Test 3: After removing the jQuery(document).ready statement from Test 2, the senddata function runs. Although it runs the process_info script, the form does not get posted to save_info.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 1: this works - form is submitted to the action URL
function senddata() { alert('here'); }
*/
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function() {
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
});
/* Test 3: this runs and the AJAX URL is executed, "success" is displayed - form is NOT submitted to the action URL
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
*/
</script>
</head>
<body>
<form name="myform" id="myform" onsubmit="return senddata()" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
I assume that what I am trying to do is actually possible. What am I doing wrong?
ok, I have edited your code in a way that it works and I'll explain a few changes after the code.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function(){
$("#myform").submit(function(event){
event.preventDefault();
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform")[0].submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
So, first I have removed onsubmit from the <form> element in the html
Then changed the function the same as you did in your comment.
The last trick is that if I wanted to use jQuery("#myform").submit(); in the complete section of the ajax it would add another listener for the form submit event and would call the function again and again and again.
So I had to access the HTML form element directly and call the submit for it, that's the trick as you can see jQuery("#myform")[0].submit();

get post jquery and echo it in $_POST(is that possible?)

I'm learning how to post data to server.I want to click on a link and post its data to the server in the same page, do I need to have a form to do that? is it possible to post data without having a form? I cannot see the result in php should I have any success or done function here to have the results? I also have tried Last example of Jquery manual and there is no content div to see any results and so I couldn't figure it out.
I do not want to show data and append it in the html I want to see it in $_POST and if it is not possible to show it in the same page I am ok with that all I want is to see $_POST can have the data from JQUERY
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: $("#link").val()
}
});
$('form#myform').submit();
});
</script>
</head>
<body>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" value="A">Send</a>
</form>
</body>
</html>
PS:I updated upon answers, and still not result:
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(e){
e.preventDefault();
$.post("newfile5.php",
{
name: $("#link").data("value")
},
function(data)
{
// Whatever is returned by newfile5.php
}
});
});
</script>
</head>
<body>
<a id="link" href="" data-value="A">Send</a>
</body>
</html>
I expect to see $_POST['name'] having the value A, just this
Use data-attr to store data.
<a id="link" href="" data-value="A">Send</a>
Use
console.log($("#link").data("value"));
to fetch it.
So your code becomes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(e){
$("#disp_name").html($("#link").data("value"));
e.preventDefault();
$.post("newfile5.php",
{
name: $("#link").data("value")
},
function(resp)
{
console.log(resp); // Whatever is returned by newfile5.php
}
});
});
</script>
</head>
<body>
<div id="disp_name"></div>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" data-value="A">Send</a>
</form>
</body>
</html>
and dont use $('form#myform').submit();
and to fetch data in PHP, use
$name = $_POST["name"];
I want to click on a link and post its data to the server in the same page, do I need to have a form to do that?
No. You can post the data without having a form.
EDIT
To answer the question after edit (if I well understand it):
Seems to me actually like a X-Y problem but the answer is - No .
PHP isn't able to interfere with the client browser. The AJAX is only a "bridge" between the server (PHP) and the page that has been fully rendered.
(you may want to read about WebSockets)
Fully rendered page have no access to the PHP variables anymore (doesn't matter if it's jQuery or any other client-side language). When connection to the server is completed (page fully rendered), all the PHP named variables and methods cease to exist. They could be set only at the time when the page is being rendered (and that's the only way to get these two languages to work together at the same time), eg:
<script>
var myData = "<?php echo 'something'; ?>";
</script>
Basically, the $.post is used to communicate with the server. If that's not required, you can access the data within the page itself and $.post is not even necessary.
You have an trigger event (click). You set the event to determine when an action should be taken and what is supposed to happen then. Whether it's an AJAX request or anything else.
If the AJAX is required:
var myData = '';
$("#link").click(function(e){
$.post(
"newfile5.php",
{name: $("#link").attr('value')},
function( data ) {
myData = data;
doSomething();
// do something else with the data here. ...
}
);
});
If there's no need to post any data:
var myData;
$("#link").click(function(e){
myData = $("#link").attr('value');
doSomething();
});
The method:
function doSomething(){
if(myData){
alert(myData);
}else{
// ...
}
}
in php access the $_POST variable
Edit:
First of all, you are combining two different ways and doing them wrong at the same time. You are making an AJAX request, and then sending a normal HTTP request without a value. Both wrongs, try this example, it will make an Ajax Post Request and show you the result in an Alert.
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: 'Some Name'
}, function(data) {
alert(data)
}
});
});
</script>
</head>
<body>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" value="A">Send</a>
</form>
</body>
</html>
<?php
if(isset($_POST["name"])) {
echo $_POST["name"];
exit; //So we don't show the HTML in $.post response
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: $("#link").attr('data-value');
}).done(function(response) {
//Handle the response, just alerting for testing
alert(response);
});
//No need
//$('form#myform').submit();
//Event to see the response
});
});
</script>
</head>
<body>
<!--anchors don't have value attributes, use data- attribute-->
<a id="link" href="" data-value="A">Send</a>
</body>
</html>

submit form and check for complete without submit button

I need to submit a form and check for its completion without using the submit button.
I managed to submit it trough document.getElementById('logoForm').submit();, but now I need to call a function if the form was successfully submitted.
My form:
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
Submit function:
$("#file1").change(function() {
document.getElementById('logoForm').submit();
//setTimeout(reloadImg, 2000) this was how i called the next function but its not safe at all
alert('submited');
});
The function I want to be called on a successful submit:
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
You need to submit the form using AJAX, otherwise you will have a page reload, rendering all your JS void.
This is how you could do it with jQuery
//bind to submit
$("#logoForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
ok i got it working!!
$("document").ready(function(){
$("#file1").change(function() {
//bind to submit
$("#logoForm").submit(function(e)
{
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
});
});
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
but once i click the file input i have to reload the page to make it work again... any ideas how to work around this?
As Regent said: "Amazing mix of pure JavaScript and jQuery"
if you will be using jquery first of all you will need to include the jquery library, I don't know if you did that.
Also, if you are working with jquery try to use all that jquery provide you to write less code.
Seeing your code I am assuming that you have a form with a input type file into. And when a file is loaded to the field, you want to submit the form. Also the form is targetted to a frame, so I am assuming that you have an iframe element there too.
To know if the form was successfully submitted you can use an ajax request but in this case your are sending files with the form, so you can not use an ajax request.
You can return a javascript code in your response that will be executed from into the iframe so, you can access to the parent element to do that you want
I have modified a little bit your code to integrate jQuery at all.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
jQuery("#file1").change(function() {
jQuery('#logoForm').submit();
});
});
</script>
</head>
<body>
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
<input type="file" name="file1" id="file1" />
</form>
<iframe name="frame"></iframe>
</body>
</html>
Then in your includes/uplLogo.php you need to return the javascript code to execute a similar of reloadImg()
So, in your includes/uplLogo.php you could have:
<?php
...
Your code here
...
if($all_is_ok) { ?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var id = jQuery('#AppId', window.parent.document).val();
jQuery.post("includes/step_img.php", {id: id}, function(data) {
jQuery('#imgDiv', window.parent.document).html(data);
});
});
</script>
<?php } ?>
I have not tested it because I just wrote it but I think that works.
Try to comment this line: e.unbind();
Try also to add a log just after the input file changes, and verify if you can see the log in the js console:
...
$("#file1").change(function() {
console.log('input file changed');
//bind to submit
...
for those who will need this in the future the problem was:
$("#file1").change(function()
i just changed that to:
function changed()
and add it to input on onchange method!

Unable to submit form with ajax without reloading parent

I am building a web application that will create a div on the page, use ajax to load a form into that div, and then have the form submitted without the parent page refreshing. I've read many examples on this site and others of how to do this, yet I'm puzzled why my proof-of-concept test is not working for me.
What successfully happens is that the parent page is creating the new div and is loading the form into the div. However, upon submitting the form, the parent page reloads. Using "Live HTTP Headers" in Opera, I can see that submitting the form is causing a GET rather than a POST, even though my Javascript is attempting to POST.
Can anyone help me understand why this is happening? Any help is very much appreciated.
Here is the code to the parent HTML page:
<html>
<head>
<script src=\"jquery-1.11.1.min.js\"></script>
<script src=\"jquery.min.js\"></script>
<script type=\"text/javascript\">
var num=1;
console.log('starting the code');
$(document).ready(function() {
console.log('document is ready');
$('#form1').submit(function(event) { // catch the form's submit event
console.log('form is going through submit');
$.ajax({ // create an AJAX call...
url: 'add_user.php', // the file to call
type: 'POST', // GET or POST
data: $('#form1').serialize(), // get the form data
success: function(data) { // on success..
$('#assign1').html(data); // update the DIV
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
event.preventDefault(); // cancel original event to prevent form submitting
});
});
function addToBox(divID) {
console.log('adding new assign to box');
var myNewDiv = document.createElement(\"div\");
myNewDivID = 'assign'+num;
myNewDiv.setAttribute('id', myNewDivID);
myNewDivID = '#'+myNewDivID;
var myBox = document.getElementById(divID);
myBox.appendChild(myNewDiv);
$.ajax({
type: 'GET',
url: 'add_user.php?id=1',
success: function(data) {
$(myNewDivID).html(data);
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
num+=1;
}
</script>
</head>
<body>
<div>
<div id=\"box1\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
<div>
<div id=\"box2\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
</body>
</html>
Here is the code to the PHP page (named add_user.php) with the form.
<?php
$n=0;
$id=$_GET['id'];
if ($_SERVER['REQUEST_METHOD']=="POST") {
echo "got the form!";
} else {
echo "<form id=\"form{$id}\"><select name=\"quantity\">\n";
for ($n=1;$n<=5;$n++) {
echo "<option value=\"answer{$n}\">option {$n}</option>\n";
}
echo "</select>\n<input type=\"submit\" /></form>";
}
?>
Thanks to the comment by A. Wolff, I replaced $('#form1').submit(function(event) { with $(document).on('submit','#form1', function(event){ and it worked.
Thanks A. Wolff!

Categories

Resources