Ajax with PHP and HTML - php

<input type="button" value="addkid " onClick="show()" />
<div>
<div id="myTableData" style="display:none; width:800px; height:500px; background-color:yellow; margin:0 auto;">
<form action="javascript:insert()" method="get">
<table>
<tr>
<td width="175">NAME</td>
<td width="245"> Gender</td>
<td width="245">Date of Birth</td>
</tr>
<tr>
<td width="175">
<input type="text" name="kid_name" id="kid_name" />
</td>
<td width="245">FEMALE
<input type="radio" name="gender" value="female" id="gender" />MALE
<input type="radio" name="gender" id="gender" value="male" />
</td>
<td width="245">
<?php for ( $i=1; $i<13; $i++ ) { $month=d ate( 'm', mktime(0,0,0,$i,2,2000)); $sel=( $i==d ate( 'n') ? ' selected="selected"' : ''); $options1[]="<option value=\" {$month}\ " {$sel}>{$month}</option>"; } $options_list1=j oin( "", $options1); echo "<select name=\"month\ " id='month' >{$options_list1}</select>"; for ( $j=1; $j<32; $j++ ) { $theday=d ate( 'd', mktime(0,0,0,0,$j,2000)); $sel=( $j==d ate( 'd') ? ' selected="selected"' : ''); $options2[]="<option value=\" {$theday}\ " {$sel}>{$theday}</option>"; } $options_list2=j oin( "\r\n", $options2); echo "<select name=\"day\ " id='day' >{$options_list2}</select>"; for ( $k=1960; $k<2016; $k++ ) { $theyear=d ate( 'Y', mktime(0,0,0,1,1,$k)); $sel1=( $k==d ate( "Y") ? ' selected="selected"' : ''); $options3[]="<option value=\" {$theyear}\ " {$sel1}>{$theyear}</option>"; } $options_list3=j oin( "\r\n", $options3); echo "<select name=\"year\ " id='year' >{$options_list3}</select>"; ?>
</td>
</tr>
</table>
<input type="submit" name="sub" value="add" />
</form>
</div>
</div>
<script>
function show() {
document.getElementById("myTableData").style.display = "block";
}
function createObject() {
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
//value solve an Internet Explorer cache issue
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('content02').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var kid_name = encodeURI(document.getElementById('kid_name').value);
var gender = encodeURI(document.getElementById('gender').value);
var month = encodeURI(document.getElementById('month').value);
var day = encodeURI(document.getElementById('day').value);
var year = encodeURI(document.getElementById('year').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', '4.php?kid_name=' + kid_name + '&gender=' + gender + '&month=' + month + '& day=' + day + '&year=' + year + '&nocache = ' + nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if (http.readyState == 4) {
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('content02').innerHTML = 'Your contact was successfully added!' + response;
}
}
</script>
4.php
<?php
if(isset($_GET['kid_name']) && isset($_GET['gender']) && isset($_GET['year']) && isset($_GET['day']) && isset($_GET['month']) )
{
echo $newFname = $_GET["kid_name"] ;
echo $newLname = $_GET["gender"] ;
echo $newPhone = $_GET["year"] ;
echo $newEmail = $_GET["day"] ;
echo $newAddress = $_GET["month"] ;
//$insertContact_sql = "INSERT INTO `test`.`contacts` (`newFname`, `newLname`, `newPhone`, `newEmail`, `newAddress`, `group`) VALUES ('{$newFname}' , '{$newLname}' , '{$newPhone}' , '{$newEmail}' , '{$newAddress}' , '{$group}')";
//$insertContact= mysql_query($insertContact_sql) or die(mysql_error());
} else
{
echo 'Error! Please fill all fileds!';
}
?>
I am working with php language. There is a addkid button, which, when the user clicks on the button a pop type window shows the form which has NAME , GENDER AND DOB. In the form action javascript:insert(). I am using ajax for the 1st time so I am not able to understand why it's not working. I guess it should redirect me to 4.php and in 4.php it will echo the values?

I have tested your code and seems it works, I just added a div to show the results there...
You can try to add this div you are not already added it...
<div id="content02">
</div>
Here you write the response, like "Your contact was successfully added"....

Related

Trying to check and send mysql info

<script>
function buttonClick(){
var total = 0;
var type = "";
for(var i=1;i<=3;i++) {
var id = "max_clicks" + i;
var label = "label" + i;
var badge = "badge" + i;
if (document.getElementById(id).checked!=null && document.getElementById(id).checked==true) {
total += parseInt(document.getElementById(id).value);
type +="Max-clicks:<hr style='margin-top:-1px;' />"+ "<span class='badge' style='margin-top:-5px;'>" + document.getElementById("label"+i).innerHTML + "</span> : <span class='badge' style='margin-top:-5px;'>" + document.getElementById("badge"+i).innerHTML + "</span><br />";
}
}
document.getElementById('Totalcost').innerHTML = total;
document.getElementById('individual').innerHTML = type;
}
</script>
<form action="<?php echo "".site_url."";?>/magaza/reklam-ver" method="post" enctype="multipart/form-data">
<input type="checkbox" name="max_clicks[]" id="max_clicks1" value="<?php echo "".$price1."";?>" onClick="buttonClick(this);">
<label id="label1" class="badge" style="background:#fc5a5d;"> 150 clicks</label>-<span class="badge" id="badge1">Price: 5 credits</span><br />
<input type="checkbox" name="max_clicks[]" id="max_clicks2" value="<?php echo "".$price2."";?>" onClick="buttonClick(this);">
<label id="label2" class="badge" style="background:#fc5a5d;"> 400 clicks</label>-<span class="badge" id="badge2">Price: 13 credits</span><br />
<input type="checkbox" name="max_clicks[]" id="max_clicks3" value="<?php echo "".$price3."";?>" onClick="buttonClick(this);">
<label id="label3" class="badge" style="background:#fc5a5d;"> 735 clicks</label>-<span class="badge" id="badge3">Price: 9 credits</span><br />
<span id="individual" class="badge" style="background:#f29d9d;">You dont have any select item.</span>
<button type="button"class="btn btn-primary" onclick="buttonClick()">Price to pay:
<span class="badge"><span id="Totalcost">0</span> credits</span></button>
<input class="btn btn-success" style="float:right;" type="submit" name="add_ad" value="Reklam satın al">
</form>
I trying to get checked item and send to mysql... All working but have problem with send to mysql i want to send max-click -info of <span>....</span> and check price with input value and send this to mysql - max-clicks -value off <span>..</span> and value of input any ideas ? i give my script form.php and action_form.php and sorry for my language :/
if($_POST['add_ad'])
{
if(!empty($_POST['max_clicks'])) {
$shipping_subtotal = 0;
foreach($_POST['max_clicks'] as $shipping){
$shipping_subtotal += $shipping;
}
$user = userInfo();
if($user['credits'] >= $shipping_subtotal){ //check user have enough credits or not
if($_POST['title'] && $_POST['target_url'])
{
$expires = strtotime("+1 month"); //Reklam 1 ay ekle
$title = quote_smart($_POST['title']);
$target_url = quote_smart($_POST['target_url']);
mysql_query("INSERT INTO ads (date_added,date_expires, target_url, clicks, author_id, title, max_clicks) VALUES ('".time()."',$expires, $target_url, '0', '".$_COOKIE['user_id']."', $title, $shipping_subtotal)") or die(mysql_error());
echo info("Success!");
delcredits($user['id'], $shipping_subtotal);
header ("refresh:3;url=".site_url."/magaza/reklam-ver");
}
else
{
echo error("Error.");
}
}
else
{
echo error("you dont have enough credits");
}
}
else{
echo "<b>Please select max-clicks.</b>";
}
}

ajax - no transmission of data

I am a newbie on ajax. I spend hours with "try and error", but unfortunately without success.
I have a form:
<form id="upload" method="post" name="form">
<input class="datepicker" type="text" name="date" value="<?php echo $date_bes; ?>"/>
<input class="chk" name="chk" type="checkbox" value="<?php echo $id_submit; ?>"
<?php if($check == 1){ echo "checked"; }else{ echo "";} ?>/>
<textarea class="remark" name="remark" cols="30" rows="1"><?php echo $remark; ?> </textarea>
<input class="submit" type="image" src="save.jpg"></td>
</form>
Then I my ajax_script.js:
$(document).ready(function() {
$( "#upload" ).on("submit", function() {
var id = $('.chk').val();
var date = $('.datepicker').val();
var chk = $('.chk').prop('checked');
var remark = $('.remark').val();
$.ajax({
type: "POST",
url: "update.php",
data : "{'id':'" + id + "', 'date':'" + date + "', 'chk':'" + chk + "', 'remark':'" + remark + "'}",
success: function (data) {
if(data.success == true)
{
console.log('everything fine');
}
},
error: function(){
console.log('something bad happened');
}
});
});
});
and my update.php
<?php
$id = $_POST['id'];
$date = $_POST['date'];
$chk = $_POST['chk'];
if($chk == true){
$check = 1;
}else{
$check = 0;
}
$remark = $_POST['remark'];
$jahr = substr($date,6,4);
$mon = substr($date,3,2);
$tag = substr($date,0,2);
$date = $jahr.'-'.$mon.'-'.$tag;
echo $id ."<br>".$date."<br>".$chk."<br>".$remark;
require_once('config.php');
$link = mysqli_connect (
MYSQL_HOST,
MYSQL_BENUTZER,
MYSQL_KENNWORT,
MYSQL_DATENBANK
);
if(!$link){
die('Keine Verbindung möglich: ' .mysql_error());
}
$sql = "UPDATE mytable
SET date = '$date', chka ='$chk', remark = '$remark' WHERE id_submits = $id";
$result = mysqli_query( $link, $sql );
echo $sql."<br>";
?>
After push on the bottom, firebug deliver me following:
Can anybody help me - please!
Regards,
Yab86
I think that you do not really need the quotes around the variable in the data section of ajax.
data: {id: id, date: date, chk: chk, remark: remark},
To let AJAX pass data through JQuery you should simply put in the "data" part of the AJAX request your data in this format {'name':name_on_php,'name2':name_on_php2}
I've written "name_on_php" to remind you that the part after the " : " is the one that you GET or POST on your php page.
Hope it helped :)

jquery function stops adding numbers up in php

I have a piece of code below where it determines which assessment the user is in and the assessment number the user is currently on:
<?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?>
So on the browser this could read for example:
1 OF 4
Now below I have a submit button:
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
Now if the user clicks on the button, it will show a confirmation box and if the user clicks OK, for the confirmation, then it will submit the page and what is suppose to happen is that it adds a number to the assessment to indicate that the user is on the next assessment.
SO FOR EXAMPLE:
If it says this on the page:
1 OF 4
If the user submits the page and confirms, then it should now say this:
2 OF 4
This is because the user is on the next assessment now.
But the problem is that it is not adding the number at all when the user submits the page. It just stays at '1' and doesn't add up. So instead of doing the above it is doing the below:
If it says this on the page:
1 OF 4
If the user submits the page and confirms, then it still says:
1 OF 4
This is obviously incorrect.
I have tested my code and what I have found is that if there is that the jquery validation() is causing the number to not add up and stay at '1'. But my question is that how come this jquery function is causing this to happen?
Below is the jquery validation() function:
function validation() {
var _qid = "";
var _msg = "";
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
Below is relevant code so you know what the code is:
<?php
session_start();
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
if ($sessionMinus == $_SESSION['initial_count']){
$action = 'create_session2.php';
}elseif($sessionMinus != $_SESSION['initial_count']){
$action = $_SERVER['PHP_SELF'];
}
?>
<script type="text/javascript">
function validation() {
var _qid = "";
var _msg = "";
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
function showConfirm(){
var confirmMsg=confirm("Make sure that your details are correct, once you proceed after this stage you would not be able to go back and change any details towards Questions, Options and Answers for your Session." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n" );
if (confirmMsg==true)
{
submitform();
}
}
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize() ,function(data){
var QandAO = document.getElementById("QandA");
QandAO.submit();
});
alert("Your Details for this Session has been submitted");
}
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<h1><?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
<div id="detailsBlock">
<table id="questionBtn" align="center">
<tr>
<th>
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
</th>
</tr>
</table>
</div>
<hr/>
<div id="details">
<table id="qandatbl" align="center">
<thead>
<tr>
<th class="question">Question</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<p><input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" onClick="myClickHandler(); return false;" /></p>
</form>
<script type="text/javascript">
function myClickHandler(){
if(validation()){
showConfirm();
}
}
</script>
UPDATE:
Below is the code of in the insertQuestion() function:
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'>");
var $image = $("<td class='image'></td>");
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"<p class='imagef1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='imagef1_upload_form' align='center'><br/><label>" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
$image.append($fileImage);
$tr.append($image);
$tbody.append($tr);
}
I think you want to check if sessionCount is NOT set (!isset). Try adjusting your code like this:
if(!isset($_POST['sessionCount'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}

JavaScript Form Validate rows in HTML table

For some reasons my javascript form validation does not go through every row in the table.
I created the table with the codes below:
The $usr variable is just a result of another process:
<form name="myForm" action="addAccessories.php" method="post" onsubmit="return validateForm(this);">
<table border="1" id="IT">
<tr>
<th>Barcode<em>*</em></th>
<th>Current stock</th>
</tr>
<?php
for($id=1; $id<=$usr; $id++){
?>
<tr>
<td><input type="hidden" name="id[]" value="<?php echo $id; ?>" />
<input type="text" name="bar_code<?php echo $id; ?>" id="bar_code<?php echo $id; ?>" value="" /></td>
<td><input type="text" name="num_stock<?php echo $id; ?>" value="0" id="num_stock<?php echo $id; ?>"/></td>
<?php
}
?>
<tr>
<td> </td>
<td> <button data-theme="b" input type="submit" name="Submit" value="Submit">Add accessories</button></td>
</tr>
</table>
</form>
The number of rows from this table is: rows = $usr + 1
My validation form codes:
<script type="text/javascript">
function validateForm(){
var errors = [];
for(i = 1; i < document.getElementById("IT").rows.length; i++){
var barcode = document.getElementById('bar_code'+i).value;
var des = document.getElementById('description'+i).value;
var num_stock = document.getElementById('num_stock'+i).value;
if(barcode == null || barcode == ""){
errors[errors.length] = "You must enter barcode.";
}
if(isNaN(num_stock)){
errors[errors.length] = "Current stock must be an integer";
}
if(num_stock < 0){
errors[errors.length] = "Current stock must be a positive number";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
This process only validates the 1st row in the table then stop. Can anyone show me what went wrong and how to fix it?
Thank you very much for your help
Your code is making life way more complex than it needs to be. A simpler approach is to just deal with the form controls, e.g. since you are already passing a reference to the form from the submit listener:
function validateForm(form) {
var errors = [];
var c, cs = form.elements;
var reB = /^bar_code/;
var reN = /^num_stock/;
var reD = /^[0-9]+$/;
for (var i=0, iLen=cs.length; i<iLen; i++) {
c = cs[i];
if (reB.test(c.name) && c.value == '') {
errors.push('You must enter barcode.'];
} else if (reN.test(c.name) && !reD.test(c.value)) {
errors.push('Stock number must be a positive integer.'];
}
}
// deal with errors...
}
Note that in the test:
> barcode == null || barcode == ""
barcode is a string, so the first test will never return true and the second is sufficient if you want to see if it's empty.

jquery Post problem

I have a code in which i am sending the values from a form to php page where the query lies and for sending the values i am using $.post of jquery everything is going good. I am resulting a table and a button now i want that button will work and 1 of the table column has the radio button list so i want that button will take the radio id of that perticular row on click but my button is not working so please guide me how i can do this my code is here
my javascript function
function searchDetail(searchName) {
var textName = searchName + "Text";
var inputText = $('#' + textName).val();
var formName = searchName + "Form";
if (inputText === "") {
$('#' + textName).css("border", "2px solid red").fadeIn(4000);
}
else {
$('#' + textName).css("border", "1px solid #8dd7f6").show(2000);
$('#searchBox').fadeIn(1000);
$.post('../search/delete' + searchName + '.php', $('#' + formName).serialize(), function(result) {
$('#searchBox').html(result);
})
}
}
my php code
if ($count == "0") {
echo "There is no data with $search = ".$searchKeyword;
} else {
$color = 2;
echo "<table cellspacing='0px' cellpadding='7px'><thead><tr><th>#</th><th>book Id</th><th>book Name</th><th>book Writer</th><th>book Price</th><th>Availability</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
$checkBook = $row['booktotal'] - $row['bookremain'];
if ($checkBook == 1) {
$status = "Yes";
} else {
$status = "No";
}
if ($color % 2 == 0) {
echo "<tr class='even'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = $color + 1;
} else {
echo "<tr class='odd'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = 2;
}
}
echo "</tbody></table><br><input type=button value=Delete id=deleteButton onclick='check()'> <script type=text/javascript> function check(){alert(Hello);}</script>";
mysqli_close($con);
}
?>
my html code
<body>
<div id="deleteFormTable">
<span id="headerFont">Enter Information to Delete Book</span><br><br>
<form id="bookSearchForm" name="bookSearchForm"><label>Search Book:</label> <input type="text" id="bookSearchText" name="bookSearchText"/>&nbsp<select id="bookSearchOption" name="bookSearchOption"><option id="bookSearchId">Id</option><option id="studentSearchName">Name</option></select> <input type="button" value="Search" id="bookSearch" name="bookSearch" onclick="searchDetail(this.id)"></form>
</div>
<div id="searchBox">
<center><div id="searchLoadBox"><img src="../images/loadings.gif" alt="..."></div></center>
</div>
</body>
OK, I think I know what you are asking.
You have a list of items with radio boxes next to them, once the user clicks one and then clicks the button, you want the "value" tied to that radio button.
If that is the case, you can use this to find the value of the "Checked" radio group.
$("#deleteButton").click(function()
{
var bookId = $("input[#name='group1']:checked").val();
}

Categories