I am having a bit of trouble with this bit of code. I am to take the values of 4 inputs, pass them to a PHP API using jQuery, compute a password with the PHP API file I have created and return that password as the data argument as a json_encoded. Below you will find the code:
PHPPasswordGenerator.php
<?php
header("Content-Type: application/json; charset: UTF-8;");
$letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$special = array('!','?',"'",'"','£','$','%','&','/','(',')','=','#','#','§','[',']','{','}');
$minLetters = array();
$maxLetters = array();
$numbers = array();
$specialCharacters = array();
$final = '';
$min = $_REQUEST["typeA"];
$max = $_REQUEST["typeB"];
$num = $_REQUEST["typeC"];
$spec = $_REQUEST["typeD"];
if(isset($min) or isset($max) or isset($num) or isset($special)){
for($i = 0; $i < $min; $i++){
array_push($minLetters, $letters[rand(0,count($letters)-1)]);
}
for($i = 0; $i < $max; $i++){
array_push($maxLetters, strtoupper($letters[rand(0,count($letters)-1)]));
}
for($i = 0; $i < $num; $i++){
array_push($numbers, rand(0,9));
}
for($i = 0; $i < $spec; $i++){
array_push($specialCharacters, $special[rand(0,count($special)-1)]);
}
$final .= implode('',$minLetters) . implode('',$maxLetters) . implode('',$numbers) . implode('',$specialCharacters);
}
print(json_encode($final));
?>
jQuery Code
$(document).ready(function(){
//Chiamata AJAX sui dati generati dal generatore di Password in PHP
$("#generator").on("click", function(){
//Mentre il focus è sull'input, modifica il valore val()
$.getJSON("passwordgenerator.php",
{
typeA : $("#typeA").val(),
typeB : $("#typeB").val(),
typeC : $("#typeC").val(),
typeD : $("#typeD").val()
},
function(data){
console.log("Success: " + data);
$("#generated").append("<h3></h3>").html(data);
}).fail(function(err){console.log(err)});
});
});
This is part of the body
<form>
<label for="A">Lettere Minuscole</label><input type="text" name="typeA" id="typeA">
<label for="B">Lettere Maiuscole</label><input type="text" name="typeB" id="typeB">
<label for="C">Numeri</label><input type="text" name="typeC" id="typeC">
<label for="D">Caratteri Speciali</label><input type="text" name="typeD" id="typeD">
<button id="generator">Generate Password</button>
</form>
<div id="generated"></div>
Now, the thing is: whenever I put a number inside the inputs and send it to the PHP file, the $final variable is json_encoded and sent back to the javascript file. If I do something like console.log(data), I actually get to see a randomly generated password with the specs I wanted it to be, but then I try to do something like:
$("#generated").text(data);
but the data doesn't go inside generated. I also tried to use html(data), but to no use. I did a console.log(typeof data); to see that it really was a string, as I wanted, and it actually is.
JSON.stringify(jsondata) to convert JSON into string. If you want to parse data string to JSON than use JSON.parse(string). I didn't get what is your actual question
So, the thing is I had to use val() and $.getJSON() at all costs, because the professor wanted so! The problem: I was using a form. The data passed as expected, but when I tried to append the data to an HTML element, since this event would occur in the same time the default form event would occur, the data would not get appended.
Removing the element was all it took. I could have also prevented default, yes.
Thank everyone for the nice help! :)
Related
i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>
Referring this post how-to-prevent-echo-in-php-and-catch-what-it-is-inside i am trying to get the output values from below mentioned php file but i can see still the values are getting printed in output of my php page.Any other suggestion are also welocme to get the output content from my php file to string without getting it echoed.Thanks!
<?php include('Crypto.php')?>
<?php
$workingKey='XXXX'; //Working Key should be provided here.
$encResponse=$_POST["encResp"]; //This is the response sent by the Server
$rcvdString=decrypt($encResponse,$workingKey); //Crypto Decryption used as per the specified working key.
$order_status="";
$order_id=0;
$decryptValues=explode('&', $rcvdString);
$dataSize=sizeof($decryptValues);
echo "<center>";
for($i = 0; $i < $dataSize; $i++)
{
$information=explode('=',$decryptValues[$i]);
if($i==0) $order_id = $information[1];
if($i==1) $tracking_id = $information[1];
if($i==3) $order_status = $information[1];
}
ob_start();
echo $order_id."_";
$out1 = ob_get_contents();
echo $tracking_id."_";
$out2 = ob_get_contents();
echo $order_status;
$out3 = ob_get_contents();
ob_end_clean();
var_dump($out3);
?>
JAVASCRIPT code to get echo'ed values in HTML format
class MyJavaScriptInterface
{
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(final String html)
{
String order_page = ""+Html.fromHtml(html);//process php output to html
String CCAvenueOrder_id = order_page.split("\\_")[0];
String CCAvenueTacking_id=order_page.split("\\_")[1];
String CCAvenueOrderStatus=order_page.split("\\_")[2];
// process the html as needed by the app
String status = null;
if(html.indexOf("Failure")!=-1){
status = "Transaction Declined!";
}else if(html.indexOf("Success")!=-1){
status = "Transaction Successful!";
}else if(html.indexOf("Aborted")!=-1){
status = " Transaction Cancelled!";
}else{
status = "Status Not Known!";
}
//Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),StatusActivity.class);
startActivity(intent);
}
}
Like in the comments of your question you can store the input in a variable. The use of the output buffer is not necessary, at least not in your example.
<?php
$workingKey='XXXX'; //Working Key should be provided here.
$encResponse=$_POST["encResp"]; //This is the response sent by the Server
$rcvdString=decrypt($encResponse,$workingKey); //Crypto Decryption used as per the specified working key.
$order_status="";
$order_id=0;
$decryptValues=explode('&', $rcvdString);
$dataSize=sizeof($decryptValues);
$output = "<center>";
for ($i = 0; $i < $dataSize; $i++) {
$information=explode('=',$decryptValues[$i]);
if($i==0) $order_id = $information[1];
if($i==1) $tracking_id = $information[1];
if($i==3) $order_status = $information[1];
}
$output .= $order_id."_";
$output .= $tracking_id."_";
$output .= $order_status;
echo $output; // response for ajax request as simple string
?>
If this does not work out for you please show us what is being echo'ed.
The best way to check what's going on inside running code is to use a debugger, for example xdebug. Find out how to install it and use with your IDE of choice, then place breakpoints and use watches to peek inside variables. Here's how to do it with PhpStorm.
If you cannot install a debugger, or you absolutely need to persist the values, learn the concept of logs. There is a PHP-FIG standard for logging (PSR-3) and at least one tool that implements it - for example, Monolog.
Sorry to add another JavaScript object to the mix. I'm just having a little trouble wrapping my head around this as it is a little more complex than i have ever dealt with.
Like the title states, i'm trying to create a JavaScript Object or perhaps a multidimensional array of a MySQL Database. For testing purposes i'm only using three tables from my database even though eventually it will store tens of tables. These tables are called "Interfaces", "IPAM", and "DNSF".
The reason i would like to complete this task is that, i am trying to create a heavy ajax page which dynamically knows when tables are added, updated, deleted etc, and automatically reflects this without having to add more code. I am doing this by writing javascript with php in addition to various other ajax callbacks spitting out html and variables.
Let me start out with my hardcoded HTML. All other html is created dynamically. This too will soon be created dynamically to add buttons to my website without adding code.
<body>
<div class = "form">
<button type="button" class = "formbutton" value = "Interfaces" onclick="inputChoice('Interfaces')">Interfaces</button>
<button type="button" class = "formbutton" value = "IPAM" onclick="inputChoice('IPAM')">IPAM</button>
<button type="button" class = "formbutton" value = "DNSR" onclick="inputChoice('DNSR')">DNSR</button>
</div>
<div class = "tableDiv" id="myTableDiv" style="height:1000px;width:1000px;border:1px solid #ccc; overflow: scroll;"><table id = "myTable"></table></div>
</body>
Before any buttons or events are executed, the first thign my page does is issue ajax requests within a $( document ).ready(function() { function. My issue is that i have to code a seperate ajax request for every single table. I'll show an example here where i fetch interface table data:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
InterfacesCols = data.split(" ");
InterfacesCols.pop();
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
for(j = 0; j < InterfacesCols.length; j++){
if(InterfacesCols[j] != null){
myString = myString + '<td id = "visibleDef">' + items[i][InterfacesCols[j]] +'</td>';
}
}
myString = myString + '</tr>';
Interfaces.push(myString);
}
});
}
});
This ajax request ultimately creates an array of html strings that are used to create the table. Interfaces[] contains each html row. InterfacesCols contains the names of each column. I have to write this block of code for every single table.
What i want to do is put my "Interfaces[]" like arrays and "InterfacesCols[]" like arrays within a master array so that i can create a template and not have tons of the same code.
Lets call this master array tables. This would allow me to put my ajax in a for loop and loop through every table array rather than hardcode it.
tables[0] would be interfaces[], tables[1] would be ipam etc.
In addition to my ajax request blocks where i initially gather my data from the database. I also have my function "inputChoice(string)", where i actually generate a table from this data. I do so by changing inner html of my table. I dont wan't to have to redirect my page. This works fine, but once again i have to create a new block of code for every single table. These blocks of code are massive right now because they include garbage collection for the DOM and also the code for handling massive data sets(>10,000) without browser slow down. I will refrain from posting that block unless necessary. The ajax calls require the same thing.
Here is the php where i originally create the empty array variables by generating javascript:
<?php
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
echo '<script>';
try{
$stmt->execute();
echo 'var tables = [];';
while($row = $stmt->fetch()){
echo 'var '.$row['TABLE_NAME'].' =[];';
echo 'tables += '.$row['TABLE_NAME'].';';
echo 'var '.$row['TABLE_NAME'].'Cols =[];';
}
echo 'console.log(tables[1]);';
}catch(PDOException $e){
echo $e;
}
echo '</script>';
?>
The above php is only called by using an statement on my index. No Ajax.
The link my ajax calls is this:
<?
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
//$stmt2->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
foreach($colnames as $value){
print $value ." ";
}
?>
The above ajax servers only the purpose of fetching column names and returning the names in a space delimeted string to be parsed and turned into an array via javascript, which you can see in my ajax call.
My getJson ajax code is here:
<?php
include "connect.php";
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
$sql = "SELECT * FROM ".$_GET['table']." LIMIT 17000";
$stmt2 = $DBH->prepare($sql);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
try{
$stmt2->execute();
while($row = $stmt2->fetch()){
foreach($colnames as $value){
if($row[$value] == null){
$row[$value] = "";
}
}
$row = array('id' => $i) + $row;
$items['post'][]=($row);
$i++;
}
}
catch(PDOExcetipn $e){
echo $e;
}
print json_encode($items);
?>
The above php seems slightly redundant to me as i fetch the column names again. However this time i also include the actual data. Line by line.
This is basically all of my code i have written for this project. The only code i did not include was my javascript inputChoice() function. Which as i stated above is very bulky and really doesnt do anything the ajax doesnt do when it comes to utilizing the arrays. This is a massive post, so i apologize for the wall of text. I am not sure exactly what the next step is for me to code this better in the way i described. Any input would be very much appreciated!
If I'm correct you want to automate the table generating.
Your index php block retrieves all tables from the DB.
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
So we need to add those to a master table pseudo code:
tables = [];
for (table in tableSQL)
{
tables[table] = tableSQL[table];
tables[table]['cols'] = [];
}
Now you have a master table array containing all your tables.
Let's loop through these. pseudo code:
for (table in tables)
{
retrieveColsWithData(table);
}
function retrieveColsWithData(tableKey)
{
//table = key = table name in DB
$.ajax({url:"/ryan/nonEmber/ajax.php?table="+table, etc.
//rest of the ajax call you're doing. Pass the key var to the JSON function
});
}
The function above loops through all the tables and retrieves the colls. When the JSON request returns you simply add the colls to table[key]['cols'].
Now you can simply iterate over the tables master with a for in or Object.keys and draw the HTML containing the data.
You can reuse retrieveColsWithData connected to your inputChoice to reload the data.
I have this basic HTML:
<div id="main">
<form id="search_form" role="form" action="" method="post">
<div class="form-group">
<input type="text" class="form-control" name="txt_search" id="txt_search" placeholder="Enter name here" autocomplete="off" >
<p></p>
<button type="submit" id="btn_search" class="btn btn-default">Retrieve </button>
</div>
</form>
<div class="result" id="result">this element used by jquery and replaced by db</div>
</div>
I want the user to type in their search query and click the btn_search which will "hopefully" populate (without refreshing the page) the results div (eventually I want to use a graph but for the time being a table is fine).
I have this within my javascript file, specifically this part under the $(document).ready...
$('#btn_search').click(function(){
$.ajax({
url: './php/search.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = rows[0];
var vname = rows[1];
$('#result').append("<b>id: </b>"+id+"<b> name: </b>"+vname).append("<hr />");
}
}
});
});
I have checked my search.php page and it returns the values i expect from the database (about 6 columns eventually) so I am wondering why it isn't being correctly displayed on the result div.
I am a beginner trying to pick it all up, no doubt I have much to work on but I am grateful for any advice and for an answer to my problem.
EDIT: Added search.php:
<?php
if (isset($_POST["txt_search"])){
$field_search= $_POST["txt_search"];
}
else{
}
//sql
$sql = "SELECT * From tbl1 INNER JOIN tbl2 ON tbl1._tbl1.id = tbl2.tbl1_id WHERE tbl1.name like '%$field_search%'";
// Connect to the database
mysql_connect("", "", "") or die (mysql_error());
mysql_select_db("") or die (mysql_error());
// Lets build the query and execute
$result = mysql_query($sql) or die(mysql_error());
$item_num = 0;
$num_records = mysql_num_rows($result);
// Put the table data into an array
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
Check this fiddle out: http://jsfiddle.net/LsB2d/2/
First, I added return: false; to your click function, so the form isn't submitted through html. Second, I added txt_search = $('#txt_search').val(); and added data: txt_search to your ajax function. This way, you're actually sending the value of the search input to the PHP file. If this doesn't work, let us know and we can go from there. (Although not seeing your PHP we can't help you with that yet)
In your PHP, you use $search = $_GET['search'];, and now $search contains your search string, which can be used to query your db or whatever you need to do.
Your question lacks the content of the result of search.php but I think your mistake is in here - you are iterating over the rows array with the var "i" but are using the rows-variable.... you mixed up iterating over array indices and iterating over array elements
for (var i in rows)
{
var row = rows[i];
var id = rows[0];
var vname = rows[1];
$('#result').append("<b>id: </b>"+id+"<b> name: </b>"+vname).append("<hr />");
}
Think it should be like this
for (var row in rows)
{
var id = row[0];
var vname = row[1];
$('#result').append("<b>id: </b>"+id+"<b> name: </b>"+vname).append("<hr />");
}
<html>
<head>
<script language="javascript">
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+window.document.contact[i].value);
}
return false; //to prevent form from submitting for debugging
}
</script>
</head>
<body>
<form name="editform" onsubmit="return validatefrm();" method="POST">
<?php
for($i=0; $i<3; $i++){
print "<input type='textbox' id='contact".$i."' value='".$i."'>";
}
?>
<input type="submit" value="Submit Values">
</form>
</body>
</html>
Hi, I'm new to php and javascript.
I'm trying to call the form with the value of 0,1,2 with javascript but it wont work. Unless i delete the for loop in javascript function and hard code it as Window.alert (window.document.contact0.value) and so on....Anyone can help? Must appreciate.
If I get your question correctly, you need to access the elements by ID. And the correct way is to use document.getElementById(...). In your case:
for (var i= 0 ; i< 3 ; i++){
window.alert(document.getElementById('contact' +i).value);
}
You are setting an ID for each element with php contact0, contact1 etc.
So in javascript look for that ID
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+ ' '+ document.getElementById('contact'+i).value);
}
return false; //to prevent form from submitting for debugging
}
Your best choice would most likely be to use json_encode. This method outputs the array as a JSON array which can be assigned to a JavaScript variable in <script> tags. Associative arrays on the PHP side would get converted into JSON objects.
json_encode in the PHP documentation
<?php
$myArr = array(0, 1, 2);
?>
<!-- somewhere in the HTML document -->
<script>
var myArr = <?php echo json_encode($myArr); ?>;
// do something with myArr
console.log(myArr);
</script>
The php is executed on the server side, before it makes it to the browser. The javascript is executed on the client side, in the browser. You cannot pass php values to javascript like this.
You can make the php output javascript (in a script tag), and use that in your javascript code though.
<script>
var foo = [];
<?php
for($i=0; $i<3; $i++){
print "foo[".$i."] = ".$i;
}
?>
console.log(foo[0] + ", " + foo[1] + ", " + foo[2]);
<script>