JavaScript/PHP/MySQL not inserting into database - javascript

On my website, I have a JavaScript function that saves data into a MySQL database. It works by sending the data to a PHP file, which processes it, and then inserts it into the database.
I was fiddling around with it, and it no longer inserts new information into the database. It still works fine when updating existing information in the database, but when I try to add new information in, nothing happens, The information is not there, and no error is displayed.
Here is my PHP code: (Obviously, I have already connected and selected the database)
$query = mysql_query( "insert into parts values( 0, " . mysql_escape_string( $objectID ) . ", " . $objectStackID . ", " . $objectCardID . ", '" .
mysql_escape_string( $objectProperties['name'] ) . "', '" .
mysql_escape_string( $objectProperties['partorder'] ) . "', '" .
mysql_escape_string( $objectProperties['top'] ) . "', '" .
mysql_escape_string( $objectProperties['left'] ) . "', '" .
mysql_escape_string( $objectProperties['width'] ) . "', '" .
mysql_escape_string( $objectProperties['height'] ) . "', '" .
mysql_escape_string( $objectProperties['stype'] ) . "', '" .
mysql_escape_string( $objectProperties['value'] ) . "', '" .
mysql_escape_string( $objectProperties['script'] ) . "', '" .
mysql_escape_string( $objectProperties['visible'] ) . "', '" .
mysql_escape_string( $objectProperties['disabled'] ) . "', '" .
mysql_escape_string( $objectProperties['style'] ) . "', '" .
mysql_escape_string( $objectProperties['family'] ) . "' )" );
if( ! $query )
{
logThis('Could not enter data: ' . mysql_error());
}
else
{
logThis("inputted sucessfully - here come the objectprops");
logThis("Button properties:");
logThis("Name: " . $objectProperties['name']);
logThis("Part order: " . $objectProperties['partorder']);
logThis("Top: " . $objectProperties['top']);
logThis("left: " . $objectProperties['left']);
logThis("width: " . $objectProperties['width']);
logThis("height: " . $objectProperties['height']);
logThis("stype: " . $objectProperties['stype']);
logThis("value: " . $objectProperties['value']);
logThis("script: " . $objectProperties['script']);
logThis("visible: " . $objectProperties['visible']);
logThis("disabled: " . $objectProperties['disabled']);
logThis("style: " . $objectProperties['style']);
logThis("family: " . $objectProperties['family']);
}
The logThis function writes the contents to a txt file, which is useful for debuging. In the txt file, I receive the message "inputted successfully - here come the objectprops" followed by the values (that should have been) inserted into the database. However, when I look at the database, nothing has been added.
This code did work fine at one point, however, I have been editing it on and off for about 6 months now, only testing to see if it will update information, not create now info (really stupid!), so I have no idea when it was last working, and what I changed to make it stop.
I think that my JavaScript is OK, as PHP receives the correct values (as can be seen from the log), but just does not actually insert them into the database.
Can anyone see what I have done wrong? Nay help at all would be greatly appreciated. I have been staring at this code for a long time now!
Thanks in advance.
EDIT - here is the javascript code, basically it cycls through an array, getting properties of buttons and then sends them to the save php file. Seems to work OK, but there might be a hidden error causing the issue

Related

Passing value to other page by clicking a list item

I am new at web programming and JavaScript.
I have a model page that show all the details of a request let 's say. And Before that page, what the user sees is a list with all the requests he have made. The this is, I want somehow to passe the ID of that clicked request, save it somewhere and pass to the other page and in there, by ID e shows all the details of that previously clicked request.
Here is my code:
<div class="list-group">
<?php
$id_utilizador = $_SESSION["id_utilizador"];
if(isset($_POST["por_aprovar"])){
$url = "http://localhost/myslim_aluguer_viaturas/api/requisicoes/fase1/" . $id_utilizador;
$json = file_get_contents($url);
$obj = json_decode($json);
if($obj->status == true){
$array = $obj->data;
foreach($array as $requisicao){
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
}
} else {
echo "Não existem resultados a apresentar.";
}
?>
I don 't know what to do. thank you for your time!!!
What you are looking for is a url query string aka get parameters. In your code change this:
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
To this:
echo "<a href='requisicao.php?theid=" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
And on requisicao.php you will obtain the value using php's super global variable $_GET[] which will be something like this:
if(isset($_GET['theid']) && $_GET['theid'] != ''){
$the_id = $_GET['theid'];
// do stuff with $the_id;
}
You can pass multiple values by adding additional parameters:
requisicao.php?theid=22&anothervar=something&var3=33
Also keep in mind the security implications when passing variables via query string parameters as users will be able to easily manipulate these variables, and they will be saved in access logs. Your application should have the logic to sanitize and insure that the values passed are valid.

Trying to send two values from php to JS

Im retrieving a value from my db, displays on screen as a 0.
echo "<article>" . $gr_display['status'] . "</article>";
Then when im clicking on this DIV i want to send both status and id to my JS function, edit. The ID of this object is 79
echo "<div onclick='edit( " . $gr_display['status'] . "." . $gr_display['id'] . " )' </div>";
Then the start of my script
function edit(status, id) {
console.log(status, id ); some code later }
But im ending up with the result that id and status is combined into one sett of value, leaving the other one "undefined"
From console log: 0.79 undefined
Please make a clarity between PHP and JavaScript. You need to use the right separator and separate.
echo "<div onclick='edit( " . $gr_display['status'] . ", " . $gr_display['id'] . " )'> </div>";
//-----------------------------------------------------^
Replace . with ,. Also please use > for the opening <div>. You forgot to close your opening div.
you have at typo change the . into, between the 2 variables
echo "<div onclick='edit( " . $gr_display['status'] . "," . $gr_display['id'] . " )'> </div>";
//---------------------------------------------------------^
or better use data-attributes
echo "<div class='edit-element' data-status='" . $gr_display['status'] . "' data-id='" . $gr_display['id'] . "'></div>";
$('.edit-element').click(function(){
console.log($(this).attr('data-status'),$(this).attr('data-id'));
});
replace div with this:-
echo "<div onclick='edit( " . $gr_display['status'] . "," . $gr_display['id'] . " )' </div>";
The problem is causes by this line:
echo "<div onclick='edit( " . $gr_display['status'] . "." . $gr_display['id'] . " )' </div>";
Notice that between the two arguments you put a '.' instead of a ',' (a comma). That way, the second argument in your JS function does not have a value
Your code has two issues
You haven't close opening div tag
Use , to separate two parameters
echo "<div onclick='edit( " . $gr_display['status'] . ", " . $gr_display['id'] . ")'>ddd </div>";
<script type="text/javascript">
function edit(status, id) {
alert(status);
alert(id);
}
</script>

Instant update on loading of page as opposed to refresh

edit.php
<?php
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
if (isset($_POST["updateSubmit"])) {
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductConsole "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p><br><br>Updated, please refresh page.</p>"; // CAN I AVOID REFRESHING PAGE?
}
}
}
}
?>
So on the home page you can view products by table. You can click edit to edit that particular row. When I modify a value and navigate back to the home page, I have to manually refresh. Once I've edited the record, I have to refresh the page edit.php for it to retrieve the record. Here is the php for once the page is updated. I assume that's the only code you need. Can anyone help? Thanks

Change src of element loaded with AJAX

I'm trying to alter the src of imgs loaded via. AJAX, wherein the <select> and <option> elements used to control the function are also loaded by AJAX.
I'm trying to do this in order to change the size of Flickr images on the page.
I've tried loading the element, and calling an existing function to update it, but of course the <select> option doesn't exist on document.ready() and thus returns null when I try to get it.
I've also tried loading a new <script type='text/javascript'></script> in the PHP file I'm using for my XML response, but although this shows on the page it obviously isn't picked up as a source.
How can I tell the Document to 're-ready' itself, or acknowledge new sources?
Here's my code as it stands:
Making the request
function makeRequest (url, userID, searchString, selectedLicense) {
event.preventDefault();
var formData = new FormData();
formData.append("userID", userID);
formData.append("searchString", searchString);
formData.append("selectedLicense", selectedLicense);
var xmlRequest = new XMLHttpRequest();
xmlRequest.open("POST", url, true);
xmlRequest.send(formData);
xmlRequest.onreadystatechange=function()
{
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
document.getElementById("results").innerHTML=xmlRequest.responseText;
} else {
document.getElementById("results").innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
}
}
The PHP
//more code before
$resultString = $resultString . "<script type='text/javascript'>"
. "function sizeChanged(i, select) {
var sel = getSelectedOptionValue(select);
var imgURL = document.getElementById(i.toString());
alert(imgURL);
}"
. "</script>";
//main loop
foreach ($XML->photos->photo as $photo):
$resultString = $resultString . '<div class="photoBox"' . photoBox($photoCounter) . "> <p>" . $photoCounter . ". " . $photo['title'] . "" . "</p>"
. " <p>" . "<img id='" . $photoCounter . "' src=\"http://farm" . $photo['farm'] . $imgURL . "/" . $photo['server'] . "/" . $photo['id'] . "_" . $photo['secret'] . "_" . $size . "\" alt=\"" . $photo['title'] . "\">" . "</p>"
. "<select form='addInformationForm' id='selectSize" . $photoCounter . "' onChange='return sizeChanged(" . $photoCounter . ", selectSize" . $photoCounter . ");'>"
. "<option value='n'>Small (320)</option>"
. "<option value='z' selected='selected'>Medium (640)</option>"
. "<option value='h'>Large (1600)</option>"
. "</select>"
. "</div>";
$photoCounter++;
endforeach;
//more code here
echo $resultString;
The HTML Output (Example)
<div class="photoBox" style="background-color:#FFFFFF">
<p>1. Killip's Adirondack Travelog, page 20</p>
<p><img id="1" src="http://farm9.staticflickr.com//8184/8427833074_2f7e22e7ce_z.jpg" alt="Killip's Adirondack Travelog, page 20"></p>
<select form="addInformationForm" id="selectSize1" onChange="return sizeChanged(1, selectSize1);">
<option value="n">Small (320)</option>
<option value="z" selected="selected">Medium (640)</option>
<option value="h">Large (1600)</option></select>
</div>
Any advice much appreciated!
NOTE: This code is for an internal tool, not a client-facing website.
The <select> doesn't exists at onload, but it does when you create it:
var res = document.getElementById("results");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
res.innerHTML = xmlRequest.responseText;
var select = res.getElementsByTagName('select')[0];
/* Use select here */
} else {
res.innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
};
Note that the <img> element should be available too, but you won't know its dimensions because it won't be downloaded. If you want to wait until it's loaded, you can add a load event listener.

PHP function ignoring an if statement

Due to one agent wanting his website url on the functionality that I worked on a month ago I ended up having to make some minor changes. I have two function PHP pages that run a very similar script but I had to make two based of two value sets. What they echo onto the page with AJAX is exactly the same and this is where it gets a little weird...
The first script I did was successful but I needed to make a if elseif else statement so everyone agent didn't have a link that went no where. After fiddling around with this statement I was able to get just the one agent to have his website URL on there. Once I had that done I was under the impression that it would be smoothing sailing from there..it was not...
I used the exact same statement for both of their scripts and only one works. The only thing that differs from them is what value it is receiving and that I use JavaScript + AJAX for the first one (Which works) and then decided to learn jQuery + AJAX to do the next one. Before this they all worked and it is the exact code for both besides the use of JavaScript/jQuery (which is the same language) and one uses GET while the other uses POST
I also get no errors or anything while the function is running. The agent's name is Sam Fiorentino that is the only one with a website url. I went into the console for the second search, the radio buttons, and it shows the company name outside of the anchor tag which is the root of the problem. Why would one display it correctly while the other doesn't?
First PHP (Works)
while ($stmt->fetch()) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>". $First_Name . " " . $Last_Name . " " . $Suffix . "</strong>" . "</span>" . "" . "<span class='email'>" . "Send an e-mail to" . " " . $First_Name . "</span>" . "" ."<div class='floathr'></div>";
if ($Company == NULL) {
echo "<p>";
}
elseif ($Website == NULL) {
echo "<p>" . "<strong>" .$Company . "</strong>" . "<br>";
}
else {
echo "<p>" . "<strong>" . "<a target='blank' href=" .$Website . ">" .$Company . "</a>" . "</strong>" . "<br>";
}
Second PHP (Doesn't Work)
while ($stmt->fetch()) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>".$First_Name . " " .$Last_Name . " " . $Suffix . "</strong>" . "</span>" . "" . "<span class='email'>" . "Send an e-mail to" . " " .$First_Name . "</span>" . "" ."<div class='floathr'></div>";
if ($Company == NULL) {
echo "<p>";
}
elseif ($Website == NULL) {
echo "<p>" . "<strong>" .$Company . "</strong>" . "<br>";
}
else {
echo "<p>" . "<strong>" . "<a target='blank' href=" .$Website . ">" .$Company . "</a>" . "</strong>" . "<br>";
}
SQL + Binded code (First/Working one)
$sql="SELECT First_Name, Last_Name, Suffix, Email, Company, WorkAddress1, WorkCity, WorkStateProvince, WorkZipCode, Work_Phone, Fax, Ancillary, SmallGroup, IndividualPlans, LongTermCare, Medicare, LargeGroup, TPASelfInsured, CertifiedForPPACA, Website FROM `roster` WHERE Last_Name = '".$q."' OR Company = '".$q."' OR WorkCity = '".$q."' OR WorkZipCode = '".$q."' ORDER BY Last_Name ASC";
if(!$stmt = $con->Prepare($sql))
{
die;
}else{
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($First_Name, $Last_Name, $Suffix, $Email, $Company, $WorkAddress1, $WorkCity, $WorkStateProvince, $WorkZipCode, $Work_Phone, $Fax, $Ancillary, $SmallGroup, $IndividualPlans, $LongTermCare, $Medicare, $LargeGroup, $TPASelfInsured, $CertifiedForPPACA, $Website);
$rows = $stmt->num_rows;
SQL + Binded code (Not working one)
$poststr = $_POST['expertise']; //get our post data
if(count($poststr) > 1){ //count to make sure we have an array
$expertise = implode(" AND ",$_POST['expertise']); //implode the array using AND as glue
}
else{ //otherwise if it is only one no need for implode
$expertise = implode("",array($poststr));
}
//here is our string for prepared statement
$sql = "SELECT First_Name, Last_Name, Suffix, Email, Company, WorkAddress1, WorkCity, WorkStateProvince, WorkZipCode, Work_Phone, Fax, Ancillary, SmallGroup, IndividualPlans, LongTermCare, Medicare, LargeGroup, TPASelfInsured, CertifiedForPPACA, Website FROM roster WHERE ".$expertise." = 1 ORDER BY Last_Name ASC";
if(!$stmt = $con->Prepare($sql))
{
die;
}else{
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($First_Name, $Last_Name, $Suffix, $Email, $Company, $WorkAddress1, $WorkCity, $WorkStateProvince, $WorkZipCode, $Work_Phone, $Fax, $Ancillary, $SmallGroup, $IndividualPlans, $LongTermCare, $Medicare, $LargeGroup, $TPASelfInsured, $CertifiedForPPACA, $Website);
$rows = $stmt->num_rows;
Javascript + AJAX (First one/Working one)
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("bodyA").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("bodyA").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","process.php?q="+str,true);
xmlhttp.send();
}
</script>
jQuery + AJAX (Second one/Not working)
$('input').on('click', function() { //Pulls data based on radial input
var value = $(this).val();
$.ajax({
type: 'POST',
datatype: "html",
data: {
expertise: value
},
url: "expertise.php",
success: function (data) {
$('#bodyA').html(data);
}
});
});
Any idea?
Live Site
"<a target='blank' href=" .$Website . ">"
This is your problem: You do not have quotes around your url. It outputs like this:
<a href=http://whatever.com/path>Company</a>
You need to add quotes like this:
"<a target='blank' href='" .$Website . "'>"
The url looks like this!
<a target='blank' href=http://www.samfiorentino.com/>Sam Fiorentino & Associates</a>
It needs quotes. The ending / in the URL is ending the <a>.
The reason why the first one works but the second one doesn't:
innerHTML lets the browser interpret the html.
$(...) is interpreted by jQuery, which does some fancy things for browser compatibility, but sometimes has drawbacks. Some browsers attempt to fix bad markup, and sometimes the browser does a bad job of it. jQuery makes them all mostly act the same.
See this jsfiddle for comparison: http://jsfiddle.net/Rk7SQ/
<p>Browser rendering:</p>
<p><a target='blank' href=http://www.samfiorentino.com/>Sam Fiorentino & Associates</a></p>
<p>jQuery rendering:</p>
<p id="jqrender"></p>
$(function() {
$('#jqrender').html("<a target='blank' href=http://www.samfiorentino.com/>Sam Fiorentino & Associates</a>");
});
You can see that they are different.

Categories