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?