Same structure, but Ajax success response acts differently from previous version - javascript

Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"&region="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?

The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..

You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().

Related

Ajax : function is not working

I don't know why my code does not work onclick, but there is no pop up. The AJAX function var phone and id got data, but the AJAX did not. Is there anything wrong with the script? Does the AJAX need a jQuery library?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript">
function clickButton() {
var phone = document.getElementById('phone').value;
var id = document.getElementById('id').value;
$.ajax({
type: "post",
url: "userDetaiAjax.php",
data: {
'phone': phone,
'id': id
},
cache: false,
success: function(html) {
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
<div class="col">
<div class="form-group">
<h6>
<label>Name :</label>
<?php echo $name ?>
</h6>
<h6>
<label>Email :</label>
<?php echo $email ?>
</h6>
<input type="" name="phone" id="phone">
<input type="" name="id" id="id" value="<?php echo $_SESSION[" staff_id "];?>" hidden>
<h6>
<label>Phone :</label>
<?php echo $phone ?>
</h6>
<input type="submit" name="aa" value="submit2" onclick="return clickButton();">
</form>
<p id="msg"></p>
</div>
</div>
</div>
</div>
for the url
<?php
$phone = $_POST['phone'];
$id = $_POST['id'];
echo 'success';
echo $phone;
echo $id;
$a='"USR_ID"';
$b='"phone"';
include 'conn.php';
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query = "update usr_web SET phone=:c1 WHERE usr_id=:c2";
$stid = oci_parse($conn, $query);
oci_bind_by_name($stid, ":c1", $phone);
oci_bind_by_name($stid, ":c2", $id);
$result = oci_execute($stid);
oci_free_statement($stid);
oci_commit($conn);
oci_close($conn);
echo $result;
?>
When you open the console of your browser you should see an error message like "ReferenceError: $ is not defined". So it seems that $ is not part of core.js which you have loaded. Just load the full version (https://code.jquery.com/jquery-3.3.1.min.js) and it should work.
U have error in your console:
$ is not defined
Which mean u did not include jquery, so u should add this code after ajax include:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
U can chack your console errors with F12 key in browser and tab Console.

Email input is not taking email address as valid input in newsletter subscribe box

I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.

How to Update/Edit data in database with AngularJS

Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.

Can I remove "&& isset" in a php form

I have got the following form to work using PHP and JavaScript to validate...
The problem is, each time I want to update the inputs in the form I need to also update the && isset and $input = $_REQUEST['input name']; in the PHP! Are these important? there is no way to make the whole process easier?! please advise
PHP:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_REQUEST['name'])
&& isset($_REQUEST['email'])
&& isset($_REQUEST['message'])
&& isset($_REQUEST['number'])
&& isset($_REQUEST['date'])
&& isset($_REQUEST['select'])
&& isset($_REQUEST['radio'])
&& isset($_REQUEST['checkbox'])
&& isset($_REQUEST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$to = "";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
number: $number<br/>
date: $date<br/>
select: $select<br/>
radio: $radio<br/>
checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = (mail($to, $subject, $message, $headers));
if( isset($_REQUEST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
HTML Form:
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form id="contactForm" name="contactForm" action="contact.php" method="post">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" class="required" autocomplete="off">
</div>
<div class="email-address">
<p>Email Address</p>
<input name="email" class="required email" autocomplete="off">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" rows="5" class="required min3"></textarea>
</div>
<div class="number">
<p>Phone Number</p>
<input name="number" class="number" autocomplete="off">
</div>
<div class="date">
<p>Date <small>(dd/mm/yyyy)</small></p>
<input name="date" class="required date calendar" autocomplete="off">
</div>
<div class="dropdown">
<select name="select" class="required">
<option value="">Select</option>
<option value="DropdownA">DropdownA</option>
<option value="DropdownB">DropdownB</option>
</select>
</div>
<div class="radio">
<p>Radios:</p>
<label><input name="radio" type="radio" value="male" class="required">Male</label>
<label><input name="radio" type="radio" value="female" class="required">Female</label>
</div>
<div class="checkbox">
<p>Checkboxs:</p>
<label><input name="checkbox" type="checkbox" value="OptionA" class="required">Option A</label>
<label><input name="checkbox" type="checkbox" value="OptionB" class="required">Option B</label>
</div>
<div>
<p></p>
<input name="" class="required number spamcheck">
</div>
<button id="submit" type="submit">Send</button>
</form>
You do need to check if variables are set, before using them. Otherwise your script will raise errors for undefined variables. E.g. You each time will try to check if $_SESSION['token'] != $_POST['token'] but it will give you errors, because there's no form submitted (or however the request is sent) with token name, that's why you do need to check it before that.
Anyway, for multiple isset() you can use a comma separator
if(isset($var, $var2, $var3...))
instead of
if(isset($var) && isset($var2)...))
Also,, if you session token is not initialized too (completely new request to the page), and no request is send to it, your if() statement will return false, thus triggering the mail() function. So, in you particular case it's more than necessary to have a check before using them in mail form.
Yes. They are important. Lots of ways to make the process easier though. You might want to look at a simple framework like Symfony (the forms component can be used independently of the whole framework).
Be aware that you'll probably get a massive amount of spam with that form. Add a captcha like reCaptcha.
Yes, the validation is important but you can simplify your code. I would use an array to define the required fields. It's easy to maintain and much less code.
$requiredFields = array('name', 'email', 'message', 'number');
$valid = true;
foreach ($requiredFields as $field) {
if (!isset($_REQUEST[$field])) {
$valid = false;
break;
}
}
if ($valid) {
// Do the stuff
} else {
echo "Form data error!";
}
If you want to check if the current field actually contains something add empty() to the condition:
if (!isset($_REQUEST[$field]) || empty($_REQUEST[$field])) {
I think the second part where you assign the post values to separate variables is actually unnecessary in this case.

How to get a msgbox?

I am creating a simple enquiry form with upload option.
If I click submit button it goes to another page and displays success message but it should come in the same page as a message box. What should I do?
Here is my Html code:
<ul>
<li><span>Name</span>
<input name="name" type="text" size="25" class="text1" />
</li>
<li><span>Contact</span>
<input name="contact" type="text" size="25" class="text2" />
</li>
<li><span>E-mail</span>
<input name="email" type="text" size="25" class="text3" />
</li>
<li><span>Subject</span>
<input name="subject" type="text" size="25" class="text4" />
</li>
<li><span>Message</span>
<textarea name="message" size="250" class="text5"></textarea>
</li>
</ul>
<label for="upload"></label>
<div class="x">
<input type="file" name="upload" id="file" class="button">
</div>
<div class="x1">
<input type="submit" name="submit" value="Submit" class="button" />
</div>
And this is my PHP code for uploading and inserting:
<?php
$target = "upload/";
$target = $target . basename($_FILES['upload']['name']);
$ok = 1;
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target))
{
echo "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
<?php
include ("conn.php");
if (isset($_POST['submit']))
{
$sql="insert into cform (name,contact,email,subject,message,upload)values('".$_POST['name']."','".$_POST['contact']."','".$_ POST['email']."','".$_POST['subject']."','".$_POST['message']."','$target')";
$result=mysql_query($sql);
if (!$result)
{
echo "could not enter data";
}
else
{
echo "successfuly entered";
}
}
?>
This PHP page has to run in background and when I click the submit button a message box should display success.
Edit the echo portion of the page as
second page
$rspnse = "";
if(!$result){
$rspnse = "Error";
}
else{
$rspnse = "Success";
}
header('Location: previous_page.php?response='.$rspnse);
Replace the previous_page.php with your original url of the first page
first page
<?php
if(isset($_GET['response'])){
?>
<script>
alert('<?php echo $_GET['response'] ?>');
</script>
<?php
}
?>
Hope this helps...
if(! $result) {
$msg = "could not enter data";
}else{
$msg = "successfuly entered";
}
header('Location: http://www.example.com/form.php?message=$msg');
//Redirect to form page with set message.
add script in form page to display message
if(isset($_GET['message'])){
print $_GET['message'];
}
This solution for as per your code
And another option is using ajax.

Categories

Resources