javascript submit() command not sending my post data - javascript

From this earlier thread I thought I learned that form data could be sent by POST method using javascript submit() command. But I can't get it to work. This demo doesn't make obvious sense with respect to purpose but bear with me. I just wanted to test this specific command which doesn't seem to work for me. Can you please help me? Clicking the regular submit button sends the post data ok but activating the javascript via the link does not.
<html><body>
<?php
$self = $_SERVER['PHP_SELF'];
$posttext = file_get_contents('php://input');
echo "Received input: ".chr(34).$posttext.chr(34)."<br><br>";
echo "<form id='test' action='{$self}' method='post'>";
?>
Please fill in the fields with any text:<br><br>
foo: <input type="text" name="foofield"><br><br>
bar: <input type="text" name="barfield"><br><br>
<input type="submit" value="Submit button works"><br><br>
Submitting by JS not working – why?
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
$(document).ready(function(){
$("a#submitlink").click(function(){
alert("Yes, the link has been clicked. It is not that.");
$("form#test").submit();
});
});
});
</script>
</body></html>

You need to: event.preventDefault(); the default behaviour from the <a>. The problem is if you don't do that, the page reloads cause that is what the <a> tag does. So even you submit the data you also refresh the page where the submitted data gets lost.
$("a#submitlink").click(function(event){
event.preventDefault();
$("form#test").submit();
});
The other solution is to add # in the href of the <a> tag like:
Submitting by JS not working – why?
this will also prevent the <a> tag from doing a refresh.

Related

How to allow a user to resubmit a form without a warning

I believe it will be a poor question, because most people wants to prevent a form from beeing resubmited but I'll need the exact opposit of it.
That means a user should be allowed to reload a page and the form values have to be posted each time (Session Variables are not possible in this cenario)
Normally the user gets the annoying warning message of the browser.
Is it possible to turn this warning off or simply resubmit the form (eg. with jQuery)
Thanks a lot for your help!
You could overwrite alert and empty the function with alert = function(){}. Check this example:
alert("test");
alert = function(){};
alert("test2");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You cannot turn off this alert (in a good way), but you can redirect to the same form, with all fields auto-compiled, so if you re-do a submit, it won't ask you a confirm.
You can redirect with a _GET parameter, and if your code detect this, it will check for all values to insert in the form.
Something like this:
form.php
<?php
if(!empty($_GET['param'])) {
/* Pseudo code */
$data = query_and_fetch("select 'value_1' as field_1 from yourtable WHERE wfield='".escape($_GET['param'])."' ;");
}
?>
<form method='post' action='process.php'>
<input name='field_1' value='<?=isset($data['field_1']) ? $data['field_1'] : ''?>/>
<input type='submit' value='submit'/>
</form>
process.php
<?php
header("location: form.php?param=123");
?>

Form submitting when clicked

I am having an issue with this login system, when ever I click the log in button, or the sign up button it re-directs me to a white page with writing on it, That being said it is interfering with my log in action.
Here is the code that I think is causing the issue,
<form method="POST" action="" accept-charset="UTF-8">
on line 16 of the HTML code, I tried to take that code out and it stopped the re-directing but the text boxes went out of place, and the white background/background-box was not there either,
Link, HERE
You want to use preventDefault() if this is a purely Javascript: you should be able to pass the button press event into the listener when you create it:
$('.login').on('click', function(e) {
e.preventDefault();
// Will be executed on press
}
<form method="POST" class="login" accept-charset="UTF-8">
If there's no JS involved in this scenario, then you want to get rid of the action parameter entirely – leaving it as the empty string will still cause it to redirect in some cases.
As Jonathan Lonowski explained above, when the log in / sign up button is clicked, the form will post the data to the page mentioned in the action= attribute. Since this attribute is empty in your form tags, it will re-load the same page, posting the data to itself.
The data will arrive in key=value variable pairs. The variable value will be the contents of the field, the variable name will be the value of the name="" attribute on the element.
For e.g., for this field:
<input id="fname" name="first" value="Bobby" />
The data will be received like this:
$fn = $_POST['first']; //value is Bobby, or whatever user enters
On your page containing the form, add a section at the top like this:
<?php
if (isset($_POST['fname']) == true){
$fn = $_POST['fname'];
echo "Received First Name: " . $fn;
die();
}else{
?>
//Your current page, in its entirety, goes here
<?php
} //close the PHP if statement
?>
That is how you deal with a normal HTML <form> construct.
However, if you wish to use AJAX to communicate with a PHP file without changing the page, then:
(1) There is no need to use a <form> construct, just use a DIV with an input button: <input type="button" id="sub_btn" value="Submit" />
(2) Trap the button press using standard js/jQuery:
$('sub_btn').click(function(){
var fn = $('#first').val();
//etc.
$.ajax(function(){
type: 'post',
url: 'my_php_processing_file.php',
data: 'fname=' +fn+ '&lname=' etc
});
});
In your PHP processor file, the data will be received thus:
<?php
$fn = $_POST['fname'];
$ln = $_POST['lname'];
//Do your MySQL lookup here...
echo 'Received ' .$fn. ' ' .$ln;
(3) IF you do use the form construct, you can still do everything as above, but you will need to suppress the default form action of navigating to the page specified in the action= attribute (an attribute setting of action="" will post data to and reload the same page you are on).
To suppress navigating to the page specified in action= (involves page refresh, even if just action=""), use event.preventDefault(), as follows:
$('#buttonID').click(function(event){
event.preventDefault();
//remainder of button click code goes here
});

Replace a php variable with textbox input

Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>

Using a php function inside javascript code

I would like to run a php function from a javascript code, to be more specific I got a button that delete a record from the database. The function that does that named
delete_post($id)
Here is what I tried:
<input type="submit" name="delete" value="delete"
onClick="if(confirm('Are you sure?')) {<?php delete_post($row['id']);?>}">
When I click the button, there is no alert box. The funny thing is if I don't call a function inside the php code and I do something else such as echo the alert does pop out but the php code doesn't executed.
So, how can I do that? How can I run a php code inside my javascript onClick code.
You can't. PHP is supposed to be run before the page loads, thus giving it the name Pre-Hypertext Protocol. If you want to run PHP after a page loads via JavaScript, the best approach would be linking to a new page that runs the PHP, then returning the user back.
file1.php:
...
<input type="submit" name="delete" value="delete" onClick="if(confirm('Are you sure?')) document.location.href='file2.php';">
...
file2.php:
<!doctype html>
<html>
<head>
<?php
delete_post($row['id']);
?>
<meta http-equiv="refresh" content="0; url=file1.php" />
</head>
<body>
<p>You will be redirected soon; please wait. If you are not automatically redirected, click here.</p>
</body>
</html>
Assuming you would have multiple IDs, you can keep them all onto one redirect page:
if(confirm('Are you sure?')) document.location='file2.php?id=2'; // file1.php
delete_post($row[$_GET["id"]]); // file2.php
But do not put PHP code directly into the query string, or your site could be susceptible to PHP injection
You can't RUN php code in Javascript , but you can INVOKE it through JS/Ajax. For good practice split your php and JS , for example create a page that takes an ID and deletes it's row (i'm guessing your using REST) and invoke it through JS.
Cleaner , effective , and more secure
From your question, i would suggest you give jquery a try.
link to Jquery on your page's head section,
here is your js function
function deleteRow(id)
{
var url='path/to/page.php';
$("#loading_text").html('Performing Action Please Wait...');
$.POST(url,{ row_id: id } ,function(data){ $("#loading_text").html(data) });
}
This should do it for you.
Since its a delete, am using $.post Let me know if you find any more issues
here is a link to jQuery hosted by google CDN
//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js
This is how your form should look like
<form>
<label for="Number"></label>
<input type="text" name="some_name" id="some_id" value="foo bar">
<input type="submit" name="delete" value="delete"
onClick="javascript: deleteRow(the_id_of_the_row);">
</form>
<br>
<div id="loader_text"></div>
now your php page that does the delete could look like this
<?php
$row_id = some_sanitisation_function($_POST['row_id']) //so as to clean and check user input
delete_post($row_id);
echo "Row deleted Successfully"; //success or failure message
?>
This should do it for you.

jquery form submit

I have a jquery fancyzoom box. In that box ,I have a contact form which sends an email on submission. But I am not able to call form submit function due to fancyzoom.
Code is like :
("req_quote.php")
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/fancyzoom.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#popup1_link').fancyZoom({width:610});
$("#submit").css('cursor', 'pointer');
$('.reqfrm').submit( function(){
alert("hell");
});
});
</script>
<body>
<form class="reqfrm" id="frm">
<input type="text" name="name" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Above file is included in "index.php" which contains the actual link to open the form in fancyzoom box.
(index.php)
< a href="#popup1" id="popup1_link">< div class="blink">Request a Quote< /a>"
If I remove $('#popup1_link').fancyZoom({width:610}); then i get alert on submission otherwise it goes on form action directly.
Are you getting any JavaScript errors with the fancyZoom call in? Are you including the script file you need to use it? It's hard to say without seeing some more data, or a jsbin / jsfiddle.
The form is submitted in the fancybox js file.
As mentioned by Raul, you need to provide more info for us to help out. You could try any of these things:
See if you can reproduce this issue within a simple html file, that doesn't have any of the extra stuff that your current page may have. If the issue still persists, put it into jsFiddle and post the link here.
If you haven't already, install the Firebug addon for Firefox, and use it's console to check for any JS errors.
Have a look at the jsFiddle that I've created. Is this similar to what you are doing? Mine works wihtout any issues.

Categories