I am sending a javascript array by using jquery to a php script.
In ajax I have a myarr variable but this variable can't be accessed in php.
Error is :
Undefined index myarr
Please Please help me. this is really important.
This is my jquery code:
for (var n = 0; n < arraySubId.length; n++) {
var ansArr = [];
for (var m = 1; m <= 11; m++) {
ansArr[m - 1] = $('#' + arraySubId[n] + '-' + m + '').val();
}
* $.ajax({
type: 'POST',
data: ({
'sub_id': arraySubId[n],
'myarr': ansArr
}),
url: 'Scripts/insert_feedback.php',
success: function(data) {
if (data == "1") {
} else {
alert(data);
}
}
}); *
}
When I access myarr variable in php, it's displaying:
Undefined index myarr.
Please Please help me.
And this is my php code:
<?php
session_start();
$prn = $_SESSION['username'];
$sub_id = $_POST['sub_id'];
$ans_arr = $_REQUEST['myarr'];
include 'dbclass.php';
$dbclass = new DBClass;
$mysqli = $dbclass->connect();
$query = "INSERT INTO ".$sub_id."(student_prn, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, date) values('$prn', '$ans_arr[0]','$ans_arr[1]','$ans_arr[2]',
'$ans_arr[3]','$ans_arr[4]','$ans_arr[5]','$ans_arr[6]',
'$ans_arr[7]','$ans_arr[8]','$ans_arr[9]','$ans_arr[10]', now())";
$msg = $dbclass->insert($query);
echo $msg;
?>
Try to convert your array to Json String and send it in JS, and in PHP decode it using json_decode()
Related
I'm making a stock table, where the user can input a number of stock to issue out, and this function is to verify, for each member of the table, whether or not the quantity of stock in the database is sufficient to make the issue.
When I breakpoint through the code on Chrome, it seems to never hit the inside code of the $.post until after its finished looping through the table. And by then the data that is supposed to be passed to AddIssue just becomes 1 and 10 and nothing else.
It's starting to drive me mad, so I'd appreciate a pointer on what I'm doing wrong here
var issueArray =[];
function VerifyIssue()
{
var numRows = document.getElementById("searchTable").rows.length - 2;
var running = true;
var str1 = "issue_";
while(running == true)
{
if (numRows < 0 && running == true)
{
running = false;
//insert code for success
break;
}
else if (running == false)
{
break;
}
var str2 = numRows;
var comb = str1.concat(str2);
var issue_element = document.getElementById(comb);
var q = issue_element.value;
var i = issue_element.name;
var idd = i.replace("issue_", "");
var trimId = idd.trim();
$.post
(
'includes/issueCheck.php',
{
id: trimId,
issueQuantity: q
},
function(result)
{
alert(result);
if (result < 0)
{
alert("One of more quantities inputted are greater than held in stock");
running = false;
}
if (result > 0)
{
addIssue(trimId, q);
}
}
);
numRows = numRows - 1;
}
alert(issueArray);
}
function addIssue(issueID, quant)
{
var item = {};
item.label = issueID;
item.value = quant;
issueArray.push(item);
}
This is the PHP that is called by the $.post
<?php
$server = 'SQL2008';
$connectionInfo = array( "Database"=>"rde_470585");
$conn = sqlsrv_connect($server,$connectionInfo);
$false = -1;
$true = 1;
$id = $_POST['id'];
$quantity = $_POST['issueQuantity'];
$query = "Select Quantity FROM Stock WHERE StockID = ?";
$param = array($id);
$res = sqlsrv_query($conn, $query, $param);
$row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC);
$dbQuantity = $row['Quantity'];
if ($dbQuantity < $quantity)
{
echo $false;
}
else if($dbQuantity >= $quantity)
{
echo $true;
}
Do you realise that your function(result){ ... } will only be called when the server response for your POST request is received? You have to build the code to take that delay into account.
I'm still working on this, reading up on Promises based on what #jojo said, but not sure if it's going to work for me.
How else can I make the javascript wait for a server response before resuming?
There are plenty of examples of using database records to disable certain dates (unavailable) using JSON and AJAX however for some reason, these are done in PHP. Is there reason why it isn't done in JAVA and how can I replace the PHP file with Java for the exact same result?
checkDates.php
<? php
$sql = "SELECT start from gbh_rooster_afwijkend WHERE dlnmrID = '".$_GET['dld'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$checkDates = array();
while ($row = mysql_fetch_assoc($res)) {
$checkDate['start'] = $row['start'];
$checkDates[] = $checkDate;
}
echo json_encode($checkDates);
?>
Javascript
$.getJSON('script/php/afwijkendrooster/checkDates.php?dld='+ id, function(json){dates=json;});
function checkAvailability(mydate){
var myBadDates = dates;
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd-mm-yy', mydate);
// start loop
for(var x in myBadDates)
{
$myBadDates = new Array( myBadDates[x]['start']);
for(var i = 0; i < $myBadDates.length; i++)
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
//end loop
return [$return,$returnclass];
}
See i have below Code in my javascript
var itemCount = 5, activeScroll = 0, countScroll = 0;
setInterval(function() {
if(countScroll == (itemCount - 2))
{
activeScroll = 0;
countScroll = 0;
$('#list').animate({scrollTop: 0});
}
else
{
activeScroll += 250;
countScroll += 1;
$('#list').animate({scrollTop: activeScroll});
}
}, 2000);
and my query string in php code is
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
i am trying to assign value of $adcount in javascript variable var itemCount;
query is running in test.php and javascript is scroller.js.
Please help me .
You can output javascript by test.php:
<?php
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
?>
<script type='text/javascript'>
var itemCount = <?php echo $adcount; ?>;
setupTimer(itemCount);
</script>
Make sure the scroller.js defines the function setupTimer(itemCount) that performs the task you want, instead of firing right away.
First you need to request the value from the server. Then you can assign it.
var itemCount;
setInterval(function() {
$.get('test.php', function(response) {
itemCount = response.itemCount;
// you scroll logic here
}, 'json');
}, 2000);
In test.php you should output the value by something like this:
$output = array(
"itemCount" => $adcount
);
print json_encode($output);
in scroller.js type this code:
$.ajax("test.php", {
type: 'post',
data: {
count:itemCount
},
sync: true,
success: function (adcount) {
itemCount=adcount;
}
});
in test.phptype this code:
if (isset($_POST['count']))
{
echo $adcount;
exit;
}
notice:you should use jquery file in your script for ajax
The code i'm trying to get to work is part of a price list of products from a db. It works almost all of it but i need one ajax to run multiple times, and it does, it even runs the success sentences but when i check the db its like it just ran once... i hope you can help me.
I take 2 values from inputs which are id and amount of the product, and i add them to the list when a button calls the send function, this is that part of the code:
function valores(cod, cant) {
if (cod != '') {
cot.push([cod, cant]);
i++;
}
return cot;
}
function send () {
event.returnValue=false;
var id = $('#id').val();
var amount = $('#cant').val();
var total;
if ($('#total').length > 0) {
total = document.getElementById('total').value;
} else {
total = 0;
}
$.ajax({
type: 'POST',
data: ({cod : id, cant : amount, tot : total }),
url: 'process/agprods.php',
success: function(data) {
$('#totals').remove();
$('#prodsadded').append(data);
valores(id, amount);
rs = $(document.getElementById('rs').html);
},
error: function () {
$('#rs').innerHTML = rs;
document.getElementById('note').innerHTML = "Error: The product doesn't exist.";
$('#handler-note').click();
}
});
}
(I translated some words to english that are originaly in spanish and to make it more readable to you)
So, the cot[] array keeps the product's id and amount, to use them in the next code, which runs when the list is complete and you hit a save button that calls this function:
function ncotiza () {
event.returnValue=false;
var nlist = $('#codp').val();
var day = $('#days').val();
$.ajax({
async: false,
type: 'POST',
data: ({listnumber: nlist, days : day}),
url: 'process/ncot.php'
});
j = 0;
while (j <= i) {
if (cot[j][0] != 0 && cot[j][1] != 0) {
var num = cot[j][0];
var cant = cot[j][1];
$.ajax({
async: false,
type: 'POST',
data: ({ listnumber : nlist, prodid: num, amount : cant }),
url: 'process/ncotpro.php',
success: function () {
alert('Success');
}
});
cot[j][0] = 0;
cot[j][1] = 0;
j++;
}
if (j == i) {
window.location.reload(1);
alert("Finished Successfully");
};
}
}
And it all runs fine, here's the PHP:
(ncot.php)
$listnumber = isset($_POST["listnumber"]) ? $_POST["listnumber"] : '';
$days = isset($_POST["days"]) ? $_POST["days"] : '';
$cons = "INSERT INTO pricelist (listnumber, diashabiles, cdate)
VALUES ('$listnumber', '$days', CURDATE())";
mysql_query($cons);
?>
(ncotpro.php)
$listnumber = isset($_POST["listnumber"]) ? $_POST["listnumber"] : '';
$prodid = isset($_POST["prodid"]) ? $_POST["prodid"] : '';
$amount = isset($_POST["amount"]) ? $_POST["amount"] : '';
$cons = "SELECT price, um
FROM inventory
WHERE listnumber = ".$prodid;
$result = mysql_query($cons) or die ("Error: ".mysql_error());
$row=mysql_fetch_assoc($result);
$umcons = mysql_query("SELECT uvalue FROM um WHERE id = ".$row["um"]) or die ("Error:".mysql_error());
$umres = mysql_fetch_assoc($umcons);
$vuum = $umres["uvalue"];
$fprice = $row["price"] * ($amount * $vuum);
$cons = "INSERT INTO cotpro (cotizacion, producto, amount, monto)
VALUES ('$listnumber', '$prodid', '$amount', '$fprice')";
mysql_query($cons) or die ("Error: ".mysql_error());
?>
The first ajax runs ok, then it also does the one that's inside the while, and it throw all the alerts but when i check the db it just made 1 row and not all it has to.
I'm sorry if it's too obvious or something, i've look a lot of questions and answers in this page and i've been trying to fix this for hours but i just dont see it.
Thank you beforehand.
Try to debug the 2nd jquery file via firebug.
what the value you return in i
while (j <= i) {
..
..
.
my problem is following:
I am using this code to pass a value to a different file called "benutzerstart.php". Debugging through the jquery shows, that the value in "var beta" is correct.
I do get a problem with getting the value to a PHP variable.
The error code is : "Notice: Undefined index: param in C:\xampp\htdocs\KVP\benutzerstart.php on line 76"
Referring to the error code my suggestion is that the passed value is not really passed to the php file.
JQuery code:
<script>
$('#form').submit(function() {
var arrayFromPHP = <?php echo json_encode($Email) ?>;
var newMail = $.trim($('#Email').val())
var pw1 = $.trim($('#Password').val())
var mailVorhanden = false;
var pwRichtig = false;
var idVondemShit = -1;
var tempindex = -1;
for ( var i = 0; i < arrayFromPHP.length; i++ ) {
// $.each(arrayFromPHP, function (i, val) {
if(newMail === arrayFromPHP[i].Email ){
mailVorhanden = true;
tempindex = i;
break;
}
};
if (mailVorhanden === true)
{
if(pw1 === arrayFromPHP[tempindex].pw)
{
idVondemShit = arrayFromPHP[tempindex].idName;
pwRichtig = true;
if(arrayFromPHP[tempindex].mode === "1")
{
location.href='startseite.html';
pwRichtig = false;
}
}
else
{
alert('Passwort oder Nutzername falsch.');
}
}
else{
alert('Passwort oder Nutzername falsch.');
}
var beta = arrayFromPHP[tempindex].idName
$.ajax({
url: 'benutzerstart.php',
data: {'param' : 'beta'},
});
return pwRichtig
});
</script>
PHP code from "benutzerstart.php":
<?php
// Collect data
mysql_connect("localhost", "root" , "Floradix94");
mysql_select_db("hallo");
$tstID = $_GET['param'];
$sql= "SELECT erfassung.Verbesserungsvorschlag,erfassung.megusta,login.Email,erfassung.id,erfassung.Betre ff FROM (erfassung INNER JOIN login ON erfassung.loginid=login.loginid)";
$query=mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)) {
$modals[] = array(
'id' => 'modal' . $row['id'],
'href' => '#modal' . $row['id'],
'FormDoneId' => $row['id'] . 'FormDoneId',
'Email' =>$row['Email'],
'Verbesserungsvorschlag' => $row['Verbesserungsvorschlag'],
'megusta' => $row['megusta'],
'betreff' => $row['Betreff'],
);
}
?>
Anyone got an idea?
Change this
data: {'param' : 'beta'},
To
data: {param : 'beta'},