Passing multidimensional array via jQuery AJAX for MYSQL - javascript

I have a couple snippets of code which are working correctly in that they pass the desired result, but they are not working in the way that I would like them to in that I think the code can be improved.
As I will explain more clearly in a minute, my question is on whether I am able to call an element out of a multidimensional array in a different way than I do in the snippet, although the snippet works I just think it is less than ideal.
A jQuery AJAX function:
jQuery("form.everglades_user_submit").submit(function(event){
event.preventDefault();
var user_submit_data = jQuery(".everglades_user_submit").serialize();
jQuery.ajax({
type: "POST",
url: "' . $db_script_location . '",
data: {action: "zip_form", action_data: user_submit_data}
}).done(function(response){
alert("success. response: " + response);
}).fail(function(response){
alert("failure. response: " + response);
});
});
Sends data to a PHP file containing a MySQL query, then passes back a database response to an alert:
if ($_POST["action"] == "zip_form") {
$database_var = mysqli_connect('localhost',/*******************/);
if (!$database_var) {
die( 'Could not connect to database. Error: ' . mysqli_error($database_var) );
} else {
$submitted_zip = $_POST["action_data"];
$modified_data = str_replace("user_zip=","", $submitted_zip);
echo "submitted: " . $submitted_zip . ". Modified : " . $modified_data;
$query = "SELECT * FROM cust_db_fl_sen WHERE rep_zip = '" . $modified_data . "'";
$mysqli_result = mysqli_query($database_var, $query);
while($query_result = mysqli_fetch_array($mysqli_result)) {
echo 'Query result, only rep district atm: ' . $query_result['rep_dist'];
}
exit;
}
As you can see, what I have done is to take the submitted data and remove the part I do not want using str_replace(). I would strongly prefer if I could simply call $modified_data in this way, but it returns an illegal string offset error on 'user_zip,' whether I drop the quotes or not:
$modified_data = $_POST["action_data"]["user_zip"];
However, if I replace the user_zip string with a number such as 0 or 1 it returns a letter (u or s, and so on), so it seems to process user_zip=12345 as a literal string rather than the key->value pair I want it to be processed as.
If I were to evaluate the following in response to an AJAX request based on submission of 11111 in the form text field:
echo $_POST["action_data"];
It would result with "user_zip=11111." user_zip is the key for which 11111 would be the value, however I am only interested in the number because this is used to look up the elected representative for the district of the zip code based on a database query.
To summarize: Is the literal string processing approach with str_replace() standard, or is there a simple way to tell the code that we are dealing with a key->value pair, or an array, or so on, so that I can easily extract with my preferred call method or something similar?

you should first check the content coming from client, use
print_r($_POST["action_data"]);
check whether it contains user_zip=1234 or you can use explode function of php in your else part
else {
$submitted_zip = explode("=",$_POST["action_data"]);
$modified_data = submitted_zip[1];
echo "submitted: " . $submitted_zip . ". Modified : " . $modified_data;
$query = "SELECT * FROM cust_db_fl_sen WHERE rep_zip = '" . $modified_data . "'";
$mysqli_result = mysqli_query($database_var, $query);
while($query_result = mysqli_fetch_array($mysqli_result)) {
echo 'Query result, only rep district atm: ' . $query_result['rep_dist'];
}
exit;

Related

Detect specific info from variable [duplicate]

I have an HTML form field $_POST["url"], having some URL strings as the value.
Example values are:
https://example.com/test/1234?email=xyz#test.com
https://example.com/test/1234?basic=2&email=xyz2#test.com
https://example.com/test/1234?email=xyz3#test.com
https://example.com/test/1234?email=xyz4#test.com&testin=123
https://example.com/test/the-page-here/1234?someurl=key&email=xyz5#test.com
etc.
How can I get only the email parameter from these URLs/values?
Please note that I am not getting these strings from the browser address bar.
You can use the parse_url() and parse_str() for that.
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
If you want to get the $url dynamically with PHP, take a look at this question:
Get the full URL in PHP
All the parameters after ? can be accessed using $_GET array. So,
echo $_GET['email'];
will extract the emails from urls.
Use the parse_url() and parse_str() methods. parse_url() will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str() will create variables for each of the parameters in the query string. I don't like polluting the current context, so providing a second parameter puts all the variables into an associative array.
$url = "https://mysite.com/test/1234?email=xyz4#test.com&testin=123";
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
print_r($query_params);
//Output: Array ( [email] => xyz4#test.com [testin] => 123 )
As mentioned in another answer, the best solution is using parse_url().
You need to use a combination of parse_url() and parse_str().
The parse_url() parses the URL and return its components that you can get the query string using the query key. Then you should use parse_str() that parses the query string and returns
values into a variable.
$url = "https://example.com/test/1234?basic=2&email=xyz2#test.com";
parse_str(parse_url($url)['query'], $params);
echo $params['email']; // xyz2#test.com
Also you can do this work using regex: preg_match()
You can use preg_match() to get a specific value of the query string from a URL.
preg_match("/&?email=([^&]+)/", $url, $matches);
echo $matches[1]; // xyz2#test.com
preg_replace()
Also you can use preg_replace() to do this work in one line!
$email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
// xyz2#test.com
Use $_GET['email'] for parameters in URL.
Use $_POST['email'] for posted data to script.
Or use _$REQUEST for both.
Also, as mentioned, you can use parse_url() function that returns all parts of URL. Use a part called 'query' - there you can find your email parameter. More info: http://php.net/manual/en/function.parse-url.php
You can use the below code to get the email address after ? in the URL:
<?php
if (isset($_GET['email'])) {
echo $_GET['email'];
}
I a created function from Ruel's answer.
You can use this:
function get_valueFromStringUrl($url , $parameter_name)
{
$parts = parse_url($url);
if(isset($parts['query']))
{
parse_str($parts['query'], $query);
if(isset($query[$parameter_name]))
{
return $query[$parameter_name];
}
else
{
return null;
}
}
else
{
return null;
}
}
Example:
$url = "https://example.com/test/the-page-here/1234?someurl=key&email=xyz5#test.com";
echo get_valueFromStringUrl($url , "email");
Thanks to #Ruel.
$web_url = 'http://www.writephponline.com?name=shubham&email=singh#gmail.com';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);
echo "Name: " . $queryArray['name']; // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:singh#gmail.com
A much more secure answer that I'm surprised is not mentioned here yet:
filter_input
So in the case of the question you can use this to get an email value from the URL get parameters:
$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );
For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.
I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:
$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );
Might as well get into the habit of grabbing variables this way.
$uri = $_SERVER["REQUEST_URI"];
$uriArray = explode('/', $uri);
$page_url = $uriArray[1];
$page_url2 = $uriArray[2];
echo $page_url; <- See the value
This is working great for me using PHP.
In Laravel, I'm using:
private function getValueFromString(string $string, string $key)
{
parse_str(parse_url($string, PHP_URL_QUERY), $result);
return isset($result[$key]) ? $result[$key] : null;
}
A dynamic function which parses string URL and gets the value of the query parameter passed in the URL:
function getParamFromUrl($url, $paramName){
parse_str(parse_url($url, PHP_URL_QUERY), $op); // Fetch query parameters from a string and convert to an associative array
return array_key_exists($paramName, $op) ? $op[$paramName] : "Not Found"; // Check if the key exists in this array
}
Call the function to get a result:
echo getParamFromUrl('https://google.co.in?name=james&surname=bond', 'surname'); // "bond" will be output here

Get variable value by name from a String

This is for server side, regardless of client.
$data= file_get_contents('textfile.txt');
The textfile.txt contains
var obTemperature = "55";
var obIconCode = "01";
What can I enter so I can get echo obTemperature value of 55?
is there not a simple php interface to read var values by name?
please no over complicated /half answers /trolling,
You would be better off explaining what you want to do in general, but if you are tied to this file format and the format is consistent:
$data = str_replace('var ', '$', $data);
eval($data);
echo $obTemperature;
echo $obIconCode;
However, any other types of JavaScript code will cause a parse error.
Also, you can treat it as an ini file:
$data = str_replace('var ', '', parse_ini_string($data));
echo $data['obTemperature'];
Or just:
$data = parse_ini_string($data);
echo $data['var obTemperature'];
You can use a regular expression:
preg_match('/var obTemperature = "(\d+)";/', $data, $match);
$temperature = $match[1];
DEMO

How to call ajax from script to insert user input into mysql

I have a table inside a form, once a button is clicked a function is called that confirms the contents of the user input (checking to ensure all fields have info). After proceeding through the if statements and no errors are present I want to write the user information to mysql.
I have written the ajax file (see below) and I think my error is how I call the ajax file. Nothing is getting written to the database table and I am not sure what I am doing wrong
<?php
include_once("config.php");
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$date = $_POST['tDate'];
$species = $_POST['tSpecies'];
$sqrNum = $_POST['tSqrNum'];
$lat = $_POST['tLat'];
$lng = $_POST['tLng'];
$cond = $_POST['tCond'];
$num = $_POST['tNum'];
$hab = $_POST['tHab'];
$behav = $_POST['tBahav'];
$reg = $_POST['tReg'];
mysqli_query($con, "INSERT INTO species_reported (date, species, square_num, lat, long, condition, numbers_obs, habitat, behavior, region)
VALUES ('{$date}', '{$species}', '{$sqrNum}', '{$lat}', '{$lng}', '{$cond}', '{$hab}', '{$behav}', '{$reg}')");
?>
and from within the script
else{
//$(document).ready(function(){
$.ajax({
type: "POST",
url:"ajax_write.php",
data:"date=" + tDate +"&Species="+ tSpecies +"&SqrNum="+ tSqrNum +"&lat=" + tLat + "&lng=" + tLng + "&cond=" + tCond +"&num=" + tNum + "&hab=" + tHab + "&behav=" + tBahav + "&reg=" + tReg,
dataType: "dataString",
cache: "true",
success: function(msg,string,jqXHR){
$("#results").html(msg+string+jqXHR);
}
});
}
}
EDIT... I checked my php log and am seeing Undefined index: tSpecies (as well as all other Post['thisHere']. If this is any help to resolving the issue. My understanding was that I could send the data as I have and ajax would allocate contents to the variables in the php file (ie. from jscript.."date=" tDate would get sent to the xjax file and assign the value of tDate (from javascript) to the php variable $date.
The indexes you use in $_POST have to match the parameter names in the $.ajax data: parameter. You have date=, Species=, etc. in the parameter, but you're trying to access $_POST['tDate'], $_POST['tSpecies'], etc. You need to change one of them to match the other.
Also, I recommend you use an object rather than a string as the data: parameter. The values need to be URL-encoded if they contain special characters, and you're not doing that. If you use an object, jQuery takes care of formatting and encoding it for you. So it should be:
data: { tDate: tDate, tSpecies: tSpecies, tSqrNum: tSqrNum, ... },
BTW, EcmaScript6 provides a shorthand for objects where the property names are the same as the variables containing their values:
data: { tdate, tSpecies, tSqrNum, ... },

PHP Get last five words from .txt-file using file_get_contents

I'm looking for a functioning way of reading the last, say, 5 words from a .txt file using file_get_contents while long-polling. I've tried to work on a solution using the commented code below, but it breaks the long-polling – which works fine when displaying the full contents of a .txt-file.
I looked at the offset parameter for file_get_contents as well, but I don't know how to do a good (or functioning) adaption of that in my code. I guess that'd involve first counting all the words in said .txt file (which in itself is dynamic) then taking that number of words minus 5 somehow? There's probably an easier solution than that, and if not how do I go about to work it out with an alternative solution?
get_data.php
$id = $_COOKIE["currentID"];
$filepath = 'stories/'.$id.'.txt';
if (file_exists($filepath)) {
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filepath);
while($currentmodif <= $lastmodif){
sleep(1);
clearstatcache();
$currentmodif = filemtime($filepath);
}
// I've tried:
// Attempt to getting the last five words of .txt file, does NOT work
$str = file_get_contents($filepath);
$words = explode(' ', $str);
$last = join(" ", array_slice($words, -5, 5));
$response = array();
/* $response['data'] = file_get_contents($filepath); */ //use if not attempting to get last 5 words
$response['data'] = $last; //part of "what I've tried"
$response['timestamp'] = $currentmodif;
echo json_encode($response);
}
else{
// if file doesn't exist
echo('nada data, son.');
}
?>
application.js (for context)
$(function(){
$.longpolling({
pollURL: './get_data.php',
successFunction: pollSuccess,
errorFunction: pollError
});
});
function pollSuccess(data, textStatus, jqXHR){
var json = eval('(' + data + ')');
$('#response').html(json['data']);
document.getElementById('notificationsound').play();
console.log('file updated');
}
function pollError(jqXHR, textStatus, errorThrown){
console.log('Long Polling Error: ' + textStatus);
}
Why not do:
$lastfive = explode(" ", trim(preg_replace("/^([\s\S]+)(( ([^ ]+)){5})$/m", "$2", $code)));
Also, you should never use eval when parsing code retrieved from a server. Try using JSON.parse(data) instead.

Chunking MySQL array with json encode

I know there are existing some Questions about Chunking a mysql array in php, but my problem is, that I want to keep the output in JSON.
Scenario:
I want to get data from mysql, do some stuff with it ( like time formatting ) and output it in JSON.
The JSON data is parsed in the browser and visualized over a javascript chart.
Problem:
All of the above is working, but because of the huge amount of data, I'm getting an out of memory error, when I select bigger date ranges to output.
The Idea of directly sending out each x-lines of data is not working because of the JSON format it needs to be. Several JSON chunks won't work, it needs to be one for the chart.
So in the end I need to chunk the data but keep it as one big JSON.
(And setting up the memory limit is not really a solution.)
Ideas:
One Idea would be, to let the browser chunk the date range and ask the data as chunks & then put them together.
Of course this would work, but if there is a way to do this server side, it would be better.
Code:
private function getDB($date1, $date2){
$query = 'SELECT * FROM `db1`.`'.$table.'` WHERE `date` BETWEEN "'.$date1.'" AND "'.$date2.'" order by `date`;';
// date = datetime !
$result = $this->db->query($query);
$array = array();
while ( $row = $result->fetch_assoc () ) {
$array[] = array( strtotime($row[ 'date' ])*1000 , (float)$row[ 'var' ] );
// the formatting needs to be done, so the chart accepts it..
}
$result->close();
return json_encode($array);
}
Since this is not an option,
ini_set("memory_limit","32M")
perhaps you can add LIMIT to the function paramaters and query:
private function getDB($date1, $date2, $start, $pageSize){
$query = 'SELECT * FROM `db1`.`'.$table.'` WHERE `date` BETWEEN "'.$date1.'" AND "'.$date2.'" order by `date` LIMIT $start, $pageSize;';
// date = datetime !
$result = $this->db->query($query);
$array = array();
while ( $row = $result->fetch_assoc () ) {
$array[] = array( strtotime($row[ 'date' ])*1000 , (float)$row[ 'var' ] );
// the formatting needs to be done, so the chart accepts it..
}
$result->close();
return json_encode($array);
}
Then setup a for loop in javascript, call this with Ajax, incrementing the $start variable each time.
Store each responseText.substr(1).substr(-1) in an array.
When the responseText is "", all of the records have been returned.
.join the array with a comma, then add a new opening and closing "{ }", and you should have a JSON equivalent to all records.
Minimal parsing, and you'll be using built-in functions for most of it.
var startRec=0;
var pageSize=50;
var xmlhttp=new XMLHttpRequest();
var aryJSON=[];
var JSON;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if(xmlhttp.responseText==""){ //Might need to check for "{}" here instead of ""
//All records are received
JSON="{" + aryJSON.join(",") + "}";
aryJSON=[];
startRec=0
}else{
aryJSON.push(xmlhttp.responseText.substr(1).substr(-1));
startRec+=pageSize;
getNextPage();
}
}
}
function getNextPage(){
xmlhttp.open("GET","your.php?start=" + startRec + "&pageSize=" + pageSize,true);
xmlhttp.send();
}
I would recommend that you have the server send the browser exactly what it needs to create the table. Parsing can be a heavy task, so why have the client do that lifting?
I would have your backend send the browser some kind of data structure that represents the table (i.e. list of lists), with all the formatting already done. Rendering the table should be faster and less memory-intensive.
One way of answer would be, to do the chunking on the server, by giving out the JSON, removing the leading [ & ].
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 0);
#ini_set('implicit_flush', 1);
$array = array();
echo '[';
$started = false;
while ( $row = $result->fetch_assoc () ) {
$array[] = [ strtotime($row[ 'datetime' ])*1000 , (float)$row[ 'var' ] ];
if(sizeof($array) == 1000){
if($started){
echo ',';
}else{
$started = true;
}
echo substr(substr(json_encode($array),1), 0, -1);
// converting [[datetime1, value1],[datetime2, value2]]
// to [datetime1, value1],[datetime2, value2]
ob_flush();
$array = array();
}
}
if($started)echo ',';
$this->flushJSON($array);
echo ']';
flush();
$result->close();
This is working and reducing the ram usage to 40%.
Still it seems that Apache is buffering something, so the ram usage increases over the time, the script is running. (Yeah, the flush is working, I debugged that, that's not the problem.)
But because of the remaining increase, the fastest way to achieve a clean chunking is to do this like alfadog67 pointed it out.
Also, to mention it, I had to disable the output compression, otherwise apache wouldn't flush it directly..

Categories