PHP - Passing Javascript Array To Php
Hello Everyone!
I have created a javascript array which now i want to pass to php, so php can store those values to mysql. So please anyone can suggest me how do i pass it to php? Any help will highly be appreciated! Similar TutorialsThis topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=332103.0 Given the following array $documentlist, displayed from print_r Array ( [MerchantDocumentInfo] => Array ( => Array ( [documentID] => 2760322451 [generatedDateTime] => 2010-08-03T16:02:45-07:00 ) [1] => Array ( [documentID] => 2761837402 [generatedDateTime] => 2010-08-03T23:01:15-07:00 ) ) ) I'm trying to figure out the syntax to use the documentID as a dynamic variable When I 'hard code' the variable, I get the document I want eg $order = $t->GetDocument('2760322451'); -- returns requested document info into $order array where $order is an array and $t are my connection credentials. I've made numerous attempts, but get errors in anything I try. Can someone tell me the correct syntax to use to pass a dynamic value for documentID from the $documentlist array at the top? I've tried $order = $t->GetDocument($documentlist['MerchantDocumentInfo' ]['documentID']) ; and get ===> syntax error, unexpected '[', expecting ']' $order = $t->GetDocument($documentlist->MerchantDocumentInfo[0]['documentID']) ; get nothing $order = $t->GetDocument($documentlist->MerchantDocumentInfo[1]['documentID']) ; get nothing $order = $t->GetDocument($documentlist->MerchantDocumentInfo[1][documentID]) ; get nothing Thanks in advance for any ideas, I've been trying to figure this out for days. I have some function or method. Is there a better design patter to implement this?
function myFunction($a=null,$b=null,$c=null,$d=null,$e=null,$f=null,$g=null,$h=null) { //Do a bunch of stuff }Maybe the second function? function myNewFunction($data=array()) { $data=array_merge(array('a'=>null,'b'=>null,'c'=>null,'d'=>null,'e'=>null,'f'=>null,'g'=>null,'h'=>null),$array); //Do a bunch of stuff }Please provide decision making factors why you would use one approach over the other. Hi all, new to php and struggling passing an array via url. first page: Code: [Select] $str = serialize($cartinfo); $strenc = urlencode($str); <A href="/test/getcart.php?cartinfo=<?PHP echo $strenc; ?>">test</A> Which does add a long string to the URL so I guess to here it's fine. Second Page: Code: [Select] <?PHP $cartinfo = unserialize($_GET["cartinfo"]); var_dump($cartinfo); ?> However all I get is: bool(false) Any advice would be great, I also tried adding $cartinfo to the session, but this didn't work either. Surely passing variables should be straight forward??? Thanks. $seat_s is a $var that can have multiple values depending on a form in a previous page. this code works fine as is, but i need to pass the array into a 3rd page. i have no idea how to do this from the code below. ive tried passing the array straight into a _post then _get on the next page but that only holds the 1st value and not all of them. suggestions please.... thanks <?php $seat_s = $_POST['seats']; foreach($_POST['seats'] AS $seat) { $rowId = substr($seat, 0, 1); $columnId = substr($seat, 1); echo $rowId . $columnId . ", "; } ?> I recently posted a simple query about ISSET and finally got that simple problem solved thanks to you guys. But I've hit a new snag. I've create a simple sort of cart, or record counter. While I can add/remove/clear items and display their affilated arrays, I don't know how to cycle through a multidimensional array that is dynamically set.
Something like $_SESSION['Primary'][$items][$attributes] - Where $items is a dynamic set, and $attributes is a fixed set of keys with values.
I can target individual $Items, or display all the items in there. But I can't display all the Items and their subsequent $attributes aswell. Do I have to write 1 set of Ajax code for just displaying the $items, and another for each individual set of $attributes? Or is their a way to cycle through each $item, and then all of it's(or specific) $attributes and values? I've tried using loops which logically work, but I can't pass it through json_encode.
Is there any documentation I could read in relation to this? I feel this is the key component to manuvering through a database of sorts. I'm just not entirely sure how to go about accessing multidimensional Array's without a ton of code that becomes redudent. And even then, it wouldnt work well with a dynamic setup.
Edited by 7blake, 07 November 2014 - 01:39 PM. I have the registration form blues! form 1 collects the classes chosen, and passes an array of classes chosen(on a previous page), in a hidden field: <input type="hidden" value="<?= $c_row['workshop_id'] ?>" name="wid[]" /> form 2 makes it a variable $wid = $_POST['wid']; I'm trying to pass it to form 3, using the hidden input again, this time as a variable: $wid = $_POST['wid']; <input type="hidden" value="<?= $wid ?>" name="wid[]" /> The next page is a printable page. But I can't do anything with the classes, because it's some how made an array of an array??? I wrote: $wid = $_POST['wid']; print_r($wid); This produces--- Array ( => Array ) I want it to give me the original array? Is there a different way to do this? Okay heres the problem. I have a form which displays items that sit within a packet. (In this case its called Wireless Package 1). Each item has its own specific value, which can be any string, hench why there is an 'input type= text' in the value column in the table. Each of these values is stored in a table, with the primary key 'piid', (show as a hidden field within 3rd column). The problem is when im posting the array 'values[]' I cant distinguish between what value needs to be referenced againist a piid, how do i obtain these individual ID's and Values in a loop so they can turned into a MySql Strings????? I tried using an explode function but got no where, any help is very much apprieciated! This is the code for the form displayed. <table border="1" cellpadding="5" cellspacing="5"> <tr> <th>Item ID</th> <th>Item</th> <th>Value</th> <th>Remove</th> </tr> <form action="edit_packet.php" method="post"> <?php foreach($packages as $packet):?> <tr> <td> <?php echo $packet['piid'] ;?> </td> <td> <?php echo $packet['desc'] ;?> </td> <td> <input type="hidden" name="values[]" value="<?php echo $packet['piid'];?>,," /> <input type="text" name="values[]" value="<?php echo $packet['value']; ?>" /> <input type="hidden" name="values[]" value="///" /> </td> <td> <form action="delete.php" method="post"> <input type="hidden" name="pid" value="<?php echo $packet['piid'];?>"/> <input type="submit" value="Delete Packet"> </td> </tr> <?php endforeach; ?> </table> <input type="submit" value="Submit" /> </form> Hi guys, Is there an html code that allows you to array a form input? and once you passed the form, how do you extract the data then insert it to the database? Thanks I am passing an array to an option list but if a value has two words, the second word doesnt get sent via POST. So if the value should be THE ONE, the word ONE doesnt get sent via POST. Kinda wierd, wondered if there is an easy explanation for this? Code: [Select] <?php echo '<SELECT name=carrier>'; foreach ($allcar as $key => $value) { echo '<OPTION value=' . $value . '> ' . $value . ''; } echo '</select>'; ?> I have an issue with a form where people choose from several classes, and how many people they're enrolling. If they choose the first class, select the number of students and hit submit, it is supposed to carry the number of students to the 2nd page where a variable is created for it: $qty = $_POST['participantqty']; It works if they pick the first class and choose a number of students. It works if they pick the first class and another, plus the number of students for each. But if they choose any one class except the first one (and only that class), choose their number of students and submit... This is when it doesn't carry the number forward... It also glitches when they select two classes that don't include the first class. It carries the number of students for one, but not the other. qty_insert and qty_total on page two are where the data dissappears. I'm assuming it has something to do with the array, but I'm in a little over my head. On the second page, I added in print_r($myarray); and it shows the variable is passing to the second page. page one: Code: [Select] <form method="post" action="register2.php"> <? //output each row while ($c_row = mysql_fetch_array($result_all_events)){ $display = date("F j", strtotime($c_row['workshop_date'])) ; $i++; //date('d m y', strtotime($mysql_date)); ?> <input type="checkbox" name="workshop_id[]" value="<?= $c_row['workshop_id'] ?>" /> <?= $c_row['workshop_title'] ?> </td><td><?= $c_row['workshop_date'] ?></td><td><select name="participantqty[]" id="" class=""> <option value="">select</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="10">9</option> <option value="10">10</option> </select> $ <?= $c_row['workshop_price'] ?></td></tr><tr><td colspan=3><hr></td></tr> <? } //end while ?> <input type="submit" value="Submit" class="buttontype"> and on page two where it totals things up: Code: [Select] <form method="post" action="register3.php"> <?php // connect to database include("dbconnectionfile.php"); $fname = mysql_escape_string($_POST['fname']); $lname = mysql_escape_string($_POST['lname']); $address = mysql_escape_string($_POST['address1']); $address2 = mysql_escape_string($_POST['address2']); $city = mysql_escape_string($_POST['city']); $state = mysql_escape_string($_POST['state']); $zip = mysql_escape_string($_POST['zip']); $phone = mysql_escape_string($_POST['phone']); $fax = mysql_escape_string($_POST['fax']); $email = mysql_escape_string($_POST['email']); $hear = mysql_escape_string($_POST['hear']); $how1 = mysql_escape_string($_POST['how1']); $how2 = mysql_escape_string($_POST['how2']); $how3 = mysql_escape_string($_POST['how3']); $how4 = mysql_escape_string($_POST['how4']); $res = mysql_escape_string($_POST['resident']); if( $res == NULL ) { $res="No"; } $how = $how1 . $how2 . $how3 . $how4; $query_insertItem = "INSERT INTO tbl_registration (reg_fname, reg_lname, reg_address, reg_address2, reg_city, reg_state, reg_zip, reg_phone, reg_fax, reg_email, reg_how, reg_how_detail, reg_dc) VALUES ('$fname', '$lname', '$address', '$address2', '$city', '$state', '$zip', '$phone', '$fax', '$email', '$hear', '$how', '$res')"; $dberror = ""; $ret = mysql_query($query_insertItem); $reg_id = mysql_insert_id(); $id_reg = $reg_id; // store all posted intemnos and descriptions in local arrays $ids = $_POST['workshop_id']; $qty = $_POST['participantqty']; echo $qty; if(sizeof($_POST['workshop_id'])) { // loop through array $number = count($ids); for ($i=0; $i<=$number; $i++) { // store a single item number and description in local variables $itno = $ids[$i]; $qty_insert = $qty[$i]; $query_insertItemWorkshop = "INSERT INTO tbl_registration_workshop (registration_id, workshop_id, regworkshop_qty) VALUES ('$reg_id', '$itno', '$qty_insert')"; $dberror = ""; $ret = mysql_query($query_insertItemWorkshop); $query_selectAllItems_events = 'SELECT * FROM tbl_workshops where workshop_id = '.$itno; @$result_all_events = mysql_query($query_selectAllItems_events); @$numRows_all_events = mysql_num_rows($result_all_events); @$num=mysql_num_rows($result_all_events); @$z_row = mysql_fetch_array($result_all_events); $qty_total=$qty_insert*$z_row['workshop_price']; $total = $total + $qty_total; // the qty_insert and the qty_total below are what appear blank. if ($ids[$i] <> '') { echo "Description:</b> ". $z_row['workshop_title'] ." " . $qty_insert . " at ". $z_row['workshop_price'] ." each: </td><td valign=top> $". $qty_total ."<br>"; } } } ?> <input type="hidden" name="reg_id" value="<?= $id_reg ?>" /> <input type="hidden" name="total" value="<?= $total ?>" /> <input type="submit" value="Checkout now!" /></form> i created an array like this while{ $ir = 0; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['id_sub']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['seminar_topic']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['seminar_mark']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['attendance']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['internal_mark']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['external_mark']; $ir++; } echo "<input type='hidden' name='ar_std' id='ar_std' value='$stud' /> </table>" ; and it is able to print in the same page using foreach ($stud as $v1) { echo "$v1\n<br>"; foreach ($v1 as $v2) { echo "$v2\n<br>"; } } and in the next page $ar_stud[]=$_POST["ar_std"]; I'm getting an error PHP Warning: Invalid argument supplied for foreach() in save.php on line 25 PHP Stack trace: Hi all Basically, I have a form which when done will calculate a quote for turf for given areas. Basically each time the user specifies an area it goes into an array, and they can add as many as they want, but the problem seems to be once submitted and it arrives back into the program, it isn't decoding so the multidimensional array is lost. What am I doing wrong here? Full code below, thanks in advance Ste Code: [Select] <?php // Framework // Get the sections $sections_array = base64_decode(unserialize($_POST['sections'])); // Build the rest of the array foreach ($sections_array as $section) { $sections[] = base64_decode(unserialize($section)); } // Set the initial unit $units = $_POST['units']; // Do the new add if ($_POST['a'] == 'add_section') { // Add the new measure if ((is_numeric($_POST['width'])) && (is_numeric($_POST['length']))) { $sections[] = array('length' => $_POST['length'], 'width' => $_POST['width']); } } // Build the output foreach ($sections as $section) { $output .= '<strong>'.$section['width'].' wide</strong> x <strong>'.$section['length'].' long</strong><br />'; $sections_array = base64_encode(serialize($section)); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <style type="text/css"> body,td,th { font-family: Verdana, Geneva, sans-serif; font-size: 11px; } body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; } .wrap { text-align: center; height: 350px; width: 410px; padding: 0 10px; } </style> </head> <body> <div class="wrap"> <h2>Turf Calculator</h2> <p>To begin, enter the width and length of the first area of garden you wish to turf. You can keep adding sections to work out the final quantity required.</p> <p><?php echo $output; ?></p> <form id="form1" name="form1" method="post" action=""> <table width="0" border="0" cellspacing="0" cellpadding="2"> <tr> <td>Length:</td> <td><input type="text" name="length" id="length" /></td> </tr> <tr> <td>Width:</td> <td><input type="text" name="width" id="width" /></td> </tr> <?php if ($units == '') { ?> <tr> <td>Units:</td> <td><select name="units" id="units"> <option value="feet">Feet</option> <option value="m" selected="selected">Metres</option> <option value="yards">Yards</option> </select></td> </tr> <?php } ?> </table> <p> <input type="submit" name="add" id="add" value="Add This Section" /> <input name="a" type="hidden" id="a" value="add_section" /> <input name="sections" type="hidden" id="sections" value="<?php echo base64_encode(serialize($sections_array)); ?>" /> <?php if ($units != '') { ?> <input name="units" type="hidden" id="units" value="<?php echo $units; ?>" /> <?php } ?> </p> </form> <p> </p> </div> </body> </html> Hello all, I'm hoping someone can help me out. Here is the code I have for a page that contains a user form: <?php include "include/dbc.php"; include "include/header.inc"; ?> <style type="text/css"> .mydate{ color:#00F; text-decoration:underline; cursor:pointer; } </style> <script type="text/javascript"> function displayDate(d){ var date=new Date(); var D=date.getDate(); date.setDate(D+d); var YYYY=date.getFullYear(); var MM=date.getMonth()+1; MM<10?MM='0'+MM:null; var DD=date.getDate(); DD<10?DD='0'+DD:null; var span=document.getElementById('date'); span.innerHTML= 'Entries for '+MM+'/'+DD+'/'+YYYY; } onload=function(){displayDate(0)}; </script> <h1>Food Diary</h1> <div class="full"> <center><div><span class="mydate" onclick="displayDate(-1)"><img src="images/left_arrow.png" border="0">Yesterday</span> <span id="date" style="font-size:2em;"></span> <span class="mydate" onclick="displayDate(1)">Tomorrow<img src="images/right_arrow.png" border="0"></span></div><br /> <a href="#" onclick="displayDate(0);return false;">Today</a> </center> <div class="full"> <form name="exercise" id="exercise" method="GET" action=""> <center><table> <tr> <td><h3>Add an Activity</h3></td> </tr> <tr> <td><input name="NewSearchString" style="width: 100px" type="text"/> <input type="submit" value="Search" /> </td> </tr> <tr> <td> <select name="activity"> <option value="_">Activity Browse...</option> <option value="all">All Activities</option> <option value="biking">Biking</option> <option value="condition">Conditioning</option> <option value="dancing">Dancing</option> <option value="fish">Fishing & Hunting</option> <option value="Home">Home Activities</option> <option value="misc">Miscellaneous</option> <option value="music">Music Playing</option> <option value="occupation">Occupation</option> <option value="running">Running</option> <option value="sports">Sports</option> <option value="walking">Walking</option> <option value="water">Water Activities</option> <option value="winter">Winter Activities</option> </select> <input type="submit" value="Submit" /></td></tr></table></center></form> </td> </tr> </table> </center> <table width="100%"> <tr bgcolor="#66CC33"> <td><div>Activity</div></td> <td><div>Specific Activity</div></td> <td><div>Time (hh:mm)</div></td> <td><div>Distance</div></td> <td><div>Units</div></td> </tr> <tr bgcolor="#66CC33"> <td><div></div></td> <td><div></div></td> <td><div></div></td> <td><div class="Float"></div></td> <td class="cp_Distance"><div></div></td> </tr> <?php if(isset($_GET[activity])) { $category=$_GET[activity]; $result = mysql_query("SELECT * FROM exercise WHERE type='$category'"); ?> <form action="add_activity.php" method="POST"> <?php while($row = mysql_fetch_array($result)) { echo '<tr><td><div>'.$row[Type].'</div></td>'; echo '<td><div>'.$row[Name].'<input type="hidden" name="exerciseid" value="'.$row[Name].'"></div></td>'; echo '<td><div><input type="text" name="duration['.$row['Name'].']"></div></td>'; echo '<td><div><input type="text" name="distance['.$row['Name'].']"></div></td>'; echo '<td><div><select name="metric[]"> <option value="mile" name="mile">mile</option> <option value="Km" name="Km">km</option> <option value="M" name="M">m</option> <option value="Yard" name="yard">yrd</option> <option value="Feet" name="feet">ft</option> </select></div></td></tr>'; } mysql_close(); ?> <tr><td colspan="6" align="center"><input type="submit" name="submit" value="Add Activities" onClick="return confirm( 'Are you sure you want to submit the activities?');"></td></tr> </form> <?php } ?> <tr bgcolor="#66CC33"> <td><div></div></td> <td><div></div></td> <td><div></div></td> <td><div class="Float"></div></td> <td class="cp_Distance"><div></div></td> </tr></table> And here is the page that the user information is supposed to be passed to: <?php include "include/dbc.php"; include "include/header.inc"; $duration = $_POST["duration['.$row['Name'].']"]; echo '<h1>Added Activities</h1>'; echo $duration; ?> Well, this isn't working for me. The second page code returns this error: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING When I execute print_r, the values are returned to me. So I have two questions: 1) What do I need to do to change the code on the 2nd page to echo and POST the array? 2)The database contains multiple exercises under the same name. So, when the variables are passed to the 2nd page. All the values are returned regardless of whether they have been filled out or not. What can be done to only returned the user input and not the blank variables? This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=347628.0 Okay, I have been looking into this for the last 3 hours, and cant find shit. I have a page with a javascript game where the player moves around on a map. They have an X and Y coordinate, but I'm having a problem. The problem is I need to store that info in a database, and I'm having trouble learning AJAX. Heres a little list of things: Play loads the game. A php variable is taken from a database. The player goes to those X and Y coordinates. The player may move around. Once they move, the player is sent to a php page that updates the Database information. The page is refreshed to the game again, where they may then move around some more. The problem is, when the page is changed the values are lost. For some reasons cookies aren't working at all (like just not working for anything, even a completely different file.) I heard something about using $_GET or $_POST, but I dont see how... This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=355358.0 Hello, I have below javascript, which I need to put in a new php page. However I need the vistiors to pass in the username to the script either by clicking the link for that user or by entering a value on the website. I am not sure how can I do this in php script and modify below java script to make it work. Any help will be greatly appreciated. <pre class="example"> $(function(){ $(".tweet").tweet({ join_text: "auto", username: "NEED_TO_BE_PARAMETER", avatar_size: 68, count: 25, auto_join_text_default: "said,", auto_join_text_ed: "I", auto_join_text_ing: "I wase", auto_join_text_reply: "I replied", auto_join_text_url: "I was checking out", loading_text: "loading..." }); }); </pre> <div class='query'></div> <script type="text/javascript"> $(function(){ $(".example").each(function(i, e){ eval($(e).text()); }); }); </script> Hello, I'm first time posting here, my PHP Javascript and HTML level is "trial, error, google", I've done some scripts, but now I'm facing one problem. Here's a code example: <?php $sa = array("Text without quotes.", "Text with 'quotes'.", "Text with \"Double Quotes\".", "Text With \"BOTH' kind of quotes."); echo "<A HREF='javascript:void(alert('".htmlspecialchars($sa[0], ENT_QUOTES)."'))'>Test One</A><BR/>"; echo "<A HREF='javascript:void(alert('".htmlspecialchars($sa[1], ENT_QUOTES)."'))'>Test Two</A><BR/>"; echo "<A HREF='javascript:void(alert('".htmlspecialchars($sa[2], ENT_QUOTES)."'))'>Test Three</A><BR/>"; echo "<A HREF='javascript:void(alert('".htmlspecialchars($sa[3], ENT_QUOTES)."'))'>Test Four</A><BR/>"; ?> What I'm trying to do is pass array of strings with quotes in them to my javascript, I tried using addslashes, htmlspecialchars but none of them work correctly. Whats the Right way to pass a string how do I preprocess it so javascript understands it correctly? Sorry if it's very simple or common question, I must have missed it in FAQ section. Thank you. |