I'm trying to post the "lang_id" var. to "get_lang.php" with jquery to get (json) data.
But I can't access the data.
Now trying to do
var r = $(this).attr('rel');
var v = data.r;
But this doesn't work because of "r" is string IMO.
Also tried
data.window[r] // but...
"get_lang.php";
$lang_id = (int) ($_POST['lang_id']);
if($lang_id == 1)
{
$lang['simple'] = 'aaa';
$lang['array'] = 'bbb';
}
if($lang_id == 2)
{
$lang['simple'] = 'ccc';
$lang['array'] = 'ddd';
}
print json_encode($lang);
my.js;
$.post("get_lang.php", { "lang_id": 2}, function(data){
$('.lang').each(function() {
var r = $(this).attr('rel');
var v = data.r;
$(this).text(v);
});
},"json");
thanks for help.
Try
var v = data[r];
The dot notation interprets r as a string and not as a variable.
I think maybe you need to tell jQuery the right content type. Put this at the TOP of your get_lang.php file
header("Content-Type: application/json");
And see if jQuery likes it.
Related
I have a script that takes variables from an html form and sends them to a php script. I query new data based on these numbers and format them into a string to be sent back to the script. The problem is that my php variables aren't printing and I think it is because they are objects. Here is my code:
//GET VENDOR PO NUMBER AND APPEND ONCHANGE OF # OF EXISTING POS
$('#numvendpo').mouseover(function(){
var countpre = $(this).val();
var p = $('#pro').val();
var c = $('#custponumhold').val();
var v = $('#vendorid').val();
var cp = (parseInt(countpre)+1);
var data_String;
data_String = 'p='+p+'&c='+c+'&v='+v+'&cp='+cp;
$.post('ft-final-v-po-num.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
});
});
I then post the values to this php script:
<?php
require "../inc/dbinfo.inc";
$p = $_POST['p'];
$c =$_POST['c'];
$v = $_POST['v'];
$cp = $_POST['cp'];
if ($c == 'null') { //cant use (!$customerpo) because $customerpo is passing the string of 'null' instead of the actual null value
$c = NULL; //so we change that to the actual null value
}
$getprojectnum = "SELECT ProjectNumber FROM tblProjects WHERE PROJECTNOID = '$p'"; //check
$getcustomerpo = "SELECT SequentialPONum FROM tblCustomerPOs WHERE CustomerPOID = '$c'"; //check
$getvendornum = "SELECT VendorNumber FROM tblVendors WHERE VENDORID = '$v'"; //check
$acpnhold = $conn->query($getprojectnum);
$accphold = $conn->query($getcustomerpo);
$acvnhold = $conn->query($getvendornum);
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
if($c){
$string = $acpn.'-'.$accp.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}elseif(!$c){
$string = $acpn.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}else{
echo json_encode('Error');
exit();
}
?>
The response on my webpage is ---2 instead of (ex: 18000-1-2-2). As mentioned earlier I think it is because they are objects but I am not quite sure. Any advice is appreciated.
Your problem is with this bit:
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
From the php docs:
object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, array $params ]] )
Your $acpn $accp and $acvn are not result objects. They are not even defined before you use them in those calls.
This should get the single column from each query result:
$acpn = $acpnhold->fetch_row()[0];
$accp = $accphold->fetch_row()[0];
$acvn = $acvnhold->fetch_row()[0];
Bear in mind you still have a major SQL Injection vulnerability with the original query calls.
Try like this code below:
$.ajax({
type: 'POST',
url: 'ft-final-v-po-num.php',
data: {
'p': p,
'c': c,
'v': v,
'cp': cp
},
success: function(msg){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
}
});
I have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)
$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');
header('Content-type: application/json');
echo json_encode($array);
and it echos as:
[{"id":1,"price":"325"},{"id":2,"price":"486"}]
now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as
counterval1 = 325;
counterval2 = 486;
but I can't seem to get it to read that way. Here is the script at the current moment.
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval + data[i].id = data[i].price;
console.log (counterval2);
});
$('#results').html(counterval2);
});
var counterval1 = 0;
var counterval2 = 0;
any help on this would be greatly appreciated.
you can't do that... but you can do this...
var counterval = [];
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval[data[i].id] = data[i].price;
console.log (counterval[2]);
});
$('#results').html(counterval[2]);
});
counterval[1] = 0;
counterval[2] = 0;
See my comment on your post. If you really want the vars to look like you explained:
eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);
I'm trying to pass image coordinates via json to a php file that should update the database.
I have this in jquery:
var coords=[];
var coord = $(this).position();
var item = { coordTop: coord.top, coordLeft: coord.left };
coords.push(item);
var order = { coords: coords };
$.ajax({
type: "POST",
data : +$.toJSON(order),
url: "updatecoords.php",
success: function(response){
$("#respond").html('<div class="success">X and Y Coordinates
Saved</div>').hide().fadeIn(1000);
setTimeout(function(){
$('#respond').fadeOut(1000);
}, 2000);
}
});
This is what updatecoords.php looks like:
<?php
$db = Loader::db();
$data = json_decode($_POST['data']);
foreach($data->coords as $item) {
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
$x_coord = mysql_real_escape_string($coord_X);
$y_coord = mysql_real_escape_string($coord_Y);
$db->Execute("UPDATE coords SET x_pos = '$x_coord', y_pos = '$y_coord'");
}
?>
The success message shows from the javascript however nothing gets updated in the database?
Any thoughts?
You have a + before $.toJSON. Meaning that the json string it returns will be converted to an integer - probably 0 or NaN.
Alex is right, but you can also take the quotes out from the preg_replace pattern. PHP naturally uses /.../ slashes to "quote" a regular expression.
try this
UPDATE coords SET x_pos = '".$x_coord."', y_pos = '".$y_coord."'
and look here how to use toJSON
EDIT :
try this
$.ajax({
type: "POST",
data : { coordTop: coord.top, coordLeft: coord.left ,coords: coords },
and in second code do this
$data = json_decode($_POST['data']);
$coordTop = mysql_real_escape_string($_POST['coordTop']);
$coordLeft = mysql_real_escape_string($_POST['coordLeft']);
$coords = mysql_real_escape_string($_POST['coords']);
foreach(.........
.....
.....
and then use those variables $coordTop , $coordLeft , $coords
Thanks for the help but this seemed to do the trick....
In javascript:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){ alert (response + mydata);
In Updatecoords.php:
$data = json_decode(stripcslashes($_POST['data']));
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
I would like to ask you for some help with my problem.
I have this php code, which I use to clean $pname from prepositions, white spaces, numbers etc. to make it more suitable for sorting.
$prepositions = array(" ", "tert-", "dl-"); //only a part of all
$patterns = array("'([0-9])'si", "/\b\w\b\s?/", "/[^a-zA-Z0-9\s]/");
$sname = preg_replace($patterns, '', str_replace($prepositions, "", strtolower($pname])));
I am trying convert this code to javascript but code is so massive. Here is part of it:
function createsname ()
{
if(document.getElementById('pname').value != '')
{
var myString = new String();
myString = document.getElementById('pname').value.toLowerCase();
var reg0 = new RegExp(" ");
var sname0 = myString.replace(reg0, "");
var reg1 = new RegExp(/\d/g);
var sname = sname0.replace(reg1, "");
document.getElementById('sname').value = sname;
}
}
Examples of php results:
1,2-Bis(3-Methylthiophene2-yl)ethane-1,2-dione
bismethylthiopheneylethanedione
4H-Cyclopenta[2,1-b3,4-b]dithiophene
cyclopentadithiophene
5-Acetyl-2-amino-4-(2-furanyl)-6-methyl-4H-pyran-3-carbonitrile
acetylaminofuranylmethylpyrancarbonitrile
5-Acetyl-2-amino-4-(4-methoxyphenyl)-6-methyl-4H-pyran-3-carbonitrile
acetylaminomethoxyphenylmethylpyrancarbonitrile
5-Acetyl-2-amino-6-methyl-4-phenyl-4H-pyran-3-carbonitrile
acetylaminomethylphenylpyrancarbonitrile
Tri-O-acetyl-D-glucal
acetylglucal
5-Amino-1,3-dimethyltricyclo(3,3,1,13,7) dekane hydrochloride
aminodimethyltricyclodekanehydrochloride
DL-2-Amino-1-propanol
aminopropanol
(S)-(+)-2-Amino-1-propanol
aminopropanol
a-(3-Aminopropyl)-w-(3-aminopropoxy)-poly (oxy-1,2-ethanediyl)
aminopropylaminopropoxypolyoxyethanediyl
N-(3'-Aminopropyl)-2-pyrrolidone
aminopropylpyrrolidone
1,1,1-(5,5,5-benzene-1,3,5-triyl-tri-thiophen-2-yl)-tris-ethanone
benzenetriyltrithiophenyltrisethanone
N-[(1,4-Benzodioxane-2-yl)carboxyl]piperazine
benzodioxaneylcarboxylpiperazine
(3R)-3-{[(Benzyloxy)carbonyl]amino}butanoic acid
benzyloxycarbonylaminobutanoicacid
1,5-Bis-(2-furanyl)-1,4-pentadiene-3-one
bisfuranylpentadieneone
1-[N,N-Bis(2-hydroxyethyl)amino]-2-propanol
bishydroxyethylaminopropanol
Bisphenol A bis(chloroformate)
bisphenolabischloroformate
Bisphenol A diacetate
bisphenoladiacetate
5''-Bromo-2,2'-5',2''-terthiophene-5-carboxaldehyde
bromoterthiophenecarboxaldehyde
tert-Butyldimethylamine
butyldimethylamine
(E)-3-Chloro-2-methyl-3-(2-thienyl)acrolein
chloromethylthienylacrolein
alpha-Cyano-4-hydroxycinnamic acid
cyanohydroxycinnamicacid
Di-tert-butyl dicarbonate
dibutyldicarbonate
trans-1,4-Dichloro-2-butene
dichlorobutene
a,a-Dichloromethyl methyl ether
dichloromethylmethylether
2,2-Dimethyl-1,3-dioxolane-4-methanol p-toluenesulfonate
dimethyldioxolanemethanolptoluenesulfonate
(R)-2,2-Dimethyl-1,3-dioxolane-4-methanol p-toluenesulfonate
dimethyldioxolanemethanolptoluenesulfonate
4a(R),9b(S)-(-)-cis-2,8-Dimetyl-2,3,4,4a,5,9b-hexahydro-1H-pyrido[4,3-b]indol
dimetylhexahydropyridoindol
4,4'-Dipyridyl N,N'-dioxide hydrate
dipyridylndioxidehydrate
Ethyl 1H-pyrazole-3-carboxylate
ethylpyrazolecarboxylate
Methyl 1H-benzo[4,5]furo[3,2-b]pyrrole-2-carboxylate
methylhbenzofuropyrrolecarboxylate
Methyl 4H-furo[3,2-b]pyrrole-5-carboxylate
methylfuropyrrolecarboxylate
4-Oxo-2,2,6,6-tetramethylpiperidinoxy
oxotetramethylpiperidinoxy
3-Oxo-3-(2-thienyl)propanenitrile
oxothienylpropanenitrile
1,4-Pentadien-3-ol
pentadienol
N-[3-Phenylcoumarinyl-(7)]-N'-(g-N,N'-dimethylaminopropyl)-urea
phenylcoumarinyldimethylaminopropylurea
N,N',N'',N'''-Tetraacetylglycouril
tetraacetylglycouril
2,3,4,6-Tetra-O-benzoyl-b-D-glucopyranosyl isothiocyanate
tetrabenzoylglucopyranosylisothiocyanate
DL-1,2,3,4-Tetrachlorobutane
tetrachlorobutane
2,4,6-Tri-tert-butylaniline
tritertbutylaniline
1,3,5-Tri-tert-butylbenzene
tritertbutylbenzene
3-Amino-2,3,4,5-tetrahydro-2-oxo-2H-1-benzazepin
aminotetrahydrooxobenzazepin
Tris(3-sulfonatophenyl)phosphine hydrate, sodium salt
trissulfonatophenylphosphinehydratesodiumsalt
2-(Tritylamino)-a-(methoxyimino)-4-thiazoleacetic acid hydrochloride
tritylaminomethoxyiminothiazoleaceticacidhydrochloride
So if you have ideas how can i write it in javascript please, help me.
var myString = document.getElementById('pname').value.toLowerCase();
var replaces = [" ", "tert-", "dl-", /([0-9])/si, /\b\w\b\s?/, /[^a-zA-Z0-9\s]/];
for ( var k in replaces ) {
myString = myString.replace(replaces[k], "");
}
Brad Christie proposition:
for ( var k = 0; k < replaces.length; k++ ) {
myString = myString.replaces(replace[k], "");
}
Well, based on the examples you gave and what I could test, here's what I came up with:
String.prototype.Lukas = function(){
return this.toLowerCase().replace(/(\(.*?\)|\[.*?\]|\b\w\b\s?|(?:dl|tert|\d+[a-z]){1,4}-|\W|\d)/ig, '');
};
DEMO
Again, only based on what I could see. Use it like this:
// assign the original string to a variable
var original = '1,2,4-Triazolo-[4,3,a]pyridin-3(2H)-one';
// then get the desired result using "Lukas()"
var result = original.Lukas();