How to insert value using ajax into database? - php

Here I am getting the counter value using javascript.
I want to insert those counter value into my database.
How can I do it? Please suggest me.
<script language="JavaScript">
var counter = 1;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>

please read W3school ajax tutorial and click on try it yourself button I am sure that you will easily get that :)

Related

how do I loop a php variable within a javascript script

I created a form with a text field that has Spry Validation (ie javascript). The user can select the number of rows in the form from 1 to 10. I need the code below to also expand but I'm not familiar enough with javascript to make it work.
$divkey is the variable that controls how many rows are in the form.
Original
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["change"], maxChars:20});
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
so I need the line 'var sprytextfield1...' to repeat based on $divkey with the next line being 'var sprytextfield2...' and so on. Can someone please rewrite this so it will work?
Trying to use php
<script type="text/javascript">
<?php for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Trying to use javascript
<script type="text/javascript">
var numwrestler = <?php echo $wrestlerkey; ?>;
var sprytextfield = [];
for (var i = 0; i < numwrestler; i++) {
var num = i+1;
var sprytextfield[num] = new Spry.Widget.ValidationTextField("sprytextfield"+num, "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
I'd recommend that you use a Javascript array for this type of task.
Your code is mostly correct, but the var in your for loop is incorrect, and the creation of the num variable instead of just using i is redundant.
<script type="text/javascript">
var sprytextfield = new Array();
var numwrestler = <?php echo $wrestlerkey; ?>;
for(var i = 0; i < numwrestler; i++){
sprytextfield[i] = new Spry.Widget.ValidationTextField("sprytextfield"+(i+1), "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Be sure that your PHP variable(s) are defined in the file before you include them in your script.
In your PHP code, you never define the variable divkey, by deafault the value will be 0.
Try:
<script type="text/javascript">
<?php $divkey = 10; for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Please, note that the variable that you are using as index $num in every iteration of the loop will be increasing 2, because of the i++ and the $num=$i+1

Update a span when a select dropdown is made using ajax

I am attempting to code the following script using jquery / ajax / php.
What happens is the php pulls all the records from the database and puts them into a select dropdown. When I select an item from the dropdown ajax pulls the price from the database and adds it into the span called priceeach1 . Well thats what its supposed to do, but my jquery is useless :-S .
The stockID comes from the select box value.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock1').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
});
});
});
</script>
The HTML :
Price Each : £<span id="priceeach1"></span>
The select2.php :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['stockID'];
$sql = 'SELECT * FROM stock WHERE stockID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'priceeach' => $row['priceeach'],
);
}
echo json_encode($json);
?>
EDIT >> Ok I have now updated the code with the latest edits, this now WORKS.....apart from an odd problem......If I select the first or last item in the list no price is displayed, anything in between appears just fine..........
Try this,
var options = [];
for (var x = 0; x < data.length; x++) {
options = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
It should be like this you have to store price in the array options[] instead of option and then join them by any separator
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options[x] = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
You have to parse your JSON data to actual JSON Object before iterating it.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var jsonParsed = JSON.parse(data);
var options = '';
for (var x = 0; x < jsonParsed.length; x++) {
options[] = jsonParsed[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
Try to use this snipt:
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);

Ajax and php when inserting into MySQL

Simple question guys , i have AJAX that pickup all data from page and it suppose to open new php page to update MySQL database , its only updating last row of data , BUT when i use alert from javascript just to check all data i got he does update whole table ... is there any chance that AJAX is not working fast enough or something?
here is my code
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var MatchID = '';
var HomeTeam = '';
var AwayTeam = '';
var TipID = '';
var arrayMaxValues = 3;
var myArray = new Array(3);
var i = 0;
$('#teams_table input[type=text]').each(function () {
myArray[i] = $(this).val();
if (!!myArray[2])
{
MatchID = myArray[0];
HomeTeam = myArray[1];
AwayTeam = myArray[2];
if (HomeTeam > AwayTeam) {
TipID = 1;
}
else if (HomeTeam == AwayTeam) {
TipID = 2;
}
else if (HomeTeam < AwayTeam) {
TipID = 3;
}
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' +
TipID + '&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, true);
http.send(null);
myArray = new Array(3);
i=0;
}
else
{
i++;
}
});
It is kinda odd to me when i use
alert('MatchID = ' + MatchID + ' HomeTeamScore = ' + HomeTeam + ',
AwayTeamScore = ' + AwayTeam)
Inside of AJAX code i get whole table updated , without it just last row
And my php page
<?php
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$HomeScore = $_GET['HomeTeam'];
$AwayScore = $_GET['AwayTeam'];
$query="update probatip1.matches set ResultTipID=".$tipID.",HomeTeamScore = "
.$HomeScore.",AwayTeamScore= ".$AwayScore." where MatchID =".$matchID;
$UpdateGame= mysql_query($query) or die(mysql_error());
mysql_close()
?>
Try encoding the data. i.e:
MatchID = encodeURIComponent(myArray[0]);
HomeTeam = encodeURIComponent(myArray[1]);
AwayTeam = encodeURIComponent(myArray[2]);
in php use
function escapedata($data) {
if(get_magic_quotes_gpc()) {
$data= stripslashes($data);
}
return mysql_real_escape_string($data);
}
to escape your data before updating the table. i.e:
$query="update probatip1.matches set ResultTipID=".escapedata($tipID).",HomeTeamScore = ".escapedata($HomeScore).",AwayTeamScore= ".escapedata($AwayScore)." where MatchID =".escapedata($matchID);
Hope this works.
Not really a direct answer, just something that you can base your answer from. What the code does is to submit a whole object using the $.post method in jquery which takes in 2 parameters and a callback function which is executed once the request is done.Not really sure by: open new php page to update MySQL database but I assume that you're simply using that page to update the database and not actually open it.
<script src="js/jquery.min.js"></script>
<script>
var obj = {
'teams' : [
{'name' : 'teamA', 'grade' : 'A'},
{'name' : 'teamB', 'grade' : 'B'}
]
};
$.post('access.php', {'obj' : obj}, function(data){
var d = JSON.parse(data);
for(var x in d){
console.log(d[x].name);
}
});
</script>
access.php:
<?php
$post = $_POST['obj']['teams'];
$array = [];
foreach($post as $row){
$name = $row['name'];
$grade = $row['grade'];
$array[] = ['name'=>$name, 'grade'=>$grade];
}
echo json_encode($array);
?>
So you only have to modify the php page, and put your database query inside the loop. This way you won't need to perform so many ajax request by putting it inside $.each
Then utilize $.each to build the object that you're going to submit via ajax through $.post method:
var obj = {};
$().each(function(index){
var myArray[i] = $(this).val();
var MatchID = myArray[0];
var HomeTeam = myArray[1];
var AwayTeam = myArray[2];
obj[index] = [];
obj[index]['match_id'] = MatchID;
});
The problem is with your logic in the way you are sending requests to php file to update the MYSQL. Actually you are running the ajax request in a loop and the loop is too fast that kills the previous update request.
Solution
You can compose an array and send it to the php outside the loop. That will work for you.
Guys with your help i managed to fix my problem
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' + TipID +
'&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, false);
http.send(null);
var response = http.responseText;
So basicly with this line i told http request not to go for next line of code until update in table is not completed , when http has done his job then it moves on next line of code.
Thank you for help

How we can get that at a particular place marker is present or not

I am making dynamic markers. I got success in that. But here is problem that if there is two same lat-log then it place only one marker there.
Instead of that I want to change the marker icon if there is two same lat-log.
I am taking lat-log from database.
Any help.
Yes, I have found the solution of this problem.
I am using two array
The code is as following:
var contentStrings = new Array();
var markers = new Array();
and getting the position
var pos = marker.getPosition();
var isPresent = false;
var index;
for(var i = 0; i < markers.length; i++) {
if(String(pos) == String(markers[i])) {
isPresent = true;
index = i;
}
}
if(isPresent) {
contentString = contentStrings[index] + '<div><br/> Tutor Name : '+data.name+'<br/>Link : '+data.url+'</div>';
} else {
markers.push(pos);
contentString = '<div> Tutor Name : '+data.name+'<br/>Link : '+data.url+'</div>';
contentStrings.push(contentString);
}
Its really working fine.

delete link with js confirm + php

this was the delete link
<div class="artworkdelete">
Delete
</div>
apparently, when that link is clicked, the portal deletes the data automatically, i think it's an ajax thing because the page doesn't refresh. so i was ask to add a confirm pop up to ask the user to click yes or no if he wants to delete the data or not, and within the confirm box , it should mention the name of the data to be deleted like e.g
"are you sure you want to delete row_title ?"
here's the function of the deleteThisArtWork()
function deleteThisArtWork(artwork_id){
var artwork_id = artwork_id.split('_');
var cat_id=artwork_id[2];
artwork_id = artwork_id[1];
//$('#divStatus').html('processing request, please wait');
//$(".pleaseWait").dialog("open");
openLightBox();
$.ajax({
type: 'POST',
url: '<?php echo BASE_URL;?>ajax/ajax_methods_gallery.php',
data: 'deleteartwork=yes&artwork_id='+artwork_id+'&category_id='+cat_id,
success: function(msg){
//alert(msg);
msg = 'done';
var status=msg;
var deleted='';
if(status == 'done') {
var temp_lid = 'li_'+artwork_id+'_'+cat_id+'_';
//alert(counter);
for(var v=1;v<counter;v++){
var curid = tempIdArr[v];
curid = curid.split('#');
var curlid = curid[0];
if(temp_lid == curlid){
var del_aw_pos = curid[1];
break;
}
}
del_aw = temp_lid+'#'+del_aw_pos;
var i = 1;
var j =0;
var op = false;
var delpoint;
var endpoint;
var delcatid = '';
var artcounter = 0;
var artcounterArr = new Array();
$(".sortli").each(function (){
var atid = this.id.split('_');
//if(atid[2]!=cat_id)return;
if(this.id == del_aw){
deleted = 'yes';
delcatid = atid[2];
$(this).remove();
op = true;
i=i+1;
delpoint=i-1;
//alert('D'+delpoint);
//return;
}
if(atid[2]==cat_id){endpoint = i-1;artcounter=artcounter+1;}
else if(j==0 && artcounter > 0){
if(artcounter>0)artcounter = artcounter-1;
//else artcounterArr[j] = 0;
artcounterArr[j] = artcounter;
j=j+1;
artcounter = 0;
}
i = i + 1;
});
//alert(delpoint)
//alert(endpoint);
//alert(artcounterArr[0]);
if(op){
for(var k=delpoint; k<counter-1;k++){
var orderVal1 = tempOrderArr[k];
if(k<endpoint)document.getElementById('sortvalid_'+(k+1)).innerHTML = orderVal1;
document.getElementById('sortvalid_'+(k+1)).id = 'sortvalid_'+(k);
document.getElementById('sortdn_'+(k+1)).id = 'sortdn_'+(k);
document.getElementById('sortup_'+(k+1)).id = 'sortup_'+(k);
var t = tempIdArr[(k+1)].split('#');
t=t[0];
document.getElementById(tempIdArr[(k+1)]).id = t+'#'+k;
}
$(".rowHead").each(function (){
var taid = this.id;
var sp = this.id.split("^");
var a1 = sp[1];
//alert(a1);
//alert(cat_id);
if(parseInt(a1)>parseInt(cat_id)){
var a2 = sp[2];
var ta = 'lititle^'+a1+'^';
//alert(ta);
document.getElementById(taid).id = ta+(a2-1);
}
});
var a2temp;
var a1temp;
var delcat=null;
var rowHeadLast;
$(".rowHead").each(function (){
//var taid = this.id;
rowHeadLast = this;
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(a2temp == a2 && delcat==null){delcat = a2temp; delcatid=a1temp;}
a2temp = a2;
a1temp = a1;
});
var delok = false;
$(".rowHead").each(function (){
//var taid = this.id;
//alert(deleted);
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(delcat == a2 && a1==delcatid && deleted==''){delok= true;deleted='yes';$(this).remove();}
});
//alert(delcatid);
//if(!artcounterArr[0])alert('d');
if(!delok){
$(".rowHead").each(function (){
var sp = this.id.split("^");
var cid_t = sp[1];
if(!artcounterArr[0] && delcatid == cid_t)$(this).remove();
//else if(artcounterArr[0]<=0)$(this).remove();
});
}
if(deleted ==''){
$(rowHeadLast).remove();
}
}
setDivsInArray();
//$(".pleaseWait").dialog("close");
closeLightBox();
}
else if(status == 'DBDelete:error'){
//$('#row_'+artwork_id).fadeOut(3500);
$('#divStatus').fadeIn(500);
$('#divStatus').html('<b>Artwork Delete Error</b>');
$('#divStatus').fadeOut(4500);
}
}
});
}
it's quite long , I think I don't need all of those stuff if the requirement is just delete the data when "Yes" was clicked from the confirm pop up box
now here's the delete PHP function
function deleteArtWork($artwork_id,$category_id){
$artwork_cat_lookup_del = "delete from artwork_category_lookup where artwork_id = '$artwork_id' AND category_id='$category_id'";
if(mysql_query($artwork_cat_lookup_del)){
$userObj = new User();
$allArtWorkByCat = $userObj->allArtWorkByCat($category_id);
for($itr = 0; $itr<count($allArtWorkByCat); $itr++){
$ordr = $itr + 1;
$art_id = $allArtWorkByCat[$itr]['artwork_id'];
$updateSQL = "update artwork_category_lookup set artwork_display_order='$ordr' where artwork_id = '$art_id' AND category_id = '$category_id'";
mysql_query($updateSQL);
}
$action = $userObj->userActions('Artwork id: '.$artwork_id.' is deleted', 'Gallery');
$userObj->setActionintoDB($action);
echo 'done';
}
else echo 'DBDelete:error';
return;
I don't think that you want to start changing that code above as that is used to pass the relevant data to the php script via ajax.
What you need is a javascript prompt to intercept the link click and give the user an option to continue or cancel the deletion action. Is this correct?
http://www.tizag.com/javascriptT/javascriptconfirm.php
At the start of the "deleteThisArtWork" javascript function you need to display a prompt.
function deleteThisArtWork(artwork_id){
var answer = confirm("Are you sure you want to delete this record?");
if (answer){
//do the rest of the function as usual, i.e. delete row via ajax.
}else{
return false;
}
}
That should stop the user from accidentally deleting a record without at least having to accidentally click on a confirmation popup as well!
If you want to make the text in the confirm popup dynamic, you would need to either pass in the dynamic text as a variable to the "deleteThisArtwork" method or draw it from another element on the page using some javascript.

Categories