Please, can somebody publish a mistakes corrected and tested code for my problem?
Program does - 22.php has the form. When the user enter and click Submit button, the result should be taken from 23.php and displayed in div on 22.php
I already tried solutions below and none of them solve my problem;
1) I changed to: $("#testform").submit(function(event){
2) I included "return false;" at the end to prevent it to actually submit the form and reload the page.
3) clear my browser cache
I can see what happen the program with my computer;
1) I do not get error message after I click submit.
2) I can see the tab of the page reloads quickly and the entered text fields are cleared.
3) No error message or result shows.
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').val(data);
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
you don't need to change your php code
try submit form with submit event ...
$("#testform").submit(function(event){
use `dataType:json`; in your ajax ..
yourData =$(this).serialize();
Your php
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
$data['name']= 'welcome '.$name;
$data ['age']= 'you are '.$age;
print_r(json_encode($data));exit;
}
?>
Now In Your Success function
var message = data.name + ' ' + data.age;
$('#result').html(message );
You are sending myname and checking name(isset($_POST['name']) in php.
don't use .value() use .html() for data rendering. and console log the data and see whats request and response using firebug.
Can you try this one?
To be changed
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
and
$('#result').html(data); // here html()
the code becomes
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
alert('Submitted');
}else{
return false;
}
}
});
});
});
Try formatting your post data like this inside your ajax function.
$.ajax({
type:'POST',
data : {
myname: myname
myage: myage
}
...
}
EDIT
Try removing the ; in
return false;
}
};
to
return false;
}
}
You can change at both end ajax and php:
#PHP:
You can check for correct posted data which is myname and myage not name and age.
<?php
if ( isset($_POST['myname'])) { // was the form submitted?
echo "Welcome ". $_POST["myname"] . "<br>";
echo "You are ". $_POST["myage"] . "years old<br>";
}
?>
or #Ajax:
yourData ='name='+myname+'&age='+myage;
//--------^^^^^^----------^^^^----change these to work without changing php
Just noticed the #result is an div element. So, you can't use .val() but use .html(), .append() etc:
$('#result').html(data);
Related
I am trying to call a function that isn't being recognised. I have a PHP block of code that adds the form to the HTML when the user is logged in:
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user'];
echo("<form onsubmit=\"nbpost('#nbpost','$usr'); return false;\">\n");
echo("<textarea id='nbpost' placeholder='Create a post...'></textarea>\n");
echo("<button type='submit'>SUBMIT</button>\n");
echo("</form>\n");
}
?>
I put my JavaScript below that HTML. According to W3Schools, the script has nothing to do with how it's executed. Additionally, I've tried countless times to execute the script when the script was on top, with no result either.
Also, I previously had the code in a separate script, but I've taken it out to see if that's the issue.
Here's the script with an example of the generated HTML:
<form onsubmit="nbpost('#nbpost','$usr'); return false;">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<button type='submit'>SUBMIT</button>
</form>
<script type="text/javascript">
const nbpost = function(element, name) {
alert("WORKING");
name[0] = name[0].toUpperCase();
const msg = $(element).val;
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
};
</script>
Whenever I execute the code, it simply says in the console:
Uncaught TypeError: nbpost is not a function at HTMLFormElement.onsubmit (index.php:54)
What's going wrong?
Change the name of the function nbpost so it does not match the textarea id='nbpost'
CodePen
I would try and separate your content a little better, it can make it less confusing. Give this a try with jQuery enabled.
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user']; ?>
<form id="form" method="post">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<input type="hidden" name="user" value="<?=$usr;?>">
<button type='submit'>SUBMIT</button>
</form>
<?php
}
?>
This needs to go at the bottom of your document. You can also put the JavaScript in a separate file and call it by filename of course.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#form").on("submit", function (e) {
e.preventDefault();
var name = $("input[name=user]").val().toUpperCase();
var msg = $("#nbpost").val();
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
});
</script>
see if this works for you.
You should declare your submit event as an entire function
onsubmit=\"function(){nbpost('#nbpost','$usr'); return false;}\"
I have form in 100.php with ajax call to 200.php.
<html>
<head>
<!-- include reCAPTCHA API JavaScript library given by Google -->
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData ='name='+myname+'&address='+myaddress; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '200.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name: <input type="text" name="name" value="" id="name"/> <br />
Address: <input type="text" name="address" value="" id="address"/>
<!--
place for the reCAPTCHA widget div with your site key
data-theme="dark" attribute - gives dark version
-->
<div class="g-recaptcha" data-sitekey="6LeJ8h8TAAAAAMS9nQX89XccpsC-SDeSycipiaHN"></div>
<input type="submit" name="ok" value="Send" id="btn"/>
</form>
<div id='result'></div>
</body>
200.php does validate captcha and diaplay name and adddress user entered. But my problem is that when I entered name and address, click on captcha. Captha is also validated and shows as in my screenshot. but name and address is not shown on the page. You can also check yourself here: http://raveen.comlu.com/100.php
I am new to Ajax call by PHP. I googled and I can troubleshoot by firebug. Can you say what I am doing wrong here? and steps to troubleshoot by firebug like to check if my ajax call is done, etc? thanks for your help.
Note: when I put all these code in one page without using ajax call. it works fine!!!!! I want this happens without page reload....
output
200.php
<?php
require_once('recaptchalib.php');
if( isset($_POST['ok']) ){
if( isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']) ){
$secret = "6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1"; //your secret key
$response = null; //empty response
$reCaptcha = new ReCaptcha($secret); //check secret key is present
$response = $reCaptcha->verifyResponse( $_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response'] );
//$response variable will report back with "success"
if( $response!=null && $response->success ){
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}
}
else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
}
?>
There are few errors in your code, such as:
Look at the following two statements,
if( isset($_POST['ok']) ){...
and
var yourData ='name='+myname+'&address='+myaddress;
You're not sending any variable named ok to 200.php page, so the control won't even enter the if block.
You're validating reCaptcha in the wrong way. From the documentation:
If your website performs server side validation using an AJAX request, you should only verify the user’s reCAPTCHA response token (g-recaptcha-response) once. If a verify attempt has been made with a particular token, it cannot be used again. You will need to call grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
So you have to use grecaptcha.getResponse() to get the user's response.
And as a sidenote use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
Your jQuery/AJAX script should be like this:
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var recaptchaResponse = grecaptcha.getResponse();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData = {name: myname, address: myaddress, recaptchaResponse: recaptchaResponse};
$.ajax({
type: 'POST',
data: yourData,
dataType: 'html',
url: '200.php',
success: function(data) {
// reset form
$('#testform')[0].reset();
// display data
$('#result').html(data);
// reset the reCaptcha
grecaptcha.reset();
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
});
});
</script>
And on 200.php page, process your AJAX data like this:
<?php
//your site secret key
$secret = '6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}else{
// failure
echo "<h1>You have incorrect captcha. Please try again.</h1>";
}
}else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
?>
I want to execute a JS function when a PHP form is submitted, and from that function, I want to return a value (which is based on user's input) to PHP, where I'd like to echo it.
This is an SSCCE. In the real code, there is more than just echoing the value, and the value is a JSON object.
Following is my code. The problem is that the $.ajax(); part is not working. Nothing happens in the browser after alert(name);.
Why isn't this working properly? How can I fix this?
From index.php:
<form id="form">
Name:
<input id="name" type="text" />
<input type="Submit" value="Go" />
</form>
From scripts.js:
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
alert(name);
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
}
});
});
});
echo.php:
<?php
if ( isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"]) ) {
echo $_POST["nameEntered"];
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
EDIT:
Console:
Network:
EDIT 2:
Added the following to $.ajax():
,
success: function(){
alert("success");
},
error : function(){
alert("error");
}
I get an alert saying success but the browser NEVER directs to echo.php =s
EDIT 3:
After the alert saying success, a ? is added to the URL in the browser. Initially the URL was http://localhost/Test12/index.php and it changed to http://localhost/Test12/index.php?.
This way should show response.
JAVASCRIPT
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
//alert(name);
$.ajax({
type:'POST',
url:'http://localhost/Test12/echo.php',
data: {
nameEntered : name
},
success : function(data){
console.log(JSON.parse(data));
},
error : function(error){
console.log('erro', error);
}
});
});
PHP
<?php
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
$name = array("nome" => $_POST["nameEntered"]);
echo json_encode($name);
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
As a test, replace your echo.php with:
<?php
echo 'Incoming = ' .$_POST["nameEntered"]. "/r/n";
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
echo 'Here 01';
} else {
echo 'Here 02';
}
?>
Try removing the document.ready() or instead of .submit use .on('submit', function(e){}); or add absolute path '/page.php'
I think you need to add "event" as parameter in your submit function, in addition to the success call to show results
What does this give you:
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
},
success: function(recd){ // <-------
alert(recd); // <-------
},
error : function(){
alert("error");
}
});
You're calling event.preventDefault(), but you've failed to add the event to your callback's parameters... so you're not actually stopping the form from being submitted. That is why you see the question mark in the address bar.
Try:
function(e){
e.preventDefault();
};
I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)
I want to execute a shell script from webpage. So I started with a simple arithmatic sum program. Webpage has two fields and a submit button. If user clicks submit button, javascipt validates and then calls php file through ajax. Php file extracts the arguments and call sum.sh with those arguments.
But i'm unable to do it. Here is my code.
design3.html:
<body>
<form action='' method='post'>
<center>
arg1: <input type='text' name='t1' id="arg1"/> <br><br>
arg2: <input type='text' name='t2' id="arg2"/> <br><br>
<input type='submit' name='use_button' value='Sum' onclick="addContent()"/>
</center>
</form>
<script type="text/javascript">
function addContent(){
var a = document.getElementById('arg1').value;
var b = document.getElementById('arg2').value;
if(a == "" || b == "") {
alert("Please fill all fields");
return;
}
var request = $.ajax({
url: "add.php",
type: "POST",
dataType: "html",
data: {functionname: 'add', arguments:[a, b]}
});
request.done(function(msg) {
alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</body>
add.php:
<?php
if (is_ajax()) {
if( isset($_POST['functionname']) ) {
switch($_POST['functionname']) {
case 'add':
$var1 = $_POST['arguments'][0];
$var2 = $_POST['arguments'][1];
$cmd = 'sh ./sum.sh'.' '.$var1.' '.$var2;
$output = shell_exec($cmd);
echo $output;
break;
}
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
sum.sh:
#!/bin/bash
var1=$1
var2=$2
echo `expr $var1 + $var2`
I'm new to this JS and PHP. But tried hard to do this. If I'm testing seperately it's working. When I write html and php in same file without JS then my script is working. If I'm not calling sum.sh script file in php, it is working. Coming to total integration it is failing. I'm getting this error from browser alert Request failed: error.
You POST to the server
functionname: 'add'
It does not match with your server-side test
switch($_POST['functionname']) {
case 'connect':
I thought the problem is in javascript or php. But the problem is in my html code. One of my friend solved this problem.
He told I took submit button. So he changed the type of button submit to button. Now it's working fine.
Change this code:
<input type='submit' name='use_button' value='Sum' onclick="addContent()"/>
to:
<input type='button' name='use_button' value='Sum' onclick="addContent()"/>