Laravel SQL: Duplicate Insertion Into Table - php

I am working on a self-learning project to learn how to use Laravel 4. At this point, I have managed to get most of it to work, but the problem I run into is I get 2 entries in the database tables rather than 1.
I had an error before about a duplicate primary key value, and it still added two entries. I thought this error was the reason behind the duplicate values, but I have since fixed this error and this still happens.
I'm sorry if my code is really messy and unorganized. I will be reorganizing it at the end.
Here's my code (I can't submit images):
Thanks for the help!
File 1: views/customer/index.blade.php
#extends('layout')
<?php
$total = "";
$url = "";
function line_totals()
{
$qty = "";
$unit_price = "";
global $total;
$bool = isset($_GET['qty']) || isset($_GET['unit_price']);
if($bool)
{
$qty = $_GET['qty'];
$unit_price = $_GET['unit_price'];
}
$qty = str_replace("\n", '<br>', $qty);
$qty = str_replace("\n", '<br>', $qty);
$unit_price = str_replace("\n", '<br>', $unit_price);
$unit_price = str_replace("\n", '<br>', $unit_price);
$qtyArr = explode('<br>', $qty);
$priceArr = explode('<br>', $unit_price);
$total = array();
for($i = 0; $i < count($qtyArr); $i++)
{
$total[$i] = $qtyArr[$i] * $priceArr[$i];
}
return $total;
}
$total = json_encode(line_totals());
function insert_customer()
{
$customerIsFilled = isset($_GET['date']) || isset($_GET['receipt']) || isset($_GET['name']) || isset($_GET['address']) || isset($_GET['city']) || isset($_GET['state']) || isset($_GET['zip']);
if($customerIsFilled)
{
$id = "";
$name = $_GET['name'];
$address = $_GET['address'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$created_at = date('Y-m-d H:i:s');
$updated_at = date('Y-m-d H:i:s');
$insert_cust = array(
'id' => $id,
'name' => $name,
'address' => $address,
'city' => $city,
'state' => $state,
'zip' => $zip,
'created_at' => $created_at,
'updated_at' => $updated_at
);
DB::table('customer')->insert($insert_cust);
}
else
return;
}
function insert_work()
{
$curId = 0;
$select = DB::select('SELECT * FROM customer');
$ids = array();
for($i = 0; $i < count($select); $i++)
{
if(!empty($select))
{
$ids[$i] = DB::table('customer')->pluck('id');
$curId = max($ids);
}
}
$workIsFilled = isset($_GET['date']) || isset($_GET['receipt']) || isset($_GET['qty']) || isset($_GET['description']) || isset($_GET['unit_price']) || isset($_GET['line_total']) || isset($_GET['created_at']) || isset($_GET['updated_at']);
$line_total = "";
if($workIsFilled)
{
$cust_id = $curId;
$qty = htmlspecialchars($_GET['qty']);
$date = htmlspecialchars($_GET['date']);
$receipt = htmlspecialchars($_GET['receipt']);
$description = htmlspecialchars($_GET['description']);
$unit_price = htmlspecialchars($_GET['unit_price']);
$created_at = date('Y-m-d H:i:s');
$updated_at = date('Y-m-d H:i:s');
$tot = line_totals();
for($i = 0; $i < count($tot); $i++)
{
$line_total .= $tot[$i]."\n";
}
$insert_work = array(
'cust_id' => $cust_id,
'qty' => $qty,
'date' => $date,
'receipt' => $receipt,
'description' => $description,
'unit_price' => $unit_price,
'line_total' => $line_total,
'created_at' => $created_at,
'updated_at' => $updated_at
);
DB::table('work')->insert($insert_work);
}
else
return;
}
// Store HTTP GET request parameters into $url
$get = action('CustomerController#getResults', $url);
?>
#section('content')
<form action="{{ $url }}" method="get">
<table style="margin-left:250px;" cellspacing="5">
<tr>
<td> Name: </td> <td> <input name="name" id="name" type="text" value="John Doe"> </td>
<td> Address: </td> <td> <input name="address" id="address" type="text" value="Street Address"> </td>
<td> City: </td> <td> <input name="city" id="city" type="text" value="City"> </td>
<td> ST: </td> <td> <input name="state" id="state" size="2" maxlength="2" type="text" value="ST"> </td>
<td> Zip: </td> <td> <input name="zip" id="zip" type="text" value="12345"> </td>
</tr>
</table>
<br><br>
<h1 style="text-align:center;">Work Performed</h1>
<table style="margin-left:350px;" cellspacing="5">
<tr>
<td> Date: </td> <td> <input id="date" name="date" type="text" value="14-01-01"></td>
<td> Receipt#: </td> <td> <input name="receipt" value="9000"> </td>
</tr>
</table>
<table style="margin-left:350px;" cellspacing="5">
<tr>
<td> <textarea rows="1" placeholder="Qty" id="qty" name="qty">5<?php echo "\n"; ?>5</textarea> </td>
<td> <textarea rows="1" placeholder="Description" id="description" name="description">Job 1<?php echo "\n"; ?>Job 2</textarea> </td>
<td> <textarea rows="1" placeholder="Unit Price" id = "unit_price" name="unit_price">200<?php echo "\n"; ?>400</textarea> </td>
<td> <textarea rows="1" placeholder="Line Total" id="line_total" name="line_total" disabled></textarea> </td>
</tr>
</table>
<br>
<input style="margin-left:600px;" id="add" type="submit" value="Submit">
</form>
#stop
File 2: views/layout.blade.php
<!doctype html>
<html>
#section('header')
<head>
<title></title>
<style type="text/css">
#subHeading
{
display: block;
position: absolute;
font-style: italic;
font-weight: bold;
font-size: 25pt;
margin-top:-10px;
margin-left: 600px;
}
#qty, #description, #unit_price, #line_total
{
text-align: center;
}
</style>
<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui.min.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
</head>
<body>
<span id="subHeading">Invoice</span>
<br>
<hr
<br>
<script type="text/javascript">
$(function(){
$("#date").datepicker({
dateFormat:"y-mm-dd"
});
});
$(document).ready(function(){
if($("#name").val() != "" && $("#address").val() != "" && $("#city").val() != "" && $("#state").val() != "" && $("#zip").val() != "")
{
$("#add").on('click', function()
{
$.ajax({
url: 'customer/index.blade.php',
success: $(function(){
//alert("New Customer!");
<?php insert_customer();?>
})
});
});
}
else if($("#qty").val() != "" && $("#description").val() != "" && $("#unit_price").val() != "")
{
$("#add").on('click', function()
{
$.ajax({
url: 'customer/index.blade.php',
success: $(function(){
//alert("New Work Order Added!");
<?php insert_work(); ?>
})
});
});
}
$("#line_total").hide();
});
/* $.ajax({
url: 'index.blade.php',
success: $(function(data) {
// <?php insert_customer(); ?>
<?php insert_work(); ?>
});*/
</script>
#stop
#yield('header')
#yield('content')
</body>
</html>

Ok so the reason you're getting a double insert is the commented out javascript contains php functions that aren't commented out:
/* $.ajax({
url: 'index.blade.php',
success: $(function(data) {
// <?php insert_customer(); ?>
<?php insert_work(); ?>
});*/
While you've managed to comment out the javascript here, the php will still run. To successfully comment out the php you'd need to work within the php tags:
<?php // myFunction(); ?>
<?php /* myFunction(); */ ?>
From looking over your code it looks like you just need to work on your understanding of Javascript (a client side language) vs PHP (a server side language) which is no problem, that's what makes a learning project so valuable. Here's a bit of info you'll hopefully find useful:
1. PHP function calls in the page will be called on page load. Here's an example:
An example php file:
<?php
function myFunction(){
echo 'Hello World';
}
?>
<html>
<body>
<?php myFunction(); ?>
</body>
</html>
This will output the following html to the browser:
<html>
<body>
Hello World
</body>
</html>
So when you call your <?php insert_work(); ?> function in the page, it will run straight away on the page load and because it's in there twice you're getting duplicate calls of your function.
2. You can't directly call PHP functions from Javascript
This unfortunately wont work how you might want it to:
<?php
function myPhpFunction(){
// Insert into database on click
}
?>
<html>
<head>
<script>
$('.button').click(function(){
<?php myPhpFunction(); ?>
});
</script>
</head>
...
What actually happens here is the myPhpFunction() get's called on the page load. What you need is an ajax call which I can see you already have attached to your #add submit button. Here's a quick example using your code:
A brief version of your layout.blade.php
<html>
<head>
<script>
$("#add").on('click', function()
{
// Grab the form data
var data = $("form").serialize();
// Perform the ajax request
$.ajax({
// Call the route here not the file
url: '/customer',
data: data,
success: $(function(data){
// Add the returned data to the p tag
$("p").html(data);
})
});
});
</script>
</head>
<body>
<form action="{{ $url }}" method="get">
<input name="name" id="name" type="text" value="John Doe">
<textarea rows="1" placeholder="Description" id="description" name="description">
<input id="add" type="submit" value="Submit">
</form>
<p><!-- Your results will load here --></p>
</body>
</html>
A brief version of your customer/index.blade.php
<?php
function insert_customer(){
// Perform DB insert
echo 'Success! Customer added.';
}
// Call insert_customer()
insert_customer();
?>
Here when your button is clicked we grab the form data and send a ajax GET request to the customer/index route which performs the function and send us the feedback that the function has been successful.
Sorry that's such a lengthy answer. Hopefully it's helpful!

Related

Loading gif while Post files uploads to database

I am trying to prompt a loading gif while the POST data and Files are being uploaded to the database. I did a research online and I saw couple of examples with my same issue which was solved but when I tried for example this Ajax and Jquery code, it just loads the gif and it just keeps spinning. I don't know if there is another way to do it without using Ajax but just php.
Here is the Ajax code I tried just below my form
<div id="loader"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
var spinner = $('#loader');
$(function() {
$('form').submit(function(e) {
e.preventDefault();
spinner.show();
$.ajax({
url: 't2228.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON'
}).done(function(resp) {
spinner.hide();
alert(resp.status);
});
});
});
and the t2228.php file to call my php code
<?php
include '../lib/session.php';
Session::checkSession();
include '../config/config.php';
include '../lib/database.php';
include '../helpers/format.php';
$db = new Database();
$fm = new Format();
define("DOCROOT", filter_input(INPUT_SERVER, "DOCUMENT_ROOT", FILTER_SANITIZE_STRING));
$pet = new Pet();
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){
$addPet = $pet->petAdd($_POST, $_FILES);
}
?>
Here is the HTML Form
<form action="" method="post" enctype="multipart/form-data">
<table class="form">
<tr>
<td>
<label>Pet Name</label>
</td>
<td>
<input type="text" name="name" placeholder="Enter Pet Name..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Price</label>
</td>
<td>
<input type="text" name="price" placeholder="Enter Pet Price..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Serie</label>
</td>
<td>
<input type="text" name="serie" placeholder="Enter Pet Serie..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Sex</label>
</td>
<td>
<select id="select" name="sex">
<option>Select Pet Sex</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Pet Age</label>
</td>
<td>
<input type="text" name="age" placeholder="Enter Pet Age..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Upload Image</label>
</td>
<td>
<div class="post-image-collection">
<label id="list">
</label>
<label class="post-image post-image-placeholder mrm mts empty">
<input type="file" id="Photofile" name="images[]" required="required" multiple />
<span class="icon-camera"><img src="../img/608815-200.png"></span>
<p class="uppercase">Photo</p>
</label>
</div>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" Value="Add Pet" />
</td>
</tr>
</table>
</form>
Here is My PHP code
public function petAdd($data, $file){
$name = mysqli_real_escape_string($this->db->link, $data['name']);
$price = mysqli_real_escape_string($this->db->link, $data['price']);
$serie = mysqli_real_escape_string($this->db->link, $data['serie']);
$sex = mysqli_real_escape_string($this->db->link, $data['sex']);
$age = mysqli_real_escape_string($this->db->link, $data['age']);
foreach($file["images"]["tmp_name"] as $key=>$tmp_name)
{
$file_name = $file["images"]["name"][$key];
$file_size = $file["images"]["size"][$key];
$file_temp = $file["images"]["tmp_name"][$key];
$file_size_preview = $_FILES['preview']['size'];
$div = explode('.', $file_name);
$file_ext = strtolower(end($div));
$permited = array('jpg', 'jpeg', 'png', 'gif');
if($tmp_name == ""){
$msg = "<span class='error'>Fields must not be empty!</span>";
return $msg;
}
elseif ($file_size > 1048567 || $file_size_preview > 1048567) {
$msg = "<span class='error'>Image Size should be less then 1MB! </span>";
return $msg;
}
elseif (in_array($file_ext, $permited) === false) {
$msg = "<span class='error'>You can upload only:-".implode(', ', $permited)."</span>";
return $msg;
}
}
if($name == "" || $price == "" || $serie == "" || $sex == "" || $age == "") {
$msg = "<span class='error'>Fields must not be empty!</span>";
return $msg;
} else{
$query = "INSERT INTO pets(name, price, serie, sex, age, status, details, shipping, type) VALUES('$name','$price','$serie', '$sex', '$age','$status', '$details','$shipping','$type')";
$inserted_row = $this->db->insert($query);
$last_id = $this->db->link->insert_id;
foreach($file["images"]["tmp_name"] as $key=>$tmp_name)
{
$div = explode('.', $file_name);
$file_ext = strtolower(end($div));
$unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
$uploaded_image = "../uploads/".$unique_image;
$saveToFolder = DOCROOT . "/dallasfrenchies/uploads/$unique_image";
$saveToDatabase = "uploads/$unique_image";
move_uploaded_file($tmp_name, $saveToFolder);
$query = "INSERT INTO images(petId, path) VALUES('$last_id','$saveToDatabase')";
$this->db->insert($query);
sleep(3);
}
$msg = "<span class='success'> Your Pet has been added Successfully. </span>";
return $msg;
}
}
Any one with a suggestion on what to modify or add?
<div id="loader"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
var spinner = $('#loader');
$(function() {
$('form').submit(function(e) {
e.preventDefault();
spinner.show();
$.ajax({
url: 't2228.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON',
success: function(resp) {
spinner.hide();
alert(resp.status);
},
error: function(resp) {
spinner.hide();
alert(resp);
}
})
});
});
Rather than .done() i used the attributes for success and error
Try below code and make few changes in ajax code. Add below parameters in your code.
processData: false,
contentType: false,
And add var formData = new FormData($(this)); line before ajax starts.
Or Check below code and make changes according to you code.
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
var spinner = $('#loader');
var formData = new FormData($(this));
$.ajax({
url: 't2228.php',
type: "POST",
data: formData,
processData: false,
contentType: false,
beforeSend: function () {
spinner.show();
},
success: function (data)
{
spinner.hide();
},
error: function (resp) {
spinner.hide();
alert(resp);
}
});
});
</script>

How to show mobile no is already exits to particular row using angularjs

i'm working on a add & remove row to add multiple user at a time with mobile no validation/available (not in use) . Its working fine. But when the mobile no is already in use for only row, Message is showing for the other rows.
Here my code html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.9.0/ui-bootstrap-tpls.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="js/addmore.js"></script>
<script src="js/dirPagination.js"></script>
</head>
<body class="nav-md" data-ng-cloak data-ng-app="AddMoreModule" data-ng-controller="AddMoreController">
<form class="form-horizontal form-label-left" name="AddMoreForm" id="AddMoreForm" autocomplete="off" enctype="multipart/form-data" novalidate>
<div class="form-group">
<div class="col-lg-12 fade-in tada" style="padding: 10px 0px 0px 0px;">
<table ng-table="tableParams" class="display table table-striped table-bordered">
<thead>
<tr>
<th width="5%">Sr.No</th>
<th width="20%">Name</th>
<th width="20%">Mobile No</th>
<th width="25%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cap in data">
<td>{{$index+1}}</td>
<td data-title="'Name'" sortable="name">
<input type="text" class="form-control" id="name" data-ng-model="cap.name" placeholder="Name" required>
</td>
<td data-title="'Mobile No'" sortable="Mobile No">
<input type="text" class="form-control" id="mobno" maxlength="10" data-ng-model="cap.mobno" data-ng-change="get_mobno(cap.mobno)" placeholder="Mobile No" required>
<strong data-ng-show="mobnoerror" style="color:#FF0000;">{{MsgE}}</strong>
</td>
<td>
<input type="submit" data-ng-click="addNewForm()" class="btn btn-default" value="Add Items" />
<input type="submit" value="Remove" class="btn btn-primary" data-ng-click="removeNewRow(cap.name,cap.mobno)" />
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-success" data-ng-disabled="AddMoreForm.$invalid" data-ng-click="submitData()"/>Submit</button>
</div>
</div>
</form>
</body>
</html>
Here is the angularJS Script
var AddMore = angular.module('AddMoreModule',['angularUtils.directives.dirPagination','ui.bootstrap'])
AddMore.controller('AddMoreController', function ($scope, $http)
{
/*Add & Remove row script starts here*/
//to remove the row
$scope.removeNewRow = function(name,mobno)
{
var index = -1;
var comArr = eval( $scope.data);
for(var i = 0; i < comArr.length; i++)
{
if(comArr[i].name==name && comArr[i].mobno==mobno)
{
index = i;
break;
}
}
if(index===-1)
{
}
$scope.data.splice(index,1);
};
//Dynamic row creation
$scope.data = [{}];
$scope.addNewForm = function()
{
$scope.data.push({});
}
/*Add & Remove row script ends here*/
$scope.get_mobno = function(mobno)
{
$http.post('get_mobno.php', { 'mobno':mobno } )
.success(function (data, status, headers, config)
{
$scope.mobnoerror = false;
if(data!="OK")
{
$scope.mobnoerror = true;
$scope.MsgE = data;
}
else
{
$scope.mobnoerror = false;
}
});
};
$scope.submitData = function()
{
var comArr = eval( $scope.data);
var name = new Array();
var mobno = new Array();
for( var i = 0; i < comArr.length; i++ )
{
name.push(comArr[i].name);
mobno.push(comArr[i].mobno);
}
if($scope.AddMoreForm.$valid)
{
var answer = confirm("Do you want to Submit?")
if (!answer)
{
}
else
{
//insert code come here
alert("Data added successfully");
}
}
else
{
alert("All fields are mandatory");
$scope.AddMoreForm.submitted= true;
}
}
});
get_mobno.php shows Ok if Mobile No is available. Now i'm little confused how to show message only particular row?

duplicate page content after ajax to the same page

I have simple registration formulae and I want I want to firstly send with ajax and without refreshing the page to control if I insert correct data and then just redirect to some other page. The problem is that after I send it through ajax to the same page everything is working but content of my page is being duplicate, I can see it twice...
here is my ajax
function registruj () {
var name = $('#meno').val();
var priez = $('#priezvisko').val();
var log = $('#login').val();
var mail = $('#mail').val();
var cisloTel = $('#cislo').val();
var heslo = $('#heslo').val();
var heslo1 = $('#heslo1').val();
$.post( "", {
'meno': name,
'priezvisko': priez,
'login':log,
'mail':mail,
'cislo':cisloTel,
'heslo':heslo,
'heslo1':heslo1,
}, function (data) {
$('#result').html(data);
}
);
$('#nove').load(document.URL + ' #nove');
}
and this is my php file
<?php
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
}
?>
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8" />
<title>blblblbl</title>
<link rel="stylesheet" type="text/css" href="./fancybox/jquery.fancybox-1.3.4.css" media="screen" />
<script src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script>$(function(){$('.img').fancybox();});</script>
<style type="text/css"> </style>
<script type="text/javascript" src="mojskript.js"></script>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/style1.css" />
</head>
<body class="registracia">
<div class="container">
<div id="nove">
<form >
<table >
<tr><td><label for="napdis">Vyplňte nasledujúci formulár:</label></td></tr>
<tr><td><input type="radio" name="pohlavie" value="zena" id="zena" >Žena</td></tr>
<br>
<tr><td><input type="radio" name="pohlavie" value="muz" id="muz">Muž</td></tr>
<br>
<tr><td><label for="meno">Meno :</label></td><td><input type = "text" id="meno" name="meno"></td></tr><br>
<tr><td><label for="priezvisko">Priezvisko :</label></td><td><input type = "text" id="priezvisko" name="priezvisko"></td></tr><br>
<tr><td><label for="login">Login :</label></td>
<td><input type = "text" id="login" name="login"></td></tr><br>
<?php
if(isset($heslo)) {
if (($heslo != "" && $hesloZnovu != "") && ($heslo == $hesloZnovu)) {
$hesloOk = 1;
}
else {
echo '<tr><td><label for="heslo">Heslo :</label><td><input type = "password" name="heslo"></td><td><label for="zleHeslo">Heslá sa nezhodujú</label></td></tr>';
$pocet = 1;
}
}
?>
<?php
if(!isset($pocet)) {
echo'<tr ><td ><label for="heslo" > Heslo :</label ></td >
<td ><input type = "password" id="heslo" name = "heslo" ></td ></tr ><br >';
}
?>
<tr><td><label for="heslo2">Heslo znovu :</label></td>
<td><input type = "password" id="heslo1" name="heslo1"></td></tr><br>
<?php
if(isset($mail)) {
if (!stristr($mail, "#") OR !stristr($mail, ".")) {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" name="email"></td><td><label for="zlyMail">Zlý formát emailu</label></td></rd></tr><br>';
} else {
$mailOk = 1;
}
}
else {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" id="mail" name="email"></td></tr><br>';
}
?>
<tr><td><label for="cislo">Telefónne číslo :</label></td>
<td><input type = "text" id="cislo" name="cislo"></td></tr><br>
<tr><td><input type="button" value="Zaregistrovať" onclick="registruj()" ></td></tr>
</table>
</form>
<?php
if(isset($mailOk) && isset($hesloOk)) {
$length = 20;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$zasifrovane = crypt($heslo,$randomString);
echo $zasifrovane;
mysql_query("INSERT INTO uzivatelia (Meno,Priezvisko,Login,Heslo,mail,pohlavie,cislo) VALUES ('$meno','$priezvisko','$login','$zasifrovane','$mail','$pohlavie','$cislo')");
header("location:index.php");
}
?>
</div>
<div id="result"></div>
</div>
</body>
How should I do that ?
Try to use exit(); like :
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
exit();
}
Use exit(); or die(); when ajax processing done otherwise it will return all page content.
Change success function to:
function (data) {
$('#result').empty().html(data);
}

could not register device on demo server in GCM

I am trying push notification in android and I use GCM api for this I get error in mobile When I try to register to service "could not register device on demo server" How can I solve this problem?
My service Url is "http://192.168.2.71:8080/gcm_server_files/register.php";
public interface Config {
// CONSTANTS
static final String YOUR_SERVER_URL = "http://192.168.2.71:8080/gcm_server_files/register.php";
// YOUR_SERVER_URL : Server url where you have placed your server files
// Google project id
static final String GOOGLE_SENDER_ID = "788729020569"; // Place here your Google project id
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Android Example";
static final String DISPLAY_MESSAGE_ACTION =
"com.androidexample.gcm.DISPLAY_MESSAGE";
static final String EXTRA_MESSAGE = "message";
}
And this register.php file I get error that
Notice: Undefined index: name in C:\xampp\htdocs\register.php on line 7
Notice: Undefined index: email in C:\xampp\htdocs\register.php on line 8
Notice: Undefined index: regId in C:\xampp\htdocs\register.php on line 9
<?php
require_once('loader.php');
// return json response
$json = array();
$nameUser = $_POST["name"];
$nameEmail = $_POST["email"];
$gcmRegID = $_POST["regId"]; // GCM Registration ID got from device
/**
* Registering a user device in database
* Store reg id in users table
*/
if (isset($nameUser) && isset($nameEmail) && isset($gcmRegID)) {
// Store user details in db
$res = storeUser($nameUser, $nameEmail, $gcmRegID);
$registatoin_ids = array($gcmRegID);
$message = array("product" => "shirt");
$result = send_push_notification($registatoin_ids, $message);
echo $result;
} else {
// user details not found
}
?>
push script from service
<?php
require_once('loader.php');
$resultUsers = getAllUsers();
if ($resultUsers != false)
$NumOfUsers = mysql_num_rows($resultUsers);
else
$NumOfUsers = 0;
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_push_notification_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.push_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
h1{
font-family:Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
textarea{
float: left;
resize: none;
}
</style>
</head>
<body>
<table width="910" cellpadding="1" cellspacing="1" style="padding-left:10px;">
<tr>
<td align="left">
<h1>No of Devices Registered: <?php echo $NumOfUsers; ?></h1>
<hr/>
</td>
</tr>
<tr>
<td align="center">
<table width="100%" cellpadding="1" cellspacing="1" style="border:1px solid #CCC;" bgcolor="#f4f4f4">
<tr>
<?php
if ($NumOfUsers > 0) {
$i=1;
while ($rowUsers = mysql_fetch_array($resultUsers)) {
if($i%3==0)
print "</tr><tr><td colspan='2'> </td></tr><tr>";
?>
<td align="left">
<form id="<?php echo $rowUsers["id"] ?>" name="" method="post" onSubmit="return sendPushNotification('<?php echo $rowUsers["id"] ?>')">
<label><b>Name:</b> </label> <span><?php echo $rowUsers["name"] ?></span>
<div class="clear"></div>
<label><b>Email:</b></label> <span><?php echo $rowUsers["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="push_message" placeholder="Type push message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $rowUsers["gcm_regid"] ?>"/>
<input type="submit" value="Send Push Notification" onClick=""/>
</div>
</form>
</td>
<?php }
} else { ?>
<td>
User not exist.
</td>
<?php } ?>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Switch the ajax request type to POST
$.ajax({
url: "send_push_notification_message.php",
type: 'POST',
data: data,
...
And your form does not even have proper tags:
<input type="text" name="name" value="<?php echo $rowUsers["name"] ?>" />
<input type="text" name="email" value="<?php echo $rowUsers["email"] ?>" />

I need help finding out why my php form with a Jquery Validator which is not validating properly

I have a php form with a jquery validator script that is only validated two out of the four required fields. The two fields that are been validated are the name and the email although if you don't input anything - the error message says 'Alphabetic chars only' rather than 'Please enter your name". The design required that I put the name of each field as a placeholder in the form and I am not sure if this is why it is not working properly. To balance that out - I put the name of each field outside the form and then hid it with a css span class of display none but the script is still not picking it up. Any Suggestions?
<?php
function isRequestSet( $name ) {
if ( isset ( $_REQUEST[$name] ) ) {
return ( $_REQUEST[$name] != "" ) ;
}
return false;
}
$name = "";
if ( isRequestSet('name' ) ) {
$name = $_REQUEST['name'];
}
$number = "";
if ( isRequestSet('number') ) {
$number = $_REQUEST['number'];
}
$email = "";
if ( isRequestSet( 'email' ) ) {
$email = $_REQUEST['email'];
}
$postcode = "";
if ( isRequestSet('postcode' ) ) {
$location = $_REQEUST['postcode'];
}
$how_did_you_hear_about_us = array();
if ( isset( $_REQUEST['how_did_you_hear_about_us'] ) ) {
$how_did_you_hear_about_us = $_REQUEST['how_did_you_hear_about_us'];
}
$message = "";
if ( isRequestSet('message' ) ) {
$location = $_REQEUST['message'];
}
$apartment_price_range = array();
if ( isset( $_REQUEST['apartment_price_range'] ) ) {
$apartment_price_range = $_REQUEST['apartment_price_range'];
}
if ( ($name !="") && ($number != "") && ($email != "") && ($isspam !="yes") ) {
$to = 'name#email.com';
$from = $to;
$headers = 'From: ' . $to . "\n" .
'Reply-To: ' . $to . "\n";
$vars = array( 'name' , 'number' , 'email' , 'postcode' , 'message' ) ;
$message = "-----------\n" ;
foreach ( $vars as $v ) {
$value = $_REQUEST[$v];
$message .= "$v:\t$value\n";
}
$message .= "-----------\n" ;
$message .= "\nHow did you hear about us?:\n" ;
foreach ( $how_did_you_hear_about_us as $how_did_you_hear_about_us ) {
$message .= "$how_did_you_hear_about_us\n" ;
}
$message .= "-----------\n" ;
$message .= "\nApartment price range:\n" ;
foreach ( $apartment_price_range as $apartment_price_range ) {
$message .= "$apartment_price_range\n" ;
}
$subject = "From: $name <$email>";
mail( $to , $subject , $message , $headers, "-f $from" );
$confirm = true;
} else {
$confirm = false;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="css/graphite.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/graphitephone.css" rel="stylesheet" media="handheld, only screen and (max-device-width: 480px)" />
<script src="js/gen_validatorv4.js" type="text/javascript"></script>
<style>
span {display: none;}</style>
</head>
<body onload="javascript:preload">
<div id="container">
<div id="header"><img src="images/HomeBanner.jpg" width="900" height="162" border="0" />
<div id="ruler"></div><!--end header-->
<div id="nav">
<ul>
<li class="list1"><span class="none">STORY</span></li>
<li class="list2"><span class="none">APARTMENTS</span>
<ul>
<li class="list7"><span class="none">GALLERY</span></li>
<li class="list8"><span class="none">FLOORPLANS</span></li>
</ul>
</li>
<li class="list3"><span class="none">MEET THE LOCALS</span></li>
<li class="list4"><span class="none">MEET THE CREATORS</span></li>
<li class="list5"><span class="none">LOCATION</span></li>
<li class="current6"><span class="none">CONTACT</span></li>
</ul>
</div><!--end nav-->
<div id="main">
<div id="contactform">
<table width="250px" border="0" cellspacing="0px" cellpadding="0px">
<form name="myform" method="post" action="" />
<input type='hidden' name='submitted' value='yes' />
<tr>
<td colspan="2"><?php
if ($confirm ) {
echo "<p>Thank you for enquiry</p>
<p>We will contact you shortly to advise on apartment availability and pricing.<p>";
} else {
if (isRequestSet( 'submitted' ) && $_REQUEST['submitted'] == "yes" ) {
echo "Request not sent, please complete all required fields marked '*'.";
}
}
?></td>
</tr>
<tr>
<td colspan="2" valign="middle"><p><span>name</span><input type="text" name="name" placeholder="Name*" id="contact_name" /></p></td>
</tr>
<tr>
<td colspan="2" valign="middle">
<table width="250px" border="0" cellspacing="0px" cellpadding="0px">
<tr>
<td bgcolor="#FFF" valign="baseline" height="10px"><p><img src="images/spacer.gif" width="1" height="5" /><span>number</span><input type="text" name="number" placeholder="Contact Number*" id="contact_number" /></p></td>
<td width="8px" height="10px"><img src="images/spacer.gif" width="8" height="5" /></td>
<td bgcolor="#FFF" valign="baseline" height="10px"><p><img src="images/spacer.gif" width="1" height="5" /><span>postcode</span><input type="text" name="postcode" placeholder="Postcode*" id="contact_postcode" /></p></td>
</tr>
<tr><td><img src="images/spacer.gif" width="1" height="6" /></td></tr>
</table></td></tr>
<tr>
<td colspan="2" valign="middle"><p><span>email</span><input type="text" name="email" placeholder="Email*" id="contact_email" /></p></td>
</tr>
<tr>
<td colspan="2"><p><select name="how_did_you_hear_about_us[]" id="" class='select-box'>
<option label="How did you hear about us?" value="0">How did you hear about us?</option>
<option label="realestate.com.au" value="realestate.com.au">realestate.com.au</option>
<option label="domain.com.au" value="domain.com.au">domain.com.au</option>
<option label="the age" value="the age">the age</option>
<option label="the herald sun" value="the herald sun">the herald sun</option>
<option label="billboard" value="billboard">billboard</option>
<option label="bpmcorp.com.au" value="bpmcorp.com.au">bpmcorp.com.au</option>
<option label="google" value="google">google</option>
<option label="site signage" value="site signage">site signage</option>
<option label="other" value="other">other - please state in box below</option>
</select></p></td>
</tr>
<tr>
<td colspan="2"><p>
<textarea name="message" cols="33" style="background:#fff; border:0px;" placeholder="What would you like to know?"></textarea>
</p></td>
</tr>
<tr>
<td><p>Price?</p></td><td rowspan="4" valign="top" align="right"><input type="image" class="rollover" id="contact_submit" src="images/buttons/BTN_Submit.png" alt="Submit" width="72px" height="68px" border="0" hover="images/BTN_Submit_over.png" name="Submit" value="Login"></td>
</tr>
<tr>
<td valign="middle"><p><input name="apartment_price_range[]" type="checkbox" value="350k-400k" style="background:#F9DC31; color: #000000;" /> 350k-400k</p></td></tr>
<tr>
<td><p><input name="apartment_price_range[]" type="checkbox" value="450k-550k" background="#F9DC31" /> 450k-550k</p></td></tr>
<tr><td><p><input name="apartment_price_range[]" type="checkbox" value="550k+" background="#F9DC31" /> 550k+</p></td></tr>
</form>
<tr><td colspan="2"><p class="italics" style="font-size:10px;">* denotes a required field</p> </td>
</tr>
<tr>
<td colspan="2"></td></tr>
</table>
</div><!--end contact form-->
</div><!--end left-->
</div><!--end main-->
</div><!--end container-->
<script language="JavaScript" type="text/javascript"
xml:space="preserve">//<![CDATA[
//You should create the validator only after the definition of the HTML form
var frmvalidator = new Validator("myform");
frmvalidator.addValidation("name","req","Please enter your name");
frmvalidator.addValidation("name","alpha_s","Alphabetic chars only");
frmvalidator.addValidation("number","maxlen=50");
frmvalidator.addValidation("number","req");
frmvalidator.addValidation("number","numeric_s", "Numbers only");
frmvalidator.addValidation("postcode","maxlen=50");
frmvalidator.addValidation("postcode","req");
frmvalidator.addValidation("postcode","numeric_s", "Numbers only");
frmvalidator.addValidation("email","maxlen=50");
frmvalidator.addValidation("email","req");
frmvalidator.addValidation("email","email");
//]]></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
</script>
<script src="js/load.js" type="text/javascript"></script>
</body>
</html>
"Name" gets validates as "has content" as the javascript records a value of "Name*" from the placeholder text. (Follow through in line 1088 of gen_validatorv4.js - objValue has a value of the placeholder text).
Also, as the placeholder text has an asterisk, this is not an alpha numeric - so it fails that clause - hence you see the message you see.
So, you're right, the placeholders, when pumped into the INPUT as "values" must then be removed when you validate. You could probably do this with "form_submit_handler()" by saying "if the value is the same as the placeholder, remove hte value before processing... and restore afterwards"
Another option is that I'd suggest looking at the jQuery validator at http://bassistance.de/jquery-plugins/jquery-plugin-validation/ - it's better documented as you're already running jQuery. You'll have the same problem, though, but there are pre-validation and post-validation hooks you can use to adjust the values. Just switch based on if ($('#contact_name').val() == '[placeholderText]') { $('#contact_name').val(''); }
A bit fiddly, but if you MUST have field names inside inputs, then that's a solution. (There are also other solutions involving background graphics or semi-transparent input fields. None are perfect.)

Categories