jQuery e.preventDefault() not Working - php

I have few lines of code to create a form and then later in the code I am using AJAX $.post through JSON.
My html form scripting code creates a simple form and then by pressing a "enviar (submit) button, it'll print my vars data. I am calling with $.post a file called dados.php, as you'll see later in this message.
I am in the impression that by using jQuery preventDefault() by clicking in the the "enviar" button nothing would happen but it'll bring to other page showing data from my vars (I am doing print_r($_POST); and var_dump($_POST); inside my dados.php.
First, I could be wrong to thing that jQuery preventDefault() or others (you'll see commented in my code) "prevent" any action after the user/me click on the "enviar"(submit) button; nothing would happen, but still prints my vars data.
Second/lastly, there's something wrong with my code.
Please check the following scripting code for my HTML form and for my dados.php (php code); In advance I really appreciate your help:
MY HTML FORM/JSON:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<title></title>
</head>
<body>
<div id="result">texto do cliente</div>​
<form id ="myform"action="dados.php" method="post">
<table>
<tr>
<td>Nome:</td>
<td>
<input type="text" id="first_name" value="" maxlength="25" />
</td>
</tr>
<tr>
<td>Sexo:</td>
<td>
<input type="radio" id="Sexo" value="Masculino" /> Masculino
<input type="radio" id="Sexo" value="Feminino" /> Feminino
</td>
</tr>
<tr><td>Profissão:</td>
<td>
<select id="dropdown">
<option value ="administrador">Administrador</option>
<option value ="analista">Analista</option>
<option value ="designer">Designer</option>
<option value ="gerente">Gerente</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="submit" type="submit" value="enviar"/>
</td>
</tr>
</table>
<script type="text/javascript">
$(function(){
/* attach a submit handler to the form */
$("input[type='submit']").click(function(e) {
/* stop form from submitting normally */
e.preventDefault();
//e.stopImmediatePropagation();
//e.stopPropagation();
$.post(
'dados.php', {firstname: $('#first_name').val(), sexo: $('#sexo').val(),
profissão: $('#dropdown').val()}, function(data) {
console.log(data);
//$('#result').html(data)
//$('#result').html(data.firstname)
//$('#result').html(data.sexo)
//$('#result').html(data.profissão)
}, 'json');
});
</script>
<script>
</script>
</body>
</html>
MY DADOS.PHP:
//ECHO $_POST['dropdown'];
print_r($_POST);
var_dump($_POST);
Big Thanks.
Marco Lanza

You didn't close your $(function(){.
You need to add another }); at the end.

Try adding return false; to the end of your callback. I usually just set this on the form itself if I'm planning to make an AJAX form: <form action="someAction" method="post" onsubmit="return false;">
Also, you should attach to the submit event on the form rather than the click event on the button - remember that if the user presses the Enter key, the form will submit, bypassing the event handler on the button.

Instead of:
$("input[type='submit']").click(function(e) {
Try this:
$("#myform").submit(function(e) {

Did you try to put your jQuery script into HTML header and change $(function() to $(document).ready(function(){?

$("input[type='submit']").click(function(e) { isn't a submit handler, it's a click handler for the submit button, which probably isn't what you actually need.
Try replacing that line with $("form#myform").submit(function(e) { instead.

Change to a form submit where you have this:
$("input[type='submit']").click(function(e) {
do this:
$('#myform').submit(function(e) {

Really, you should just use <input type="button"> and add the click handler to that.

Try putting return false; after your $.post call

Related

Codeception - how to render(or process) html returned from sendPost request

I need to test POST endpoint that returns html with autosubmit form(js script submits it after small delay). Current behaviour is that after sendPost nothing happens, wait does not help too, but I can retrieve full html with grabResponse method. Is there any way I can either make Codeception process returned html so that form will be submitted automatically or render html manually? In the end I will need to check that returned html form was submitted, that I was redirected to the correct url and then I will need to check some elements on the page I was redirected to.
Returned html example
<html xmlns="http://www.w3.org/1999/xhtml">
<body onLoad="autoSubmit(300)">
<form id="redirectForm" name="form" action="/redirect-url" method="post">
<input type="hidden" name="input1" value="value">
<input type="hidden" name="input2" value="value">
<input type="hidden" name="input3" value="value">
<noscript>
<center>
<h3>Please click the Continue button if you are not automatically redirected.</h3>
<input type="submit" value="Continue">
</center>
</noscript>
</form>
<script type="text/javascript">
function autoSubmit(timeout) {
setTimeout(function () {
form.submit();
}, timeout);
}
</script>
</body>
</html>
What I want to do
$data = $this->prepareData(I);
$I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded', true);
$I->sendPost($url, $data); // returns html with form
// some magic happens here
$I->canSeeCurrentUrlMatches('my-url');
$I->canSeeElement('element indicating that form values were valid');

PHP form pop-up for confirmation request

I would like to implement a pop-up request for the user , e.g. if the user press "yes" for confirm data on MySQL DB are modified otherwise no. This should be done without creating another php confirmation page. I looked through forum discussions , I founded some possible solutions based on Ajax or Javascript but unfortunately I don't know how to programme with these tools.
Can anyone helps?
many thanks
//$sql_select= "SELECT .... FROM DB
}
//------------------Button save data pressed--------------------
if (isset($_POST['bottone_update'])) {
// If te user click confirm button I have to modify the database
/*$sql_upd = "UPDATE db_sale.prenotazioni_alpha SET VALUES.....*/
}
?>
<html>
<head>
</head>
<style type='text/css'>
<meta charset="utf-8">
</style>
<body>
<form method="post" action="">
<!--Table data -->
<table class='table1' id="pos_table1">
<tr>
<td><textarea name="alpha_9_10"></textarea>
<td>
<td><textarea name="meda_9_10"></textarea>
<td>
</tr>
<tr>
<td><textarea name="alpha_10_11"></textarea>
<td>
<td><textarea name="meda_10_11"></textarea>
<td>
</tr>
</table>
<button type="submit">look for data</button>
<button type="submit">Save data</button>
You can simply add an onSubmit attribute to the form, with the JavaScript function confirm in it. It will open a pop-up in the browser, asking whatever you define within the first parameter, with two buttons: "OK" and "Cancel". This has the feature of returning true or false (a boolean), when clicking "OK" or "Cancel" respectively.
This means that if you do onSubmit="return confirm('Are you sure?');" in the form, you'll be able to send the form only if you press "OK" to this check. Then, in PHP, you just check weather or not the form has been submitted; and if it has - you perform your update-query, like you already started doing - no need for additional checks!
if (isset($_POST['bottone_update'])) {
// Perform your query
}
Your opening <form>-tag should then contain this:
<form method="POST" onSubmit="return confirm('Are you sure?');">
<!--- Rest of form goes here -->
</form>
If you have action="", you can just remove it altogether.
Try This:
$('#button').click(function () {
if (confirm('Are You Sure?')) {
$.post('http://localhost/ajax.php', function () {
alert('Data Added Successfully!');
});
}
});

Assistance with FORM-SUBMIT & "?" removal from URL

I was wondering how one would go about sending whatever the user types in text box; to the end of the <form action=. If one does not have access to the websites code source, how would one go about this?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
a:link {color:#687BC6;}
a:visited {color:#0F0;}
a:hover {color:#000;}
a:active {color:#0A0;}
</style>
</head>
<body>
<form name="form1" method="get" action="http://www.blah.com/right-now/" target="_blank">
<table border="0" cellpadding="2" cellspacing="0">
<tr><td>ZC:</td>
<td><input name="fld-zip" type="text" maxlength="7" size="15"></td></tr>
<tr><td> </td>
<td><input type="submit" name=Submit value="Submit this"></td></tr>
</table>
</form>
</body>
</html>
Pretty much asking how you can add what you put in text box to the end of URL /??? when you click the submit button.
So it shows:
Textbox - "11722"
URL = http://www.blah.com/right-now/11722
Is there a way to do this via css/html/php/js?
Every time I click the SUBMIT button, it just adds a '?' at the end and it gets cut off.
Well,m just giving it a try...i dunno whether it'll work or not.. do one thing,use two files..one to get the zip code..
=>in file 1,use a form.. after submitting,send the zip code to a dummy file(second file) i.e.,action="dummy.php"
=>in dummy file assign the zip code to a variable '$a'
$a=$_GET['zip'];
now use javascript
<script>
function a()
{
newwindow=open("http://www.blah.com/rightnow/'$a'",window,"height=900,width=1100");
}
</script>
I would do something like this at the top of the page.
<?php
if (!(empty($_GET['fld-zip']))){ //check if the var is empty
$url = "http://www.blah.com/right-now/";
$page = $_GET['fld-zip'];
header("location:$url . $page"); //if its all good then redirect to the correct page
}
?>
This could probably be done a bunch of different ways but should work.
The ? is there because the form is submitted using get it wont go away and shouldnt. Do some reading on GET and POST in HTML forms.
if you use GET, the link should look something like "http://www.blah.com/right-now?variable1=11722&variable2=11733. The question mark is at the beginning of the variables. How does it get cut off?
If you're using http://www.blah.com/right-now/ as the action, make sure that http://www.blah.com/right-now/index.php has the logic.
As your basically wanting to just open a new window with the value of what's entered in the text box concatenated on to a url;
Change your form slightly, use a button instead of a submit, and with the use of jquery(cleaner imo) and a simple js function to put it altogether & trigger it from the forms onClick="doForm()".
<script>
function doForm(){
var param = $("#fld-zip").val();
window.open ("http://www.blah.com/right-now/" + param,"openwindow");
}
</script>
<form name="form1" method="get" action="" target="_blank">
ZC:<input name="fld-zip" id="fld-zip" type="text" maxlength="7" size="15">
<input type="button" name="Submit" onClick="doForm()" value="Submit this">
</form>
Add a script like this
function formSubmit(){
document.getElementById('frm1').setAttribute('action', "http://www.google.com/right-now/" + document.form1["fld-zip"].value)
document.form1["fld-zip"].value = '';
return true;
}
then add onsubmit event to your form
<form id="frm1" name="form1" method="get" action="http://www.blah.com/right-now/" target="_blank" onsubmit="return formSubmit()">
Working example http://jsfiddle.net/FtRKp/4/

Submit button clicking changing the value of it to another thing

maybe very easy!
I'm php coder and I don't have experience in js but I must do this for one of my codes
suppose I have sub1 in page after clicking it must be that sub1 but value now is sub2
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<?php
//some code
if(array_key_exists('update',$_POST)){
//somecode
}
?>
<input type="submit" name="update" value="<?php echo if(isset($_GET['update'])) ? 'Show' : 'Update' ?> ">
</form>
</body>
</html>
show as function name does not really make sense here (imo), but you could do:
<input type="submit" name="sub" value="sub1" onclick="show(this)">
and
function show(element) {
element.value = 'sub2';
}
Important:
But that will actually not solve your problem. As soon as you click the button, the form is submitted, meaning the browser initiates a new request and will load a new page. So every change you made the current page is lost anyway.
The question is: What are you trying to do?
It seems to me that you should change the value of the button on the server side. You have to keep track which form was submitted (or how often, I don't know what you are trying to do) and set the value of the button accordingly.
Update:
I see several possibilities to solve this:
You could keep using JavaScript and send and get the data via Ajax. As you have no experience with JavaScript, I would say you have to learn more about JavaScript and Ajax first before you can use it.
You could add a GET parameter in your URL with which you can know which label to show for the button. Example:
<form method="post" action="?update=1">
and
<input type="submit" name="sub" value="<?php echo isset($_GET['update']) ? 'Show' : 'Update' ?> ">
Similar to 2, but use a session variable (and not a GET parameter) to keep track of the state.
Update2:
As you are already having $_POST['update'] you don't need the URL parameter. It could just be:
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<input type="submit" name="update" value="<?php echo isset($_POST['update']) ? 'Update' : 'Show'; ?> ">
</form>
</body>
</html>
This should do it
function show(){
document.getElementsByName('sub')[0].value = 'sub2';
return false;
}
Edit: if you don't want it to submit the form, just add a return false, but then you'd need to change your onclick from your submit button to your forms onsubmit;
<html>
<head>
<title>test</title>
<script>
function show()
{
document.getElementById("sub").value= "sub2";
return true;
}
</script>
</head>
<body>
<form method="post">
<input type='submit' id="sub" name='sub' value="sub1" onclick="return show()">
</form>
</body>
</html>

Combing JS and PHP on one button. Is it possible?

Hiya:
i know some people would be so tired of my questions, but I'm working on a uni project and need to get it done as soon as possible. This question is about using JS on a button(button) and sending a php_my_sql update on the same button. The problem is JS uses button, right? but PHP uses button(submit). How can I get these two to work on one of these buttons, cuz there has to be only one button.
this is my code for JS
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex)
}
</script>
HTML
<form method="post">
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="**submit/button**" onclick="formAction()" name="Collect" value="Collect" /></form>
PHP
<?
if (isset($_POST['Collect'])) {
mysql_query("UPDATE Player SET score = score+10
WHERE name = 'Rob Jackson' AND rank = 'Lieutenant'");
}
?>
This can be a way
Submit the form through JS after removing parameter
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex);
document.forms[0].submit();
}
</script>
Input type button
<input type="button" onclick="formAction()" name="Collect" value="Collect" />
Embed jQuery and use $.post() to send an AJAX request.
JavaScript can interact with the button whilst the user is navigating the page and entering data into the form. The instant the user pushes the submit button and the request for the form submission is sent JS no longer has control. The request is sent to the form's action (most likely a PHP file) which processes the request and gives an answer back.
If you really need to combine the two, look into AJAX.
<?php print_r($_POST); ?>
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect");
x.remove(x.selectedIndex);
submit_form();
}
function submit_form() {
document.form1.submit();
}
</script>
<form method="post" name='form1'>
<input type='hidden' name='Collect'/>
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="button" onclick="formAction()" name="Collect" value="Collect" /></form>
<?
if (isset($_POST['Collect'])) {
//do whatever update you want
}
?>
Simple Solution
Make this modification in the form tag
<form method="post" onsubmit="return formAction()">
In JavaScript function add a line "return true;" at the end of the function.
Voila ..!!! you are done..!!
Enjoy..!!

Categories