i have a problem with my simple program in php that include an alert javascript.
This is the code:
<?php
function iva(){
$country='IT';
$vatnum=$_POST['n'];
$a="Work";
$b="NotWork";
$url='http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
}
if ($response != 'true'){
echo $b;
}
}
?>
<script>
function ivaz(){
alert("<?php iva() ?>");
}
</script>
<form method="post">
<input name="n" type="textarea" >
<input onclick="ivaz();" value="Validate" type="submit"> </input> </form>
My program take a value from input text box and pass the value to php script that return true or false in a javascript alert. The program work, but return previous value passed in input box.
Can someone help me to solve it?
Thanks guys.
No, it doesn't work that way. If you want to call a PHP function from Javascript without the page refreshing, you need an XMLHttpRequest.
Example:
<?php
// your php process when called by XMLHttpRequest
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vatnum = $_POST['n'];
$country='IT';
$a = "Work";
$b = "NotWork";
$url = 'http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
} else {
echo $b;
}
exit;
}
?>
<form method="post" id="form1">
<input name="n" type="text" id="n" />
<input value="Validate" type="submit">
</form>
<script type="text/javascript">
// when the form is submitted
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
var n = document.getElementById('n').value; // get the textbox value
var xmlhttp = new XMLHttpRequest();
var params = 'n=' + n;
var php_url = document.URL;
xmlhttp.open('POST', php_url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
alert(response); // alert the server response
}
}
xmlhttp.send(params);
});
</script>
Remove onclick="ivaz();" from input tag
You cannot run the php script without reloading the page as php is generated serverside and javascript runs clientside.
Related
PHP code
<?php
...
//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$findemail = [
"email" => $email,
"password" => $password,
];
$cursor = $collection->findOne($findemail);
if($cursor){
if($cursor['email'] == $email and $cursor['password'] == $password){
// I Know these two lines don't work but I want to show what I want to do
echo "success";
header('location: cms-view-products.html');
}
else {
echo "failed";
header('location: login.php');
}
}
?>
AND this is my HTML code
<?php include('demo2.php') ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="demo2.php" onsubmit="return false"; method="post">
Email: <input type="email" name="email" required >
name: <input type="password" name="password" required >
<button type='submit' onclick="loadContent()">Load</button>
</form>
<div id="ServerContent">
<p>Dynamically loaded content goes here</p>
</div>
<script>
function loadContent(){
var url = "demo2.php";
var email = document.getElementsByName('email').value;
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById("ServerContent").innerHTML = this.responseData;
}
else
alert("Error communicating with server");
}
var data = `JSON.stringify({
"email": "document.getElementsByName('email').value",
"name": "document.getElementsByName('name').value"
})`;
xhr.send(data);
}
</script>
</body>
</html>
I've currently tried to echo the message via JS, the specific element <p id=" feedback"></p>, nevertheless it doesn't work. With PHP the process works, nevertheless, I can't redirect users using headers. I've found $_SESSION could resolve this issue. However, my question is to use JS to open a pop-up and then redirect the user to x page?
I edited the post since comments advised me about using Ajax and so this is my first attempt. I can always achieve one of the two either redirect the user to x page or show an error massage. but I can't do both.
Also, I don't want to alert the massage, but to change HTML element dynamically.
Thanks guys for your time and comments.
I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.
Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.
I don't know how to use jquery yet, so please answer with plain javascript.
Here's events.php:
<script>
//show past events
function showPastEvents(str) {
document.getElementById('pastevents').style.display = "block";
document.getElementById('hideoldbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("pastevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pastevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pastevents.php?q="+str, true);
xhttp.send();
}
function hidePastEvents() {
document.getElementById('pastevents').style.display = "none";
document.getElementById('hideoldbutton').style.display = "none";
}
//show upcoming events
function showUpcomingEvents(str) {
document.getElementById('upcomingevents').style.display = "block";
document.getElementById('hidenewbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("upcomingevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("upcomingevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "upcomingevents.php?q="+str, true);
xhttp.send();
}
function hideUpcomingEvents() {
document.getElementById('upcomingevents').style.display = "none";
document.getElementById('hidenewbutton').style.display = "none";
}
</script>
<!-- page content -->
<div class="content">
<h6>Past events</h6>
<form name="postpastevents" action=""/>
<div id="pastevents"></div>
<input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>
<br>
<br>
<!-- ####### -->
<h6>Upcoming events</h6>
<form name="postupcomingevents" action=""/>
<div id="upcomingevents"></div>
<input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
Here is pastevents.php (it's the same code for upcomingevents.php):
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
$query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
$result = pg_query($query);
while ( $row = pg_fetch_assoc($result) ) {
$i = 0;
echo "<tr>"; //table row
foreach ($row as $key => $value) {
if ($i == 0) {
$eventname = $value;
}
if ($i == 1) {
$eventdate = $value;
}
$eventinfo = $value;
echo "<td>"; //1 column each loop
echo "$eventinfo";
if ($i == 1) {
echo date(" (l, F jS)", strtotime($eventdate));
}
echo "<br><br>";
echo "</td>";
$i++;
}
echo "<td>";//1 column while same event
?>
<div>
<form name="pasteventsurvey" action="pastevent-handle.php" method="post">
What did you think of the event?
<select name="pasteventopinion">
<option value="">(Choose one)</option>
<option value="good">Loved it!</option>
<option value="okay">Liked it</option>
<option value="bad">Needs improvement</option>
<option value="time">Time conflict</option>
<option value="NA">NA</option>
</select>
<input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
<input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
</form>
</div>
<?php
echo "</td>";
echo "</tr>"; //-table row
}
pg_close($conn);
?>
Here's pastevents-handle.php:
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));
echo "email is $idkey, eventname is $name, pastopinion is $opinion";
pg_close($conn);
?>
(I edited a bit for space, ignore anything that isn't vital)
It is illegal to have a form inside another form.
Remove the outer form and everything should work fine, except you have another problem with the code.
Sorry a newbie to PHP, I'm trying to do a curl form submit but want to keep the results after the first submit. These then display buttons and depending which button is clicked another submit displays the second values in a popup. Its passing the values to the popup correctly but I dont want the screen to be refreshed when the second submit is clicked.
Any pointers be appreciated
<?php session_start();
?>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<SCRIPT TYPE="text/javascript">
function popup(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, windowname, 'width=700,height=235,scrollbars=yes');
return false;
}
</SCRIPT>
<form action="index.php" method="post">
CHECK DOMAIN:
<input type="text" input name="checkDomain" value="<?php echo isset($_POST['checkDomain']) ? $_POST['checkDomain'] : '' ?>"/>
<button type="submit" value="Submit">Check</button>
<?php
$DomainArray = array("ie","com","net");
//IF WE WANT TO PARSE XML RESPONSE
function produce_XML_object_tree($raw_XML) {
libxml_use_internal_errors(true);
try {
$xmlTree = new SimpleXMLElement($raw_XML);
} catch (Exception $e) {
// Something went wrong.
$error_message = 'SimpleXMLElement threw an exception.';
foreach(libxml_get_errors() as $error_line) {
$error_message .= "\t" . $error_line->message;
}
trigger_error($error_message);
return false;
}
return $xmlTree;
}
if(!empty($_POST)) {}{
if(!empty($_POST["checkDomain"])) {
$checkDomain = $_POST["checkDomain"];
if(!empty($_POST["form2-submit"])) {
$whoIs = $_POST['form2-submit'];
}
if ($checkDomain !=null || $whoIs !=null)
{
//Check if a TLD has been entered
if (strpos($checkDomain, '.') !== FALSE)
{
$domain = substr($checkDomain, 0, strpos($checkDomain, "."));
$DomainList = substr($checkDomain, strpos($checkDomain, ".")+1);
$url = 'check1';
}
else if (!empty($_POST['form2-submit'])) {
$WhoisDomain = $DomainArray[$whoIs-1];
$url = 'check2';
}
else{
echo ' Checking all domains:';
$DomainList = implode(",",$DomainArray);
$url = 'check3';
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($ch);
curl_close($ch);
$cont = produce_XML_object_tree($xml);
}
$_SESSION["otherXML"] =$xml;
foreach( $cont->Domain as $domain){
print '<br/>'.(string)$domain;
}
$index = 0;
foreach( $cont->RRPText as $rRPText ){
$index++;
print '<br/>'.(string)$rRPText;
//echo 'index'.$index;
if ($rRPText == "Domain not available")
{
print ' <button type="submit" name="form2-submit" onclick="popup(\'popup.php\')" value="'.$index.'">whois </button> ';
}
}
}
?>
</form>
</body>
</html>
If you don't want the page to be refreshed you should make an AJAX call.
To make life easier you could use jQuery's POST .
I've being trying to use httpRequest to do it async but there nothing being returned? API says return can be Text, HTML, or XML. I've tried them all.
<SCRIPT TYPE="text/javascript">
function httpGetAsync()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "URL....", true);
xmlHttp.send( null );
alert(xmlHttp);
alert(xmlHttp.responseText);
return xmlHttp.responseText;
}
</SCRIPT>
i have tried this code:
<script type="text/javascript">
var s = 0;
document.getElementById('text').value = "<?php echo phpVal[s];?>";
</script>
the problem is how can i put the (s) value into (PHP) code.
Here's more context:
<head>
<?php $s = ["a","b","c"]; ?>
<script type="text/javascript">
function doFun(ss){
var data = "<?php echo json_encode($s); ?>";
document.getElementById('t').value = s[ss];
}
</script>
</head>
<body>
<input type="text" id="t" name="t" />
<button type="button" id="b" name="b" onclick="doFun(0)">doFun</button>
</body>
You can't, by the time s has a value (on the client), the PHP code (on the server) has long-since completed.
What you do instead depends a lot on what your end goal is. You have a lot of options. Here are two of them:
Output the entire phpVal array/object to the client, and then index into it with s.
var s = 0;
var data = <?php echo json_encode(phpVal)%>;
document.getElementById('text').value = data[s];
Send s to the server via ajax, have the PHP code that runs in response to that request pick out the correct value from phpVal, and return that as the result of the ajax, putting it in the client-side input's value. For example:
JavaScript:
var s = 0;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('text').value = xhr.responseText;
}
};
xhr.open("get-value.php?s=" + encodeURIComponent(s));
// You don't really need this ^
// for `0`, but many times when sending variables to the
// server, you do
xhr.send();
PHP for get-value.php (roughly):
<?php
header('Content-Type: text/plain');
$phpVal = /*...get the value however it is you do that...*/
echo $phpVal[$_GET['s']];
?>
But again it depends on what you're actually trying to do.
I have an HTML form in which I have to upload 3 files.
I have to call a create.js script after form submission which uses getElementById to format the input in desired way. Then it uses a xmlHTTPRequest to call create.php which inserts the form data into mysql database, and in the mean time fetches some data that it sends back to create.js using json_encode.
So I don't use the form action attribute but instead use the onClick attribute on my Submit button to call create.js.
But I have to upload my 3 files also on clicking Submit. I tried using $_FILE['file1']['name'] and other $_FILE[][] variables, where I use <input type="file" name="file1" id="file1"> to uplaod my first file but it gave the following error:
Undefined index: file1 in C:\xampp\htdocs\mywebsite\sites\all\themes\danland\create.php on line 77
So how can I incorporate my code for storing uploaded files on my server in the same php that returns xmlhttp.responseText to my .js file ?
I also tried putting my code of uploading in upload.php and called it using <form action="the/correct/path/upload.php"> besides using onClick = "my_create.js_function()" in my submit button but it did not work
Note that I have read html upload using ajax and php and know that I cannot upload my file using xmlhttprequest, but I am not trying to do that. I want my xmlhttprequest to fetch data after submit is clicked and my submit button to also store my files.
My HTML form is:
<script src="http://localhost/mywebsite/sites/all/themes/danland/src/create.js">
</script>
<script type="text/javascript" src="http://localhost/mywebsite/sites/all/themes/danland/src/datepickr.js"></script>
<script>
window.onload = create_new_project_getoptions();
</script>
<div class="searchinterfacecontainer">
<p id="my_first_para"></p>
<p id="this_is_my_new_para"></p>
<h2>Enter Details</h2>
<form id="create_projectform1" name="create_projectform1" method="POST" enctype="multipart/form-data" action="http://localhost/mywebsite/sites/all/themes/danland/create_new_project_upload.php">
<input type="text" name="project_id" id="project_id" required/>
<input type="text" name="project_name" id="project_name" required/>
<input id="project_start_date" onClick="new datepickr('project_start_date')" required/>
<select id="project_geography" name="project_geography">
<option value="">Select Country </option>
</select><br/>
<input type="file" name="file1" id="file1">
<input type="file" name="file2" id="file2">
<input type="file" name="file3" id="file3">
<div class="searchinterfacebuttons"><input type="submit" class="searchinterfaceform1go" value="Search" onClick="create_new_project()"/> <button class="searchinterfaceform1go" type="reset" value="Reset"> Reset </button></div>
</form>
</div>
My create.js:
function create_new_project( )
{
alert("entered");
var project_id = document.getElementById("project_id").value;
var project_name = document.getElementById("project_name").value;
var project_start_date = document.getElementById("project_start_date").value;
// some more getElementByID
var error_para = document.getElementById("my_first_para");
var my_error = "";
error_para.innerHTML = my_error;
// some string manipulation with the above defined variables
project_start_date = date_fixer(project_start_date);
project_completion_date = date_fixer(project_completion_date);
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "project_id=" + project_id + "&project_name=" + project_name ; // + some more parameters
var url = "http://localhost/mywebsite/sites/all/themes/danland/create.php";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var val = xmlhttp.responseText;
//alert(val);
var jsonData = JSON.parse(val);
// some manipulation with json data
var answer = document.getElementById("this_is_my_new_para");
answer.innerHTML = jsonData;
}
}
xmlhttp.send(params);
}
function date_fixer(my_date)
{
// code here that works fine
}
My create.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'this_user');
define('DB_PASSWORD', 'this_password');
define('DB_DATABASE', 'mywebsite');
$project_id = $_POST["project_id"];
$project_name = $_POST["project_name"];
$project_start_date = $_POST["project_start_date"];
// some more $_POST[]
$date_status1 = date_fixer($project_start_date);
$date_status2 = date_fixer($project_completion_date);
//echo "date status 1 is $date_status1 and date_status2 is $date_status2";
if ( $date_status1 == -1 || $date_status2 == -1 ) // not a valid date
{
echo "The date was not in correct format. Please use the date picker";
}
else
{
try
{
$db = new PDO('mysql:host=' .DB_SERVER . ';dbname=' . DB_DATABASE . ';charset=utf8', DB_USERNAME, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query_geography = "INSERT into " . DB_TABLE . "( projectID, project_name, start_date) values ( (:pid), (:pname), (:sdate))";
$parameters1 = array(':pid'=>$project_id, ':pname'=>$project_name, ':sdate'=>$project_start_date);
$statement1 = $db->prepare($query_geography);
$statement1->execute($parameters1);
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
}
function date_fixer($my_date)
{
// valid function that works fine
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
print_r($temp);
print_r($extension);
if ( ( ($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/jpg") || ($_FILES["file1"]["type"] == "image/pjpeg") || ($_FILES["file1"]["type"] == "image/x-png") || ($_FILES["file1"]["type"] == "image/png") ) && ($_FILES["file1"]["size"] < 20000) && in_array($extension, $allowedExts) )
{
if ($_FILES["file1"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file1"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file1"]["name"] . "<br>";
echo "Type: " . $_FILES["file1"]["type"] . "<br>";
echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file1"]["name"]))
{
echo $_FILES["file1"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file1"]["tmp_name"], "upload/" . $_FILES["project_file1"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["project_file1"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
to get values from $_FILE you have to set form enctype to multipart/form-data.
if you want to read the value of file field then in jQuery simply write $('#id_filefield').val();