Display certain data in output from call back (jquery solution needed) - php

I am using a html web form to pass input fields to a php file using an AJax, the php file processes the data and returns data back. The data comes back as raw text but does have structure to it. However, alot of it i prefer not to display.
How can I manipulate data to only show certain information.
For example, data returned may look like this:
[CN] => www.domain.com
[O] => ACME INC
Usually, the information returned is formatted like the above. Is there a way for me to do a search for, say [CN] and return the rest of the data om that same line excluding the characters =>
I should end up with only www.domain.com
-- Sample of Ajax call --
$.ajax({
url: 'test.php',
success: function(response) {
$('result').html(response);

One way to do it in JavaScript would be using a regular expression
var ajaxResponse = "\r\n[CN] => www.domain.com\r\n\r\n[O] => ACME INC\r\n";
var regexParser = /^\[CN]\s*=>\s*(.*)$/m;
var parseResult = regexParser.exec(ajaxResponse);
alert(parseResult[1]);

Here is how you can do it in php:
<?php
$data =
"[CN] => www.domain.com
[O] => ACME INC";
$lines = explode("\r\n",$data);
foreach ($lines as $line ){
$parts = explode(" => ",$line);
if($parts[0]=="[CN]")
echo $parts[1];
}
?>
And Javascript:
<script>
var data ="[CN] => www.domain.com\r\n"+
"[O] => ACME INC";
var lines = data.split("\n");
for(var i=0;i<lines.length;i++){
var parts = lines[i].split(" => ");
if(parts[0]=="[CN]")
alert(parts[1]);
}
</script>

Related

How to parse URL when using the pager plugin with AJAX

I am trying to use the tablesorter pager plugin with AJAX but run into som problemes (or limitations) when trying to handle the AJAX request in my php backend.
If eg. the table is set up with a default sorting of
sortList: [ [0,1], [1,0] ]
I will get a URL like this on my AJAX request:
page=0&size=50&filter=fcol[6]=batteri&sort=col[0]=1&col[1]=0
In my php back end I do a
$cur_sort = $_GET['sort']
and get
col[0]=1
So the last part is missing - I guess since it contains a & char.
How do I get the entire sort string?
That said how is the string col[0]=1&col[1]=0 best parsed? I need to extract the info that col 0 is to be sorter DESC and col 1 ASC.
You can try this;
parse_str($_SERVER['QUERY_STRING'],$data);
It will parse the url to an array;
Also; you should use empty [] instead of [1] and [0]
See more here: parse_str()
Example:
$str = "page=0&size=50&filter=fcol[6]=batteri&sort=col[0]=1&col[1]=0";
parse_str($str, $output);
echo $output['page']; // echo 0
And to answer your question; it is correct; is echoing col[0]=1 because you are dividing with & see here:
&sort=col[0]=1 & col[1]=0;
An advice; use more names, instead.
You could use
&sort[]=1&sort[]=0;
UPDATE:
To access the last one; you should do, simply;
$_GET['col'][1];
If you want to access, the last number in
$_GET['sort'];
You can do this;
$explode = explode('=',$_GET['sort']);
$end = end($explode);
echo $end; //it will outout 1
If you print your entire query_String, it will print this;
Array
(
[page] => 0
[size] => 50
[filter] => fcol[6]=batteri
[sort] => col[0]=1
[col] => Array
(
[1] => 0
)
)
I'm not sure how the ajaxUrl option is being used, but the output shared in the question doesn't look right.
I really have no idea how the string in the question is showing this format:
&sort=col[0]=1&col[1]=0 (where did sort= come from?)
&filter=fcol[6]=batteri (where did filter= come from?)
If you look at how you can manipulate the ajaxUrl option, you will see this example:
ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}"
So say you have the following settings:
page = 2
size = 10
sortList is set to [[0,1],[3,0]] (1st column descending sort, 4th column ascending sort)
filters is set as ['','','fred']
The resulting url passed to the server will look like this:
http://mydatabase.com?page=2&size=10&col[0]=1&col[3]=0&fcol[2]=fred
The col part of the {sortList:col} placeholder sets the sorted column name passed to the URL & the fcol part of {filterList:fcol} placeholder sets the filter for the set column. So those are not fixed names.
If the above method for using the ajaxUrl string doesn't suit your needs, you can leave those settings out of the ajaxUrl and instead use the customAjaxUrl option to modify the URL as desired. Here is a simple example (I know this is not a conventional method):
ajaxUrl: "http://mydatabase.com?page={page}&size={size}",
// modify the url after all processing has been applied
customAjaxUrl: function(table, url) {
var config = table.config,
// convert [[0,1],[3,0]] into "0-1-3-0"
sort = [].concat.apply( [], config.sortList ).join('-'),
// convert [ '', '', 'fred' ] into "--fred"
filter = config.lastSearch.join('-');
// send the server the current page
return url += '&sort=' + sort + '&filter=' + filter
}
With the same settings, the resulting URL will now look like this:
http://mydatabase.com?page=2&size=10&sort=0-1-3-0&filter=--fred
This is my own best solution so far, but it's not really elegant:
if (preg_match_all("/[^f]col\[\d+]=\d+/", $_SERVER['QUERY_STRING'], $matches)) {
foreach($matches[0] AS $sortinfo) {
if (preg_match_all("/\d+/", $sortinfo, $matches)) {
if(count($matches[0]) == 2) {
echo "Col: ".$matches[0][0]."<br/>";
echo "Order: ".$matches[0][1]."<br/>";
}
}
}
}
It gives me the info I need
Col: 0
Order: 1
Col: 1
Order: 0
But is clumbsy. Is there a better way?

How to: Properly use PHP to encode data into JSON format, and request the data with jquery/ajax

I am trying to create an address book of sorts.
I can successfully connect to the database and insert data with a php script.
I have even managed to display json encoded data of my table rows, though I don't know if I am doing it right.
What I am actually trying to accomplish:
I would like to be able to make an ajax request for say, and ID, then get back all of that ID's corresponding data, (wrapped in Json - At least I think it needs to be..).
With the ajax script, I would like to be able to save the returned corresponding data to an input field in an html file.
I would also like to know if it would be better to try to return HTML to the ajax call, and input the data into the html input fields that way?
So far I am having limited success, but here is what I have so far...
I have a DB connection script:
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "data_base";
$mysqli = new mysqli($host, $user, $pass, $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
return $mysqli;
A mysql ISAM DB with the following columns:
id, user, pass, nickname, address, facebook, twitter, linkedin, youtube
ID should be unique
User is an index
Pass is an index
nickname is an index
address is primary - though its possible that id should be...
Facebook, Twitter, Linkedin, and Youtube are all indexes.
Note: I would be happy to change index, primary, etc as somebody sees fit...
EDITED!**Now my query page:
error_reporting(E_ALL); ini_set("display_errors", 1);
include 'db/dbcon.php';
//Start connection with SQL
$q = "SELECT * FROM `cfaddrbook` WHERE key = '111111'";
$res = $mysqli->query($q) or trigger_error($mysqli->error."[$q]");
$array = array(); // initialize
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$array[] = array(
'key' => $row[0],
'username' => $row[1],
// ... continue like this
);
}
header('Content-Type: application/json');
echo json_encode($array);
$res->free();
$mysqli->close();
Now, the above script seems to work fine. At least it displays just fine when loading the php page in the browser.
But when I make an ajax call with this script:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "queries.php",
dataType: 'json',
data: "",
cache: false,
success: function(result)
{
var cfkey = result[0];
var user = result[1];
alert("cfkey:" + cfkey + "user:" + user);
}
});
});
After loading this code, the chrome console states that the server returned with error 500.
Again, what I am trying to accomplish:
I would like to be able to make an ajax request for say, and ID, then get back all of that ID's corresponding data, (wrapped in Json - At least I think it needs to be..).
With the ajax script, I would like to be able to save the returned corresponding data to an input field in html.
EDIT:
Finally figured out that the problem I was discussing with Majid was with the SQL query.
key needed to be need to be wrapped in ` characters.
After you execute your query and the resultset is available in $res you could just build up your array, no need for a separate foreach:
$array = array(); // initialize
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$array[] = array(
'id' => $row[0],
'username' => $row[1],
'password' => $row[2],
'nick' => $row[3],
'addr' => $row[4],
'facebook' => $row[5],
'twitter' => $row[6],
'linkedin' => $row[7],
'youtube' => $row[8]
);
}
header('Content-Type: application/json');
echo json_encode($array);
Also note that this way, your json will have keys, so to consume it you should change:
success: function(result) {
var cfkey = result[0];
var user = result[1];
alert("cfkey:" + cfkey + "user:" + user);
}
To
success: function(result) {
var cfkey = result.id;
var user = result.username;
alert("cfkey:" + cfkey + "user:" + user);
}
Or simply do
$.getJSON('queries.php', {cfkey: $("#cfkey").val()}, function(result) {
// we have multiple results
$.each(result, function(i,r) {
console.log("cfkey:" + r.key + "user:" + r.username);
});
});
Edit: added header as pointed out by #amurrell
I believe you are expecting queries.php to return json (to your ajax) and thus you need content header types in your queries.php!
header('Content-Type: application/json');
You need more useful error messages. Try adding the following lines at the beginning of your code.
error_reporting(E_ALL);
ini_set("display_errors", 1);
Your script that outputs JSON is writing several valid JSON strings (one for each database row), but they don't add up to a valid JSON file. A JSON file should represent one JSON object.
If you want to pass an ID and get one database row back, you have to add that ID to the data part of your AJAX call, and modify queries.php to pass that id from its $_POST array into the WHERE part of your MySQL query. Then, you'd only output one JSON-encoded object rather than many, which would be a valid JSON file.
(Alternately, you could json_encode() the entire $rows array rather than each $row individually if you want the whole table back.)
Also, if you json_encode() a string-indexed array in PHP, you read its properties in Javascript by name, not by index. You've gone through the trouble of naming your keys in PHP, then switch back to trying to reference them by their 0-based index in Javascript. You can pick one way or the other, but you can only pick one!

Communication between Javascript and MYSQL

I am working on some code using Google Maps API. To sum up shortly, I have MySQL database with a table of information used to generate markers on the map. I connected to the database and am using PHP to draw out the necessary attributes and communicate with my Javascript code using XML.
What I'm currently attempting to do is go in the other direction, I'm trying to send a string of information (for example "1,2,3,45,18") from my Javascript code to MySQL to be set as a session parameter (call it #sparam). What is the process behind passing this value to MySQL?
Would I be able to access a MySQL variable through PHP in the same way I can access tables (for the purpose of getting a value back into Javascript)?
I'd appreciate any insight.
Thanks.
EDIT
Maybe I was unclear in my original post. What I'm asking is how would I be able to pass a string to a MySQL session variable, specifically a set of IDs directly related to the IDs in the table of the MySQL database, and then be able to work with these IDs by calling the necessary procedures in MySQL. In turn, the procedures called in MySQL would generate some output, which would then have to be passed back to the Javascript code.
I created a special JSON (JavaScript Object Notation) php pages that I would call from javascript. Then I would parse those JSON responses.
Simple example:
JAVASCRIPT:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "page_json.php?action=getsession",
type : "GET",
success : function(data) {
//Get Json and loop over it's data
if (data.length>10){
var jsonData = JSON.parse(data);
$.each(jsonData, function(Idx, Value) {
if (Idx>0){
//get values for each vehicle and then remove it's marker from the map and then add new marker on the map (thereofore update the marker)
c_latitude = Value["lat"];
c_longitude = Value["lon"];
c_name = Value["name"];
c_notes= Value["notes"];
removeMarker(c_name); //remove old marker function
addMarker(c_latitude, c_longitude, c_name); //add current marker function
}
});
}
}
});
});
}
PHP: Here I loop over my arrayList and then create a simple array with values. Then I just output it as a json string
foreach ($listOfCars->arrayList as $key => $value) {
$unit = new fleetUnit();
$unit = $value;
//create array for json output
$data[] = array('lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes);
}
echo json_encode($data);

Passing arrays from Flash to PHP

I am having a problem passing an array variable from Flash (AS2) to PHP. In action script I have several arrays defined like this
output["px1"]
output["px2"]
output["px3"]
and then I use the following code to pass the variables into a php file
output.sendAndLoad("orders/print2cart.php",output,"POST");
I want to know how to get the data from the array in PHP. I have tried using $_POST['px1'], $_POST['output']['px1'], $_POST['output'] but I cannot seem to get any data. Any ideas as to what I can change to get the desired result?
Thanks!
EDIT: Just noticed that I one of the other variables in output (output.username) is also not being sent to PHP, despite it showing up in flash. Using the following code to alert to flash and it does show all the variables correctly.
getURL("javascript:alert('Print Stamp: " + output.PrintStamp + " User: " + output.username "')");
EDIT: Seems like once I send a pretty long array (or a string for that matter) none of the other fields associated with the LoadVars variable are sent either. I googled it up for limits and it says text limits are ~ 63000. Still not sure if that is the problem
Try it as a String.
Use Array.join(); in flash and send the value returned by that, then use explode() in PHP convert it back to an array.
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
dataOut.info = your_array.join("#");
vars.sendAndLoad("url", dataIn, "post");
dataIn.onLoad = function(go:Boolean):Void
{
if(go)
{
trace('success');
}
else trace('connection failed');
}
The PHP:
<?php
$str = $_POST["info"];
$myarray = explode($str);
?>
Since there were no other alternatives and I went through a lot of stuff before finally concluding that Arrays of large sizes cannot be passed through from AS2 to PHP very easily. My array was actually an image converted to pixels, so what I did was that I split the array into 2 pieces and posted to the PHP file twice instead of only once. Another alternative would be to split and post the array to a text file first and then read that text file directly from PHP.
You can do the same as you would do with HTML, by naming your parameters "array[0]", "array[1]", etc... :
var urlVariable:URLVariables = new URLVariables();
urlVariable["phpArray[0]"] = "arrayEntry0";
urlVariable["phpArray[1]"] = "arrayEntry1";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://yourserver.com/phpScript.php");
request.method = URLRequestMethod.POST;
request.data = urlVariable;
loader.load(request);
then serverside you can verify the result received by php script :
print_r($_POST);
it should output :
Array
(
[phpArray] => Array
(
[0] => arrayEntry0
[1] => arrayEntry1
)
)
and for multiple dimension array you can use :
urlVariable["phpArray[0][0]"]

JavaScript two-dimensional Array to PHP

I have to send a two-dimensional JavaScript Array to a PHP page.
Indeed, I'm working on a form-builder, in which the user can add or remove fields.
These fields are added (or removed) using JavaScript (jQuery). When the user is done and hit a 'publish' button, I have to get all the fields concerned and send them to a PHP page which would build a real form with it.
I found a way to do it but I'm pretty sure it's not very clean :
addedFields = new Array();
$("#add-info .field").each(function() {
addedFields.push(new Array($(this).find('.name').val(), $(this).find('.type').val(), $(this).find('.size').val()));
});
Basically, the ".field" class objects are <tr> and the ".name", ".type" and ".size" objects are inputs.
So I get an array of [name, type, size], then I convert it into a string using
addedFields = addedFields.join(";");
Finally, I go to the PHP form that way ;
document.location.href = "create.php?addedfields=" + addedFields;
Concerning the PHP code, I create a PHP array using the explode() function:
$addedFields = explode(";", $_GET['addedfields']);
and then I use it again for each element in the array:
foreach ($addedFields as $field) {
$field = explode(",", $field);
echo "<li>Field with name : '$field[0]', of '$field[1]' type and with a size of $field[2]</li>";
}
So it works, but it seems very dirty...
Use the auto-array feature in PHP:
var data = {};
$("#add-info .field").each(function(i) {
data['field['+i+'][name]'] = $(this).find('.name').val();
data['field['+i+'][type]'] = $(this).find('.type').val();
data['field['+i+'][size]'] = $(this).find('.size').val()]);
});
$.post("target.php", data);
then on the server side
var_dump($_POST['field']);
// array(
// 0 => array(
// 'name' => ...
// 'type' => ...
// 'size' => ...
// ),
// 1 => ...
Edit: slightly more elegant version of the loop:
$("#add-info .field").each(function(i) {
for (attr in {name: 1, type: 1, size: 1}) {
data['field['+i+']['+attr+']'] = $(this).find('.'+attr).val();
}
});
Put those input fields in a form-element. Use JSON like
var formData = $('form').serializeArray();
formData = window.JSON.stringifiy(formData);
$.post('address', {addedfields: formData}, function(){});
something similar to that should do it in jQuery.
on the backend convert the JSON into an object and loop through.
Try consider using JSON to interact data between PHP and JavaScript.
JSON is built into Javascript and there is an awesome library for PHP. Check them out.

Categories