Below i have written code of a soap webservice in php with its client,It is working fine, actually m new to php so don't know how to post data to my server php service from html page, i know by using javascript it is possible but how.....any help by code or helpful link will be appreciated.
<?php
require_once "lib/nusoap.php";
function getProd($username,$password) {
$user = "root";
$pswd = "root";
$db = "LOGIN";
$conn = mysql_connect('localhost', $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT * FROM PEOPLE WHERE USERNAME = '$username' AND PASSWORD = '$password'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
$valid="LoginSucessful";
else
$valid="LoginFailed";
return $valid;
}
$server = new soap_server();
$server->configureWSDL("productlist", "urn:productlist");
$server->register("getProd",
array("username" => "xsd:string","password" => "xsd:string"),
array("return" => "xsd:string"),
"urn:productlist",
"urn:productlist#getProd",
"rpc",
"encoded",
"Get a listing of products by category");
if ( !isset( $HTTP_RAW_POST_DATA ) ) $HTTP_RAW_POST_DATA =file_get_contents( 'php://input' );
$server->service($HTTP_RAW_POST_DATA);
#client of service#
<?php
require_once "lib/nusoap.php";
$client = new nusoap_client("http://localhost/expa/productlis.php");
$result = $client->call("getProd",array("category" => "admin","item" => "admin"));
Overall just need to pass parameter to the php function.
There are few ways to get data from the user:
Pass data via url parameters:
Foo equals Bar
<?php
$foo = (isset($_GET['foo'])) ? $_GET['foo'] : 'undefined';
echo "foo equals $foo";
?>
A straight up form:
// index.php
// An example form that loops back to itself.
<form action="index.php" method="post" id="the_demo_form">
<fieldset>
<label for="foo">Foo</label>
<input type="text" name="foo">
</fieldset>
<input type="submit"/>
</form>
<pre>
<?php
// the $_POST global contains the data sent in the request.
var_dump($_POST);
?>
</pre>
Ajax
If you need to submit the data without reloading via javascript the page you would use AJAX.
This is an example using jQuery that catches the form submit event and sends the form without reloading the page.
// index.php
// An example form
<form action="index.php" method="post" id="the_demo_form">
<fieldset>
<label for="foo">Foo</label>
<input type="text" name="foo">
</fieldset>
<input type="submit"/>
</form>
<script>
$(document).ready(function(){
$("#the_demo_form").submit(function(event){
// This prevents the browser from following the form.
event.preventDefault();
// We take the data and send it to server via AJAX.
$.ajax({
// set this to server side script
url : "index.php",
data : $(this).serialize(),
success: function(data){
alert("eureka!");
}
});
});
});
</script>
Related
I'm trying to create a system on my HTML website where you can enter a code which then gets checked by a php-file. The php shall compare the code with codes that are in my MYSQL Table. The php shall also check whether the code was allready used or not. After the check is completed a message shall appear on the Website that tells the user if his code is valid or not.
If the Code is valid, it shall inform me somehow that somebody entered a code.
I've wrote some code but when I press the button it's not working at all.Here my HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11/jquery.min.js">
</script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 6;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' has allready been used.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<center><h1>Enter Promo Code</h1>
<form method="post" action="check_code.php">
<input type="text" id="code" name="code" maxlength="6" />
<div id="promo_code_status"></div>
<br>
<input type="submit" value="Let's go"></center>
</form>
</body>
</html>
And here you have my PHP File:
<?php
//connect to database
$user = "***"; //Username
$pass = "***"; //Password
$host = "localhost"; //Host
$dbdb = "***"; //Database name
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select Code from Codes where Code = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
By pressing the Button "Let's go" the PHP shall do it's Job and afterwards it shall give the user the information about his code.
What do I have to change?
I thing you not assign the post value in $code, that's reason.
$code = mysqli_real_escape_string($connect, $_POST['code']);
make sure the jquery CDN that you are using can be accessed. because it looks like wrong CDN.
in the checkcode() function, you use #Promo_code_status, P is uppercase, while in html you use promo_code_status with p is lowercase.
in php file you forget to assign values to the $code
I hope this helps
I want to validate my form using JQuery and use php to send it to my database.
This is what I've tried:
<body>
<form id="first_form" method="post" action="">
<div>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"></input>
</div>
<div>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name"></input>
</div>
<div>
<label for="handphone">Handphone:</label>
<input type="text" id="handphone" name="handphone"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
<script>
$(document).ready(function() {
$('#first_form').submit(function(e) {
e.preventDefault();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var handphone = $('#handphone').val();
$(".error").remove();
if (first_name.length < 1) {
$('#first_name').after('<span class="error">This field is required</span>');
return false;
}
if (last_name.length < 1) {
$('#last_name').after('<span class="error">This field is required</span>');
return false;
}
if (handphone.length < 1) {
$('#handphone').after('<span class="error">This field is required</span>');
return false;
}
});
});
</script>
<?php
$first_name = "<script>var first_name = $('#first_name').val();</script>";
$last_name = "<script>var first_name = $('#last_name').val();</script>";
$handphone = "<script>var first_name = $('#handphone').val();</script>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO vali (first_name, last_name, handphone)
VALUES (first_name, last_name, handphone)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
So as you can see, the first part is just the html and form.
The second part is where I used Jquery to validate (which works).
Now the issue is at the php part, where it sends the data to my database as empty.
The logic behind my php code is that, I take the values of the variables I set in Jquery and just update it to the database. But its updating empty values.
I tried to return false in Jquery, but its not working for me. May I know what am I doing wrong here?
Firsty, you have to understand JavaScript in this case is a client-scripting language and PHP is a server-scripting language. Variables can't be pass from JavaScript to PHP is the <script> tag.
Secondly, we have different types of requests; GET, POST, PUT, DELETE and so on. This we can check via PHP. A form can only send two types of request as at the time of me typing this answer, GET and POST request, this is the method value you set in your form. Every value set in a form can be accessed in the request global array and the name of the value being the key/indetifier. $_GET[] if you sent a get request and $_POST[] if you sent a post request.
In your form above, your method is set to POST, meaning all the values would be available in the global $_POST[].
When ever a page loads, the server script gets loaded first before the Client Side / HTML / CSS and other resources used by your document.
PHP has a function called isset() which is used to check if a variable available regardless it's value which is very useful for form validation.
If you ever have PHP codes in file performing logic/operations, it is advisable you placed them topmost of you file since it isn't used in rendering your document/view.
From your code, you should edit as
<?php
if(isset($_POST['submit'])){
// This block will only be executed when a submit button is triggered
//Make your connection here, it is not a must but good practice to always make connection first in order to make it available everywhere. Ensure to check if connection was successful or not.
$first_name = $_POST['first_name']; // this gives you the exact value you passed in the form.
...
// All you variables should be assigned using the above method
//in the above assignation of variables, we didn't sanitize. mysqli has a method real_escape_string() which does that for us. Ensure to always sanitize and properly validate inputs you send to your DB
//Sanitizing inputs
$first_name = $con ->real_escape_string($first_name);
// Do the above for other inputs, then you are good to perform an insert.
$result = $conn->query($sql);
if($result){
//Record has been inserted, you can choose to redirect or do some other logic
}else{
//Record was not successfully inserted. Print your error if in development to get an insight to what went wrong
}
}
$conn->close()
?>
This might be a stupid problem but i'm new to this (this is a homework ^^) and i can't find a solution :)
i have a .php file with an html form plus some php code to execute a query and insert the values from the form in my DB. And it works, but every time the page is loaded the php code is executed and this insert in the DB a "blank" line, because obviously the form was not filled yet. This is the code
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title></title>
</head>
<body>
<form action="myPage.php" method="post">
ID: <input type="text" name="id" /> <br />
<input type="submit" name="Submit" value="Go" /> <br />
</form>
<?php
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_close();
?>
</body>
</html>
Is there a way to execute the php code only once the "Go" button on the form is executed?
Try:
if(isset($_POST['Submit'])) {
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_query($query, $connessione);
mysql_close();
}
PHP will work before the page is rendered. You need to set up a condition to stop the PHP you don't want running until you submit the form.
if(isset($_POST['myform'])) {
// process the form
}else{
// html for form goes here
}
Hope that helps.
Assuming the form points to the script itself, there are numerous options :) Among others:
This first example just checks if a form was posted. If a normal (GET) request is received, it will do nothing, because it will not fall into your if-clause
// your form here
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// your php code
}
And this example checks if a variable with the name 'Submit' has been posted, and if so, if it has the value 'Go' in it. It is a slightly stricter check, but in your current example behaviour is exactly the same (so you can pretty much choose which one you like most ;))
// your form here
if(array_key_exists('Submit', $_POST) && $_POST['Submit'] == 'Go') {
// your php code
}
I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.
I have an HTML form(2 list-boxes and a check-box) which I want to use for filtering results on the page.
How can I make it so when I press the Submit button(.onclick(function(){})) it would execute a jQuery AJAX call to a PHP script on my local server that will, firstly, check if anything was selected in the list-boxes and if the check-box was checked and then based on that build a SQL statement to query my database and retrieve the result as JSON.
How would you do it, theoretically. I already have the PHP script to simply grab everything from my table and save it as JSON:
<?php
// databse connection info
require("dbinfo.inc.php");
// try to open a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// grab data about every campus and which instituion they belong to
$query = 'select statement to grab all the data from a table';
$result = mysql_query($query);
// check if $results has anything
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// time to start generating our huge XML
while ($row = #mysql_fetch_assoc($result)){
$finalarray[] = $row;
$main_arr['products'] = $finalarray;
}
// close connection to the database
mysql_close($connection);
// echo, save and write the file
// print json_encode($main_arr);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($main_arr));
fclose($fp);
?>
First send the data from the form with ajax:
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url : 'myPHPfile.php',
data: {form : $('form').serialize()}
}).done(function(data) {
var myJSONresult = data;
});
});
In your PHP file you'll get the form with
$form = $_POST['form'];
and there's no need to save to a file, just send it back by echoing
echo json_encode($main_arr);
Here is an example of posting to a php file and grabbing the data with ajax.
The result will get logged into the console.
I assume you know how to process the json with js once it has been retrieved?
//the php
<?php
//bla bla connect to database etc
//if form has been submitted with ajax
if(isset($_POST["ajax_request"])){
//build query
$id = $_POST["id"];
$fruit = $_POST["fruit"];
$query = "SELECT * FROM fruits WHERE id=$id AND fruit='$fruit'";
//fetch from db
$result = mysql_query($query);
//send out json
die(json_encode($result));
}
?>
//the jquery
<script type="text/javascript">
$(document).ready(function(){
//on submit
$("#ajaxForm").submit(function(e){
//stop default page refresh
e.preventDefault();
//define the form
var form = $(this);
//get the form data
var data = form.serialize();
//send it via ajax
$.ajax({
type : "post",
dataType : "json",
url : "url to your php here",
data : data+"&ajax_request=1",
success : function(json){
console.log(json);
},
error : function(a,b,c){
console.log(a,b,c);
}
});
});
});
</script>
//the html
<form id="ajaxForm" method="post" action="">
<input type="text" name="id" required="required" placeholder="enter id"/>
<input type="text" name="fruit" required="required" placeholder="enter fruit"/>
<input type="submit" name="submit"/>
</form>