Passing json to php and updating mysql - php

I'm trying to pass image coordinates via json to a php file that should update the database.
I have this in jquery:
var coords=[];
var coord = $(this).position();
var item = { coordTop: coord.top, coordLeft: coord.left };
coords.push(item);
var order = { coords: coords };
$.ajax({
type: "POST",
data : +$.toJSON(order),
url: "updatecoords.php",
success: function(response){
$("#respond").html('<div class="success">X and Y Coordinates
Saved</div>').hide().fadeIn(1000);
setTimeout(function(){
$('#respond').fadeOut(1000);
}, 2000);
}
});
This is what updatecoords.php looks like:
<?php
$db = Loader::db();
$data = json_decode($_POST['data']);
foreach($data->coords as $item) {
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
$x_coord = mysql_real_escape_string($coord_X);
$y_coord = mysql_real_escape_string($coord_Y);
$db->Execute("UPDATE coords SET x_pos = '$x_coord', y_pos = '$y_coord'");
}
?>
The success message shows from the javascript however nothing gets updated in the database?
Any thoughts?

You have a + before $.toJSON. Meaning that the json string it returns will be converted to an integer - probably 0 or NaN.

Alex is right, but you can also take the quotes out from the preg_replace pattern. PHP naturally uses /.../ slashes to "quote" a regular expression.

try this
UPDATE coords SET x_pos = '".$x_coord."', y_pos = '".$y_coord."'
and look here how to use toJSON
EDIT :
try this
$.ajax({
type: "POST",
data : { coordTop: coord.top, coordLeft: coord.left ,coords: coords },
and in second code do this
$data = json_decode($_POST['data']);
$coordTop = mysql_real_escape_string($_POST['coordTop']);
$coordLeft = mysql_real_escape_string($_POST['coordLeft']);
$coords = mysql_real_escape_string($_POST['coords']);
foreach(.........
.....
.....
and then use those variables $coordTop , $coordLeft , $coords

Thanks for the help but this seemed to do the trick....
In javascript:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){ alert (response + mydata);
In Updatecoords.php:
$data = json_decode(stripcslashes($_POST['data']));

Related

Select multiple rows into array and send them via AJAX

I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.php', // Sending variable emp, pos, and sal, into this url
type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
data: {
data1: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}

JQuery Ajax multi array repsonse

I got the following problem. I want to display a multi array via ajax.
Javascript:
function getContent(HSID,HSname){
$.ajax({
url: 'ajax/script.gethandlungslogContent.php',
type: "POST",
data: { HSID : HSID },
dataType : "json",
success: function(data) {
document.getElementById('wartungslogHead').innerHTML = HSname;
document.getElementById('wartungslogContent').innerHTML = data.hl_aenderung;
document.getElementById('wartungslogID').value = data.HSID;
//document.getElementById('wartungslogID').value = data.KentID;
document.getElementById('buttonEdit').style.display = 'inline';
document.getElementById('buttonDelete').style.display = 'inline';
}
});
}
PHP Script:
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
echo json_encode($row3);
}
?>
The return of the php script looks like this:
{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"}
{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"4","HSID":"2","hl_datum":"2014-04-13","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.39Apache Update 2.4.8 (OpenSSL auf 1.0.1g)"}
{"HLID":"5","HSID":"2","hl_datum":"2014-04-14","hl_info":"n","hl_aenderung":"Zertifikatsaustausch wegen Heartbleed Bug"}
{"HLID":"6","HSID":"2","hl_datum":"2014-04-27","hl_info":"y","hl_aenderung":"Java Update auf 7.0.58"}
{"HLID":"7","HSID":"2","hl_datum":"2014-06-08","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.41Apache Update auf 2.4.9 (OpenSSL auf 1.0.1h)Java Update auf 7.0.60"}
{"HLID":"8","HSID":"2","hl_datum":"2014-07-21","hl_info":"y","hl_aenderung":"Apache Update auf 2.4.10Java Update auf 7.0.62"}
What to do here? Thanks in advance!
You must save it to another Array and show after gets all data from mysql.
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$myjsonarray = null;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
$myjsonarray[] = $row3;
}
echo json_encode($myjsonarray);
?>
And now you get this
[{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"},{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},...]
Example show in php...
<?php
echo $myjsonarray[0]["HLID"];
echo $myjsonarray[1]["HLID"];
?>
In jquery you may use "for"
for(i=0;i<data.lenght;i++){
mydata = data[i];
alert(mydata["HSname"]);
}
Change your PHP to :
$tempArray = array();
while ($row3 = $mydb3->fetchRow()){
tempArray[] = $row3;
}
echo json_encode($tempArray);
Then in javascript:
success: function(data) {
$.each(data, function(index, item){
// Now loop through e.g.
$('body').append('<div class="wartungsLogID">' + item.HSID + '</div>');
});
}
In your javascript, in the success callback, you need to parse the json (var data).
If you have a table element, you can fill it with your data.
First you need a table and cycle:
var t = document.getElementById(mytableId);
for (var i = 1; i < data.length; i++)
...
inside the loop you need to create a row for every object inside your json:
var tr = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = data[i].hl_aenderung;
tr.appendChild(td);
t.appendChild(tr);
and repeat this for every field (every object's propery (hl_datum,hl_info,etc.)).
Within the Ajax Success callback you must loop through the array to display each object individually.
Below is an example, including some best practice techniques:
success: function(data) {
var textToDisplay = '';
$.each(data, function(i, item){
textToDisplay += '<li data-id="'+item.HLID+'">'+item.hl_aenderung+'</li>'
});
$('ul').append(textToDisplay);
}
Here's a working fiddle which you can expand on.

returned ajax query data undefined

Hello I am attempting to create an ajax query but when my results are returned I get Undefined as a response. Except for the object called "hello" which returns back as "h" even though it is set to "hello". I have a feeling it has something to do with the way ajax is sending the data but i'm lost as to what may be the issue. Any help would be greatly appreciated.
here is the ajax
function doSearch() {
var emailSearchText = $('#email').val();
var keyCardSearchText = $('#keyCard').val();
var userNameSearchText = $('#userName').val();
var pinSearchText = $('#pin').val();
var passwordSearchText = $('#password').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: {
"hello": "hello",
"emailtext": "emailSearchText",
"keycardtext": "keyCardSearchText",
"usernametext": "userNameSearchText",
"pinText": "pinSearchText",
"passwordtext": "passwordSearchText"
},
dataType: "json",
success: function (data) {
alert(data.msg);
var mydata = data.data_db;
alert(mydata[0]);
}
});
}
Then here is the php
include_once('connection.php');
if(isset($_POST['hello'])) {
$hello = $_POST['hello'];
$emailSearchText = mysql_real_escape_string($_POST['emailSearchText']);
$keyCardSearchText = mysql_real_escape_string($_POST['keyCardSearchText']);
$userNameSearchText = mysql_real_escape_string($_POST['userNameSearchText']);
$pinSearchText = mysql_real_escape_string($_POST['pinSearchText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordSearchText']);
$query = "SELECT * FROM Students WHERE (`User name`='$userNameSearchText' OR `Email`='$emailSearchText' OR `Key Card`='$keyCardSearchText')AND(`Password`='$passwordSearchText'OR `Pin`='$pinSearchText')";
$students = mysql_query($query);
$count = (int) mysql_num_rows($students);
$data = array();
while($student = mysql_fetch_assoc($students)) {
$data[0] = $student['First Name'];
$data[1] = $student['Last Name'];
$data[2] = $student['Date of last class'];
$data[3] = $student['Time of last class'];
$data[4] = $student['Teacher of last class'];
$data[5] = $student['Membership Type'];
$data[6] = $student['Membership Expiration Date'];
$data[7] = $student['Free Vouchers'];
$data[8] = $student['Classes Attended'];
$data[9] = $student['Classes From Pack Remaining'];
$data[10] = $student['5 Class Packs Purchased'];
$data[11] = $student['10 Class Packs Purchased'];
$data[12] = $student['Basic Memberships Purchased'];
$data[13] = $student['Unlimited Memberships Purchased'];
$data[14] = $student['Groupon Purchased'];
};
echo json_encode(array("data_db"=>$data, "msg" => "Ajax connected. The students table consist ".$count." rows data", "success" => true));
};
Your PHP script is likely producing error messages because the $_POST values you are trying to access don't match the key names you are sending in the request. For example: $_POST['emailSearchText'], yet you used emailtext in the AJAX call.
This is most likely causing jQuery to not be able to parse the response as JSON, hence the Undefined.
First of all, you have to remove the quotes or you will be passing those literals instead of the variables.
$.ajax({
...
data: {
hello: "hello",
emailtext: emailSearchText,
keycardtext: keyCardSearchText,
usernametext: userNameSearchText,
pinText: pinSearchText,
passwordtext: passwordSearchText
},
...
});
And then, like ashicus point out, in your PHP file:
$emailSearchText = mysql_real_escape_string($_POST['emailtext']);
$keyCardSearchText = mysql_real_escape_string($_POST['keycardtext']);
$userNameSearchText = mysql_real_escape_string($_POST['usernametext']);
$pinSearchText = mysql_real_escape_string($_POST['pinText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordtext']);
JS file looks ok, so this few clues to check PHP file.
See if there are even POST params there (printr all $_POST in php)
Check if your even enters IF. Add an else statement and echo some dummy json.
Check what is actually in encoded json that is echoed. Assign it to var then print.

using jquery post to send values to php file

I'm trying to write a script in javascript/jquery that will send values to a php file that will then update the database. The problem is that the values aren't being read in by the PHP file, and I have no idea why. I hard-coded in values and that worked fine. Any ideas?
Here's the javascript:
var hours = document.getElementById("hours");
var i = 1;
while(i < numberofMembers) {
var memberID = document.getElementById("member"+i);
if(memberID && memberID.checked) {
var memberID = document.getElementById("member"+i).value;
$.ajax({
type : 'post',
datatype: 'json',
url : 'subtract.php',
data : {hours : hours.value, memberID : memberID.value},
success: function(response) {
if(response == 'success') {
alert('Hours subtracted!');
} else {
alert('Error!');
}
}
});
}
i++;
}
}
subtract.php:
if(!empty($_POST['hours']) AND !empty($_POST['memberID'])) {
$hoursToSubtract = (int)$_POST['hours'];
$studentIDString = (int)$_POST['memberID'];
}
$query = mysql_query("SELECT * FROM `user_trials` WHERE `studentid` = '$studentIDString' LIMIT 1");
Edit: Updated code following #Daedal's code. I'm still not able to get the data in the PHP, tried running FirePHP but all I got was "profile still running" and then nothing.
This might help you:
function subtractHours(numberofMembers) {
var hours = document.getElementById('hours');
var i = 1;
while(i < numberofMembers) {
// Put the element in var
var memberID = document.getElementById(i);
// Check if exists and if it's checked
if(memberID && memberID.checked) {
// Use hours.value and memberID.value in your $.POST data
// {hours : hours.value, memberID : memberID.value}
console.log(hours.value + ' - ' + memberID.value);
// $ajax is kinda longer version of $.post api.jquery.com/jQuery.ajax/
$.ajax({
type : 'post',
dataType : 'json', // http://en.wikipedia.org/wiki/JSON
url : 'subtract.php',
data : { hours : hours.value, memberID : memberID.value},
success: function(response) {
if( response.type == 'success' ) {
alert('Bravo! ' + response.result);
} else {
alert('Error!');
};
}
});
}
i++;
}
}
and PHP part:
$result = array();
// Assuming we are dealing with numbers
if ( ! empty( $_POST['hours'] ) AND ! empty( $_POST['memberID'] ) ) {
$result['type'] = "success";
$result['result'] = (int) $_POST['hours'] . ' and ' . (int) $_POST['memberID'];
} else {
$result['type'] = "error";
}
// http://php.net/manual/en/function.json-encode.php
$result = json_encode( $result );
echo $result;
die();
Also you probably don't want to CSS #ID start with a number or to consist only from numbers. CSS Tricks explained it well http://css-tricks.com/ids-cannot-start-with-a-number/
You can simple fix that by putting some string in front:
var memberID = document.getElementById('some_string_' + i);
This is not ideal solution but it might help you to solve this error.
Cheers!
UPDATE:
First thing that came to my mind is that #ID with a number but as it seems JS don't care about that (at least not in a way CSS does) but it is a good practice not to use all numbers. So whole error was because document.getElementById() only accepts string.
Reference: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById id is a case-sensitive string representing the unique ID of the element being sought.
Few of the members already mentioned converting var i to string and that was the key to your solution. So var memberID = document.getElementById(i); converts reference to a string. Similar thing could
be accomplished I think in your original code if you defined wright bellow the loop while(i < numberofMembers) { var i to string i = i.toString(); but I think our present solution is better.
Try removing the '' fx:
$.post (
"subtract.php",
{hours : hours, memberID : memberID}
try this
$.ajax({type: "POST",
url:"subtract.php",
data: '&hours='+hours+'&memberID='+memberID,
success: function(data){
}
});
Also you could try something like this to check
$(":checkbox").change(function(){
var thisId = $(this).attr('id');
console.log('Id - '+thisId);
});
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];
Try this:
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
document.body.style.cursor = "auto";
});
Try n use this...
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
$(body).css({ 'cursor' : 'auto' });
});

How to get MySQL data into correct array structure

I just finished getting a script to work by using a hard coded array like so:
dataArray[0] =[50,10,0.3,0.25,50,"FFF",3];
dataArray[1] =[50,10,0.3,0.2,50,"FFF",3];
....
dataArray[5] =[50,20,0.5,0.7,120,"FF0",4];
I put the contents of dataArray into a db table so I could eliminate the hard coded array.
I'm returning the data in a string from MySql with PHP, and a data dump shows that the number of values and the values themselves are correct.
However, I'm apparently not coding the data capture correctly because I'm not ending up with an array like my hard coded array (I need to maintain the structure of my hard coded array).
Here's the code for the db read:
function getSomeData(){
$.ajax({
type: "GET",
url: "GetSomeData.php",
dataType: "text",
success:function(result){
setSomeData(result);
}
});
}
var someDataArray = new Array();
function setSomeData(resultData){
var resData = resultData.split('^');//record split
for(var i = 0; i < resData.length; i++){
someDataArray[i] = resData[i].split('#');//field split
someDataArray[i].pop();//removes array element occupied by '^'
if(i == resData.length - 1){
setDataArray();
}
}
}
This for loop in setDataArray() doesn't create the correct array structure because someDataArray[x] is just a string:
var dataArray = new Array();
function setDataArray(){
for(var i = 0; i < dataArray.length; i++){
dataArray[i] = someDataArray[i];
}
}
So I tried putting someDataArray[x] in an array like so:
dataArray[i] = [someDataArray[i]];
But that didn't work either.
I've spent the 2 days trying to puzzle this out, reading blogs, and experimenting with everything I could think of, but no luck. I think it's a simple solution but I just can't get it.
Help?
EDIT:
After learning a bit about JSON and json_encode I now have my script working. I wanted to post the way I did it to acknowledge that I received some valuable advice from Pat Burke. The code below may not be what he had in mind but I massaged it until it worked. But I don't really understand why it works, so I'll have to do some more reading on json_encode I think.
Note that using dataType:"json" in the ajax call threw an error.
//GetSomeData.php
$return_arr = array();
$query1 = "SELECT * FROM mytable ORDER BY idx ASC";
$result = mysql_query($query1) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result)){
$resultArray = array();
$resultArray[] = (int)$row['dc'];
$resultArray[] = (int)$row['smlspc'];
$resultArray[] = (float)$row['sclx'];
$resultArray[] = (float)$row['scly'];
$resultArray[] = (int)$row['lgspc'];
$resultArray[] = (int)$row['colr'];
$resultArray[] = (int)$row['diam'];
if(count($resultArray) == 7){
array_push($return_arr, $resultArray);
}
}
echo json_encode($return_arr);
mysql_free_result($result);
//new js
function getSomeData(){
resultData = new Array();
$.ajax({
type: "GET",
url: "GetSomeData.php",
dataType: "text",
//dataType: "json", //using this threw an error (see below)
success:function(result){
resultData = $.parseJSON(result);
$("#p1").append("resultData.length =" + resultData.length + "<br />");
//resultData.length =114 (it's a string not an array)
$("#p1").append("resultData =" + resultData + "<br />");
//resultData =
//[[50,10,0.375,0.25,50,0,0],
//[50,10,0.3,0.2,50,0,1],
//[50,10,0.6,0.4,0,0,2],
//[50,0,0.4,0.4,0,0,3],
//[50,0,0.4,0.4,0,0,3]]
for(var i = 0; i < resultData.length; i++){
$("#p1").append("resultData[" + i + "] =" + resultData[i] + "<br />");
//data displayed with dataType: "text"
//resultData[0] =50,10,0.375,0.25,50,0,0
//resultData[1] =50,10,0.3,0.2,50,0,1
//resultData[2] =50,10,0.6,0.4,0,0,2
//resultData[3] =50,0,0.4,0.4,0,0,3
//resultData[4] =50,0,0.4,0.4,0,0,3
//data displayed with dataType: "json"
//resultData is null
}
},
//this has no effect with either dataType: "text" or dataType: "json"
contentType: 'application/json'
});
}
if someDataArray[i] is a string of values separated by commas, you could do
dataArray[i] = someDataArray[i].split(',')

Categories