AJAX onkeyup event trigger in php code - javascript

I am a newbie in AJAX script and javascript. I am using AJAX to get search suggestion when the user type the first letter in the search box. But after typing the AJAX and javascript code, I could not get any suggestion coming out below the search box. I wonder if someone could help me to fix this problem?
By the way, I hope that the suggestion limit would be 5. How can I do this?
Code for index.php:
<html>
<head>
<title>
Brandon's Search Engine
</title>
<style type="text/css">
#suggestion {
border: 1px solid black;
visibility: hidden;
}
#suggestion a {
font-size: 12pt;
color: black;
text-decoration: none;
display: block;
width: 450px;
height: auto;
}
#suggestion a:hover {
background-color: #dddddd;
}
</style>
</head>
<script type="text/javascript">
function getSuggestion(q) {
var ajax;
if(window.XMLHttpRequest)//for ie7+, FF, Chrome
ajax = new XMLHttpRequest();//ajax object
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
ajax.onreadystatechange = function {
if(ajax.status == 200 && ajax.readyState == 4) {
document.getElementById("suggestion").innerHTML = ajax.responseText;
}
}
ajax.open("GET", "suggestion.php?q=$query" + q, false);
ajax.send();
}
</script>
<body>
<form method="GET" action="search.php">
<input type="hidden" name="page" value="0" />
<table align="center">
<tr>
<td>
<h1><center>Brandon's Search Engine</center></h1>
</td>
</tr>
<tr>
<td align="center">
<input type="text" name="q" size="90"
onkeyup="getSuggestion(q)" autocomplete="off" />
</td>
</tr>
<tr>
<td align="center">
<input type="submit" value="Search" />
<input type="reset" value="Clear" />
</td>
</tr>
</table>
</form>
<div id="suggestion" size="90">
</div>
</body>
</html>
Code for suggestion.php:
<?php
include 'connect.php'; //connect with database
$query = $_GET["q"];
if($query != "")
{
$stmt = "SELECT * FROM searchengine WHERE title LIKE '%" . mysqli_real_escape_string($con,$query) . "%' OR link LIKE '%" . mysqli_real_escape_string($con,$query) . "%' LIMIT 0 , 10";
$result = mysqli_query($con,$stmt) or die(mysqli_error($con));
$number_of_result = mysqli_num_rows($result);
if ($number_of_result < 1) {
echo "Your search did not match any documents. Please try different keywords.";
} else {
//results found here and display them
while ($row = mysqli_fetch_assoc($result))//show first 10 results
$title = $row["title"];
$link = $row["link"];
echo "<div id='sugg-search-result'>";
echo "<a href='$link' id='sugg-title'>" . $title . "</a>";
echo "</div>";
}
}
?>
Thanks in advance.

Your missing php delimiter's here.
Change this:
ajax.open("GET", "suggestion.php?q=$query" + q, false);
To:
ajax.open("GET", "suggestion.php?q=<?php echo $query;?>"+q, false);
Updated answer:
In the keyup function, the parameter your passing is incorrect.
<input type="text" name="q" size="90" onkeyup="getSuggestion(q)" autocomplete="off" />
Instead pass the value what has been typed:
<input type="text" name="q" size="90" onkeyup="getSuggestion(this.value)" autocomplete="off" />
Change this:
ajax.open("GET", "suggestion.php?q=$query" + q, false);
To:
ajax.open("GET", "suggestion.php?q="+q, false);
jQuery ajax:
function getSuggestion(q){
$.ajax({
type: "GET",
url: "suggestion.php",
data: {item:q},
success:function(data){
alert(data);
$("#suggestion").html(data);
}
});
}
suggestion.php:
$value = $_GET['item'];
// enter the query here and echo the results
Note: Do not forget to include jQuery library.

Let's start with this:
// some common external JavaScript - learn now - common.js
//<![CDATA[
var doc = document, bod = doc.body;
var IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function E(e){
return doc.getElementById(e);
}
//]]>
// this page external JavaScript - thispage.js
//<![CDATA[
var q = E(q);
function getSuggestion(){
var xhr = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
E('suggestion').innerHTML = xhr.responseText;
}
}
xhr.open('GET', 'suggestion.php?q='+q.value, false);
xhr.send();
}
q.onkeyup = getSuggestion;
//]]>
Now your HTML:
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>
Brandon's Search Engine
</title>
<style type='text/css'>
#import 'external.css';
</style>
</head>
<body class='njs'>
<form method='GET' action='search.php'>
<input type='hidden' name='page' value='0' />
<table align='center'>
<tr>
<td>
<h1><center>Brandon's Search Engine</center></h1>
</td>
</tr>
<tr>
<td align="center">
<input type='text' name='q' id='q' maxlength='90' autocomplete='off' />
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Search' />
<input type='reset' value='Clear' />
</td>
</tr>
</table>
</form>
<div id='suggestion'></div>
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='thispage.js'></script>
</body>
</html>

Related

My Post methot in my PHP file and AJAX not working

I have the following problem, I am trying to use JQUERY and AJAX, but when I use the Post method, it does not post to the php file. I get an error undefined array key I know there are many more threads with this question, I've searched them all, watched a lot of tutorials, but nothing helps. The mistake remains. The weirdest thing is when I do a success check to see the value it shows the correct value. My source code is:
SevenTops_Test3.php
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Seven Tops Plovdiv</title>
<link rel="stylesheet" type="text/css" href="Style/mystyle2.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="Script/MyScript2.js"></script>
<script src="jquery-3.6.3.js"></script>
<script src="Raion.js"></script>
<script>
$(document).ready(function () {
$("#Raion").change(function () {
var x = $(this).val();
alert(x),
$.ajax({
url: 'fresh_db_raion3.php',
type: 'POST',
data: { raion : x },
success: function (data) {
alert(x);
// Stuff
},
error: function (data) {
alert("Not Ok");
// Stuff
}
});
});
});
</script>
<script>
$(document).ready(function () {
$("#Query").click(function () {
var x = 5;
alert(x);
$("#lists").load("fresh_db_raion3.php", { raion : x});
});
});
</script>
</head>
<body>
<?php
include 'db_connection_string.php';
include 'fresh_db_raion3.php';
?>
<div id="Top_Button">
<table>
<tr>
<td>
<input type="submit" class="Submit" id="Query" name="query" value="Заявка">
</td>
<td>
<input type="submit" class="Submit" id="Read" value="Преглед" />
</td>
<td>
<input type="submit" class="Submit" id="Delete" value="Изтрий" />
</td>
<td>
<button type="submit" class="Submit" id="Menu">
<img src="Picture/Menu.png" id="Menu_Img" />
</button>
</td>
</tr>
</table>
</div>
<hr />
<div>
<select id="Raion" name="raion" >;
<option selected disabled> Избор</option>
<?php
all_raion();
?>
</select>
</div>
<div id="lists" style="overflow:scroll;">
<?php
db_klient();
?>
</div>
<div id="Down_Control">
<table>
<tr>
<td>
<input type="number" id="number" />
</td>
<td>
<input class="label_down" id="label_down1" value="%" readonly>
</td>
<td>
<input type="checkbox" class="Submit" id="check" />
</td>
<td>
<input type="button" value="Запиши" class="Submit" id="Down_Btn_Insert" />
</td>
<td>
<textarea id="label_down2" readonly>кашон/стек</textarea>
</td>
<td>
<input type="checkbox" class="Submit" id="check1" />
</td>
</tr>
</table>
</div>
</body>
</html>
fresh_db_raion3.php
<?php
include "db_connection_string.php";
$getraion = $_POST['raion'];
echo $getraion;
function all_raion(){
$result_raion = $GLOBALS['db']->query('SELECT * FROM Raion');
$rowas_raion = $result_raion->fetchAll(PDO::FETCH_ASSOC);
foreach ($rowas_raion as $GLOBALS_k => $v)
{
echo '<option value=' . $GLOBALS_k . '>' . $v['Raion_Name'] . '</option>';
}
}
function db_klient(){
print_r( $GLOBALS['getraion']);
echo '<br>';
$result_klient = $GLOBALS['db']->query("SELECT* FROM Klient WHERE Raion_ID=". $GLOBALS['getraion']);
$row_klient = $result_klient->fetchAll(PDO::FETCH_ASSOC);
foreach ($row_klient as $kk => $vv)
{
echo '<input type=radio value=' . $vv['Klient_Name'] . ' name = klient_name>
<label>'. $vv['Klient_Name'] . '</label><br>';
}
}
I know the code must be very lame, but I'm very new..
And the database schema is this:
Raion CREATE TABLE "Raion"("Raion_ID" INTEGER PRIMARY KEY, "Raion_Name" TEXT NOT NULL)
Kategorii CREATE TABLE "Kategorii" ( "Kategorii_ID" INTEGER PRIMARY KEY, "Kategorii_Name" TEXT NOT NULL)
Stoki CREATE TABLE "Stoki" ( "Stoki_ID" INTEGER PRIMARY KEY, "Kategorii_ID" INTEGER NOT NULL, "Stoki_Name" TEXT NOT NULL)
Klient CREATE TABLE "Klient" ("Klient_ID" INTEGER PRIMARY KEY, "Raion_ID" INTEGER NOT NULL, "Klient_Name" TEXT NOT NULL)
youtube tutorials, answers in various topics in here in the forum

How to add new data into XML

register.htm
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<script type="text/javascript" src="shoponline.js"></script>
<title>ShopOnline Register Page</title>
</head>
<body>
<H3>ShopOnline</H3>
<table width="100%">
<tr>
<td><button class="button" name="btnHome" value="Home" onclick="location.href='login.htm';">Home</button></td>
<td><button class="button" name="btnListing" value="Listing" onclick="location.href='listing.htm';">Listing</button></td>
<td><button class="button" name="btnBidding" value="Bidding" onclick="location.href='bidding.htm';">Bidding</button></td>
<td><button class="button" name="btnMaintenance" value="Maintenance" onclick="location.href='maintenance.htm';">Maintenance</button></td>
<td><button class="button" name="btnLogout" value="Logout" onclick="location.href='#';">Log Out</button></td>
</tr>
</table>
<hr><br><br>
<I>To register a new account with ShipOnline, please complete the registration form below.</I>
<br><br>
<form>
<div class="form">
<fieldset>
<legend>Registration Details</legend>
<p style="text-align:left;">* Required Fields</p>
<br>
<table>
<tr>
<td style="text-align:right;">First Name <label>*</label></td>
<td><input type="text" id="txtFName" name="txtFName" class="textbox" placeholder="Enter Your First Name"
oninvalid="this.setCustomValidity('Please Enter Your First Name!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td style="text-align:right;">Surname <label>*</label></td>
<td><input type="text" id="txtSurname" name="txtSurname" class="textbox" placeholder="Enter Your Surname"
oninvalid="this.setCustomValidity('Please Enter Your Surname!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td style="text-align:right;">Email <label>*</label></td>
<td><input type="email" id="txtEmail" name="txtEmail" class="textbox" placeholder="Enter Your Email Address"
oninvalid="this.setCustomValidity('Please Enter Your Email!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" name="btnRegister" value="Register" onclick="register()" />
<input type="button" name="btnReset" value="Reset" onclick="reset('registerForm')" />
</td>
</tr>
</table>
</fieldset>
</div>
<form>
<div id="information"></div>
</body>
</HTML>
shoponline.js
var xHRObject = false;
if (window.XMLHttpRequest)
xHRObject = new XMLHttpRequest();
else if (window.ActiveXObject)
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
function reset(formID) {
switch (formID) {
case 'loginForm':
document.getElementById('txtEmail').value = "";
document.getElementById('txtPassword').value = "";
break;
case 'registerForm':
document.getElementById('txtFName').value = "";
document.getElementById('txtSurname').value = "";
document.getElementById('txtEmail').value = "";
break;
}
}
function login() {
var email = document.getElementById('txtEmail').value;
var pass = document.getElementById('txtPassword').value;
xHRObject.open("GET", "login.php?id=" + Number(new Date) + "&email=" + email + "&pass=" + pass, false);
xHRObject.send();
if (xHRObject.responseText == true)
document.location.href = "bidding.htm";
else
window.alert("Login Failure!");
}
function register() {
var isFound = false;
var email = document.getElementById('txtEmail').value;
var firstName = document.getElementById('txtFName').value;
var surName = document.getElementById('txtSurname').value;
xHRObject.open("GET", "register.php?id=" + Number(new Date) + "&email=" + email + "&firstName=" + firstName + "&surName=" + surName, false);
xHRObject.send();
if (xHRObject.responseText == true)
window.alert("Registration Failure!");
else
window.alert("Registration Success!");
}
customer.xml
<customers>
<customer>
<ID>C1</ID>
<FirstName>Jack</FirstName>
<SurName>Wong</SurName>
<Email>jack#hotmail.com</Email>
<Password>081292</Password>
</customer>
<customer>
<ID>C2</ID>
<FirstName>Ashley</FirstName>
<SurName>Rachael</SurName>
<Email>ashley#hotmail.com</Email>
<Password>081292</Password>
</customer>
<customer>
<ID>C3</ID>
<FirstName>Vongola</FirstName>
<SurName>Steve</SurName>
<Email>vongola#hotmail.com</Email>
<Password>081292</Password>
</customer>
</customers>
register.php
<?php
$xmlFile = "customer.xml";
$isFound = false;
$count = 0;
// Check the XML is exist or not.
// If does, do checking against the email address.
if (file_exists($xmlFile)) {
$dom = new DOMDocument();
$dom->load($xmlFile);
$customer = $dom->getElementsByTagName("customer");
foreach($customer as $node) {
$fName = $node->getElementsByTagName("FirstName");
$valueFName = $fName->item(0)->nodeValue;
$email = $node->getElementsByTagName("Email");
$valueEmail = $email->item(0)->nodeValue;
if($_GET["email"] == $valueEmail)
$GLOBALS["isFound"] = true;
$GLOBALS["count"]++;
}
if ($isFound != true) {
// UNIQUE EMAIL, START UPDATE XML & SEND MAIL
$firstName = $_GET["firstName"];
$surName = $_GET["surName"];
$email = $_GET["email"];
$password = random_password(8);
$xml = new SimpleXMLElement($xmlFile);
$customer = $xml->addChild("customer");
$customer->addChild("ID", "C" .($count + 1));
$customer->addChild("FirstName", $firstName);
$customer->addChild("SurName", $surName);
$customer->addChild("Email", $email);
$customer->addChild("Password", $password);
$xml->saveXML($xmlFile);
}
} else {
// XML FILES NOT EXIST. STRAIGHT AWAY CREATE A NEW ONE AND SEND EMAIL
}
ECHO ($isFound);
?>
Basically, I was used AJAX for server and client communication.
Therefore, when end-users finish input their information at register.htm and it will go to javascript file using XMLHttpsRequest.open to register.php for updating data on XML.
But it doesn't update my XML data.
Any advise will be appreciate.

HTML how to validate any of checkbox which are in Array before submit

Below is the HTML/PHP code, in which i need to validate any of the checkbox out of 5 before submit the Form.
function checkAddress(checkbox)
{
if (checkbox.checked)
{
document.frmUser.action = "edit_user.php";
document.frmUser.submit();
}
else {alert("checkbox");}
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Details Form</title>
<script language="javascript" type="text/javascript">
function checkAddress(checkbox)
{
if (checkbox.checked)
{
document.frmUser.action = "edit_user.php";
document.frmUser.submit();
}
else {alert("checkbox");}
}
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
i=0;
while(i=5){
?>
<input type="checkbox" name="users[]" value="<?php echo i; ?>" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress(this);" />
<?php
$i++;}
?>
</form></div></body></html>
I think you are trying to do this
function checkAddress(checkbox) {
if (checkbox.checked) {
document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
document.frmUser.action = "#";
alert("checkbox");
}
}
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php $i=0; while($i<=5){ ?>
<input type="checkbox" name="users[]" onClick="checkAddress(this);" value="<?php echo $i; ?>">
<?php $i++;} ?>
<input type="submit" name="update" class="button" value="Update" />
</form>
</div>
Some errors in your code
you have not used $ while denoting the variable i
you are taking the button inside the while loop so it also repeating with the checkboxes.
You are calling onClick="checkAddress(this);" from your button, so this refers to the button and not a checkbox, so then in your function checkbox.checked is testing if the button is checked - which obviously it never will be.
To test whether at least one checkbox is checked you could loop through them testing them in turn, but you can also do it in one step as follows:
if (document.querySelector('form[name="frmUser"] input[name="users[]"]:checked')) {
// at least one is checked
}
The .querySelector() method returns the first matching element (which is a truthy value for use in an if test), or returns null if no matching elements are found (which is a falsey value for use in an if test).
(If the page has only one form with one group of checkboxes then you could simplify the selector to something like .querySelector(':checked'), but I think it is better to be explicit about which items you're testing.)
In context:
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[name="users[]"]:checked')) {
alert("Success! (form would be submitted here)");
//document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
alert("You must select at least one checkbox");
}
}
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<input type="checkbox" name="users[]" value="1" >
<input type="checkbox" name="users[]" value="2" >
<input type="checkbox" name="users[]" value="3" >
<input type="checkbox" name="users[]" value="4" >
<input type="checkbox" name="users[]" value="5" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress();" />
</form>
</div>
There was another problem with the code posted - the variable i wasn't correctly defined ~ it should have been $i
Rather than assigning the function directly to the button you can create an event listener like this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Details Form</title>
<script language="javascript" type="text/javascript">
function validate(e){
var form=e.target.parentNode;
var col=form.querySelectorAll('input[type="checkbox"]');
var checked=[];
if( col )for( var n in col )if( col[n].nodeType==1 ){
if( col[n].checked ) checked.push( col[n].name );
}
if( checked.length > 0 ){
form.action='edit_user.php';
form.submit();
} else {
alert('You MUST tick at least one checkbox');
}
}
function bindEvents(){
var bttn=document.forms['frmUser'].querySelectorAll('input[type="button"]')[0];
bttn.addEventListener( 'click', validate, false );
}
document.addEventListener('DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
$i=0;
while( $i <= 5 ){
echo "<input type='checkbox' name='users[]' value='{$i}' >";
$i++;
}
echo "<input type='button' name='update' class='button' value='Update' />";
?>
</form>
</div>
</body>
</html>
<html>
<head>
<script language="javascript" type="text/javascript">
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[type="checkbox"]:checked')) {
alert("Success! (form would be submitted here)");
//document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
alert("You must select at least one checkbox");
}
}
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
$i=0;
while($i<=5){
?>
<input type="checkbox" name="users[]" value="<?php echo $i; ?>" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress(this);" />
<?php
$i++;}
?>
</form></div></body></html>

Need preview page before send email [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My email sending script send email after submitting the form.Form data are directly sent to receiver email address after clicking submit button, but I need preview page which will show preview of form data before sending email. Here form action is controlled by javascript file workMail.js and action page is sendMail.php
Thanks for any help.
Here is my code
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
<script src="http://unnayannews.com/testjs/jquery_003.js"></script>
<script src="js/workMail.js"></script>
<link rel="stylesheet" type="text/css" href="css/mailAlert.css">
</head>
<body style="margin: 0px;">
<div class="onedari_form_wrapper info_form_wrapper ajast_onedari_form mgt0">
<form id="contactForm">
<div class="form_field">
<label id="name">■Name<span class="red">*</span></label>
<input kl_virtual_keyboard_secure_input="on" placeholder="Name" class="custom_input" name="name" type="text" required>
</div>
<div class="form_field">
<label id="mail">■Email<span class="red">*</span></label>
<input kl_virtual_keyboard_secure_input="on" class="custom_input" name="mail" type="text" required>
</div>
<div class="form_field">
<label id="age">■Age<span class="red">*</span></label><br>
<input kl_virtual_keyboard_secure_input="on" style="width: 30%" placeholder="" class="custom_input" name="age" type="text" required>
</div>
<p style="margin: 0px 0px 8px;"><label id="work">■Work<span class="red">*</span></label></p>
<div class="category-wrapper">
<input id="CategoryCategory10" class="checkbox" value="10" name="data[]" type="checkbox" >
<label for="CategoryCategory10">App development</label>
<br> <input id="CategoryCategory209" class="checkbox" value="209" name="data[]" type="checkbox"> <label for="CategoryCategory209">System management</label>
<br>
<input id="CategoryCategory213" class="checkbox" value="213" name="data[]" type="checkbox"> <label for="CategoryCategory213">Web</label><br>
<input id="CategoryCategory19" class="checkbox" value="19" name="data[]" type="checkbox"> <label for="CategoryCategory19">Graphics</label><br>
<br>
<button id="send" class="submit bg_red" type="button" name="send">Submit</button>
</form>
</div>
</body>
</html>
sendMail.php
<?php
if( isset($_POST['data']) && is_array($_POST['data']) ) {
foreach($_POST['data'] as $data) { }
$datatList = implode(', ', $_POST['data']);
}
$send_for_address = "test#email.com";
$header = "From: test#email.com";
$messages = "Name: $_POST[name]\n";
$messages .= "Email: $_POST[mail]\n";
$messages .= "Age : $_POST[age]\n";
$messages .= "Work $datatList\n";
mail($send_for_address, $messages,$header);
mb_internal_encoding("UTF-8");
if (mail($send_for_address, $messages,$header)) {
$response = <<<HTML
<div class='alert'>
<div class='alert-header'><div class="alert-remove layerOff">×</div></div>
<div class="alert-body fs0_7">
Thank you for your applicaion!
</div>
<div class="alert-footer">
<input type="button" value="OK" class="layerOff">
</div>
</div>
HTML;
echo json_encode(array("success"=>true, "message"=> $response));
}else{}
?>
workMail.js
$(function(){
// sendForm
$("#send").on("click", function(e){
e.preventDefault();
chackError("#contactForm");
});
$(document).on("click", ".layerOff", function(){
$(".overlay").remove();
});
});
function chackError(selector){
var $form = $(selector);
var name = $form.find("input[name='name']").val();
var mail = $form.find("input[name='mail']").val();
var age = $form.find("input[name='age']").val();
/*var work = $form.find("textarea[name='work']").val();*/
var dataval = document.getElementsByName("data[]");
// or document.querySelectorAll('[name="summer[]"]');
var checked = [].filter.call( dataval , function( v ){
return v.checked;
});
$form.find(".coution").remove();
var error_frag = false;
if ( checked.length < 1 ) {
$("#work").append("<span class='coution'><br>Work field reqire</span>");
error_frag = true;
error_kind = "#work";
}
if(age == ""){
$("#age").append("<span class='coution'><br>Age field reqire</span>");
error_frag = true;
error_kind = "#age";
}
if(mail == ""){
$("#mail").append("<span class='coution'><br>email field reqire</span>");
error_frag = true;
error_kind = "#mail";
}
if(name == ""){
$("#name").append("<span class='coution'><br>Name field reqire</span>");
error_frag = true;
error_kind = "#name";
}
if(error_frag === false){
sendForm();
}else{
var targetY = $(error_kind).offset().top;
var headerH = $("#header").height();
var ajast = ($(window).width() >= 761)? 80 : 20;
$("html, body").animate({ scrollTop: targetY - headerH - ajast}, 'fast');
}
}
function sendForm(){
var post_data = $("#contactForm").serialize();
$("#contactForm").find("input, checkbox, textarea").val("").end().find(":checked").prop("checked", false);
$.post("sendMail.php",
post_data,
function(data){
if(data.success === false){
alert("error");
$(".overlay").remove();
}else{
$("body").append("<div class='overlay'></div>");
$(".overlay").html(data.message);
$("html, body").animate({ scrollTop: 0}, 'fast');
}
},
"json"
);
return false;
}
Further to my comment, what I mean by splitting up the sendMail.php (you will, of course, have to modify your main page javascript to accommodate a confirm response from your sendMail.php):
if(isset($_POST['data']) && is_array($_POST['data']) ) {
foreach($_POST['data'] as $data) { }
$datatList = implode(', ', $_POST['data']);
}
else
$datatList = $_POST['data'];
if(!isset($_POST['confirm'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['mail']);
$age = preg_replace('/[^0-9]/','',$_POST['age']);
$data = strip_tags($datatList);
$response = '
<h2>Preview</h2>
<table>
<tr>
<td>NAME:</td><td>'.$name.'</td>
</tr>
<tr>
<td>EMAIL:</td><td>'.$email.'</td>
</tr>
<tr>
<td>AGE:</td><td>'.$age.'</td>
</tr>
<tr>
<td>DATA:</td><td>'.$data.'</td>
</tr>
<tr>
<td colspan="2">
<form id="confirm" method="post" action="">
<input type="hidden" name="name" value="'.$name.'" />
<input type="hidden" name="mail" value="'.$email.'" />
<input type="hidden" name="age" value="'.$age.'" />
<input type="hidden" name="data" value="'.$data.'" />
<input type="submit" name="confirm" value="Confirm" />
</form>
</td>
</tr>
</table>';
echo json_encode(array("confirm"=>true, "message"=> $response));
}
else {
$send_for_address = "test#email.com";
$header = "From: test#email.com";
$messages = "Name: $_POST[name]\n";
$messages .= "Email: $_POST[mail]\n";
$messages .= "Age : $_POST[age]\n";
$messages .= "Work $datatList\n";
mail($send_for_address, $messages,$header);
mb_internal_encoding("UTF-8");
if (mail($send_for_address, $messages,$header)) {
$response = <<<HTML
<div class='alert'>
<div class='alert-header'><div class="alert-remove layerOff">×</div></div>
<div class="alert-body fs0_7">
Thank you for your applicaion!
</div>
<div class="alert-footer">
<input type="button" value="OK" class="layerOff">
</div>
</div>
HTML;
echo json_encode(array("success"=>true, "message"=> $response));
}
}

Using AJAX to pass variable to PHP and get that variabel again

I want to pass values to a PHP script so i am using AJAX to pass those and that part works. But in the same function I want retrieve those values that I passed to the PHP script. The problem is I cannot retrieve any value from the PHP file. I have search high and low, but now come to you for answers. How can I store the variable passed on to the PHP script so that my ajax can retrieve it? My code is as follows:
This is my form :
<!-- file album.php -->
<html>
<head>
<?PHP
include ("conection/connect.php");
?>
<script type="text/javascript" src="jstbl/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function cekjumlah(tableID)
{
var hitung=document.getElementById(tableID).rows.length;
var jumlah = hitung-1;
document.getElementById("media").value=jumlah;
}
</script>
</head>
<title></title>
<body>
<form name="form1" id="form1" method="post">
Jumlah Inputan :
<input type="text" id="media" name="media" size="5">
<input type="text" id="data_barang" name="data_barang" size="60" onKeyPress="onEnterPenjualan(event);">
<br><br>
<table id="tabelimei" border="1">
<tr id="Last">
</tr>
</table>
<br><br>
<div id="menu">
<p>
<input type="submit" name="simpan" value="Simpan" onClick="cekjumlah('tabelimei')">
<input onClick="deleteRow('DivTambah')" name="button" type="submit" value="Hapus" />
</p>
<p id="hasil">hasil</p>
</div>
</form>
</body>
</html>
And this is my jquery :
function onEnterPenjualan(e){// => Digunakan untuk membaca karakter enter
var key=e.keyCode || e.which;
if(key==13){// => Karakter enter dikenali sebagai angka 13
$(function(){
var data_barang = $("#data_barang").val();
$.ajax({
url: "ambildatabarang.php",
data: "data_barang="+data_barang,
cache: false,
success: function(data){
console.log(data);
alert(data);
}
});
var nama = alert (data.$nama);
var baris = document.getElementById("data_barang").value;
var i = 1;
var row = $(document.createElement('tr')).attr("id", 'DivTambah' + i);
row = '<tr>'+
'<td>1</td>'+
'<td><input name="cek[0]" id="cek" type="checkbox" size="10" /></td>'+
'<td><input name="qty_penjualan[0]" type="text" id="qty_penjualan" value="1" size="10" required/></td>'+
'<td><input type="text" name="imei_penjualan[0]" id="imei_penjualan" size="60" value="'+baris+'" required/></td>'+
'<td><input type="text" name="nama_penjualan[0]" id="nama_penjualan" size="30" value = "'+nama+'"required/></td>'+
'<td><input type="text" name="hargajual_penjualan[0]" id="hargajual_penjualan" value="300000" size="15" required/></td>'+
'<td><input type="text" name="diskon_penjualan[0]" id="diskon_penjualan" size="15" value="0"/></td>'+
'<td><input type="text" name="total_penjualan[0]" id="total_penjualan" size="15" value="300000" required/></td>'+
'<td><button type="button" class="del">Del</button></td>'+
'</tr>';
$(row).insertBefore("#Last");
var hapus = "";
document.getElementById('data_barang').value=hapus;
document.getElementById('data_barang').value.focus();
i++;
});
$(".del").live('click', function(){
$(this).parent().parent().remove();
});
}}
And this is my PHP file :
<?php
if (isset($_GET['data_barang'])){
// Instructions if $_POST['value'] exist
include ("conection/koneksidb.php");
$databarang = $_GET['data_barang'];
$datalengkapbarang = mysql_query("SELECT i.id_imeibarang, jb.nama_jenisbarang, b.type_barang, b.hargajual_barang FROM jenisbarang jb, barang b, imeibarang i WHERE i.id_imeibarang='$databarang' and i.idbarang_imeibarang=b.id_barang and b.idjenis_barang=jb.id_jenisbarang");
$angka = 1;
while($k = mysql_fetch_array($datalengkapbarang)){
echo $no[$angka] = $angka;
echo $imei[$angka]=$k['id_imeibarang'];
echo $nama[$angka]=$k['nama_jenisbarang'].$k['type_barang'];
echo $harga[$angka]=$k['hargajual_barang'];
$angka = $angka+1;
}
}
?>
to send the some data to php and get the result of the php file to javascript synchronously, this is what you need
function sendData (data1,data2)
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("POST", "url.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send("data1=" + data1 + "&data2=" + data2);
return AJAX.responseText;
}
else
return null;
}
now, on your php file, you just get your data like this
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
once you work with the data in your php file, and then you echo the result, it is returned by the javascript function, so you just need to use it like this in your javascript file
var data_from_php = sendData(data1,data2);

Categories

Resources