Send Javascript info to php and save it on a database - javascript

A former co-worker developed an a quiz which sended results to a databse. He was fired but i need to use that code again . I only have the javascript code and i need to recreate the php ( save.php) which saves the info from javascript . Can you help me with the php code or give me a hint . Thaks !
$(document).ready(function() {
$("#answer_a").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "a" } );
});
$("#answer_b").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "b" } );
});
$("#answer_c").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "c" } );
});
$("#answer_d").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "d" } );
});
});

In save.php use $_GET[] to to use the variables and save them on your table
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$test = mysqli_real_escape_string($con, $_GET['test']);
$question = mysqli_real_escape_string($con, $_GET['question']);
$answer = mysqli_real_escape_string($con, $_GET['answer']);
$sql="INSERT INTO Persons (test, question, answer)
VALUES ('$test', '$question', '$answer')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

Use $_GET[<name>] to get the values in your php and mysqli_connectto insert the data into the table.

You are already on the right track, the next move is in the PHP. You can use this example to get those values. Consider this example:
<?php
if(isset($_GET['test'])) {
$data = array(); // initialize return data holder
$test = isset($_GET['test']) ? $_GET['test'] : null;
$question = isset($_GET['question']) ? $_GET['question'] : null;
$answer = isset($_GET['answer']) ? $_GET['answer'] : null;
// they should be inside now, now you can go on with mysql inserts
// just a sample callback value to check if indeed php got it
$data['test'] = $test;
$data['question'] = $question;
$data['answer'] = $test;
echo json_encode($data);
exit;
}
?>
<!-- lets say this is an image -->
<button id="answer_a" type="button">Hi im an image</button>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#answer_a").click(function() {
$.get("index.php", {test: "1", question: "1", answer: "a" }, function(response){
var data = $.parseJSON(response);
console.log(data); // check this in console
});
});
});
</script>

Related

Formatting JSON data and displaying in a PHP for loop

I have some form data which I'm saving in JSON format using jQuery (this is all working fine).
But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.
check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children
But I want to separate each room e.g.
(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children
JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/
PHP I'm using to try a display JSON data in for loop (not working):
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data, true);
//print_r($data);
foreach($data as $key => $val) { ?>
<?php echo $key; ?>
<?php } ?>
The issue is how you're building the JSON. Each item has it's own object due to the use of serializeArray() on the form, which means you have no idea what property is for what room.
To fix this use map() to build the array of objects per room. Like this:
function save_all_rooms() {
$(".save_all_rooms").on('click', function(e) {
var formData = $('.add_new_form .the_form').map(function() {
return {
check_in: $(this).find('[name="check_in"]').val(),
check_out: $(this).find('[name="check_out"]').val(),
room_type: $(this).find('[name="room_type"]').val(),
adults: $(this).find('[name="adults"]').val(),
children: $(this).find('[name="children"]').val()
}
}).get();
console.log(formData);
});
}
Updated fiddle
The result of this will be in the below format, where each object contains the properties of a room. This can then be easily iterated over:
[{
"check_in": "07/04/2017",
"check_out": "07/10/2017",
"room_type": "option_1",
"adults": "1",
"children": "1"
}, {
"check_in": "07/28/2017",
"check_out": "07/31/2017",
"room_type": "option_3",
"adults": "3",
"children": "3"
}]
I think this should work
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data, true);
//print_r($data);
foreach($data as $key => $val) {
foreach($val as $val_key=>$val_val) {
echo $val_key.":".$val_val."</br>";
}
}
?>
you should use $data as $key and echo $key['name']
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data, true);
// echo "<pre>";
// print_r($data);
$i=0;
foreach($data as $key) {
if($i==2) break;
echo 'Name: '.$key['name'];
echo "<br>";
echo 'Value: '.$key['value'];
echo "<br>";
$i++;
}
?>
Use json_decode to read the json value and you can use array_slice to keep the first two elements.Try this one:
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data);
foreach(array_slice($data,0,2) as $key => $val) {
echo $val->name."-".$val->value."<br>";
} ?>
check the Output here

Sending and processing an associative array from jquery to php

I have a filter for some devices in a webpage, made of checkbox. Whenever one of the checkbox is clicked, i call a function which add to an object the value of the checkboxes checked. I want to send this object to a php file, via ajax, and use it to perform some MySQL query, then return the results from the php and display them on the page. The problem is, i'm missing something, since i kept getting a parseerror in my js.
Here's my code:
device-filter.js
$(document).ready(function(){
$(".ez-checkbox").click(function() {
console.log("ok");
var re = {Brand: "", Cost: "", OS: ""};
$("#Brand :checkbox:checked").each(function(){
re.Brand += $(this).val()+" & ";
});
$("#Cost :checkbox:checked").each(function(){
re.Cost += $(this).val()+" & ";
});
$("#OS :checkbox:checked").each(function(){
re.OS += $(this).val()+" & ";
});
if(re.lenght==0){
}
else{
$.ajax({
method: "POST",
dataType: "json", //type of data
crossDomain: true,
data: re,
url:"./php/filtered-device-query.php",
success: function(response) {
//display the filtered devices
},
error: function(request,error)
{
console.log(request+":"+error);
}
});
}
});
});
filtere-device-query.php
<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");
if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else
}
else {
//echo "Successful connection"; // connection ok
$devices =json_decode($_POST['re']);
echo var_dump($devices)."<br>";
$myArray = array();//create an array
$brand = rtrim($devices["Brand"], " &");
$cost = rtrim($devices["Cost"], " &");
$os = rtrim($devices["OS"], " &");
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
//free result
$result->close();
//close connection
$mysqli->close();
}
?>
Thanks in advance for any help!
You have some typos, first in the jQuery:
if(re.lenght==0){
should be:
if(re.length==0){// note the correct spelling of length
Then in your PHP you're using quotes on column names in the query. Those should be removed or better yet, back ticked:
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND `Cost` = '$cost' AND `OS` = '$os' ";
More importantly...
An object, as you've described it, has no length. It will come back as undefined. In order to find the length you have to count the keys:
if(Object.keys(re).length == 0){...
The object re, as you've declared it, already has 3 keys, a length of 3. Checking for length of 0 is a waste of time.
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

php string comparison search only returning one entry not returning correct entries

I'm using ajax to send a search string to a php script that executes a mysql like function to find all related entries with the username like the string being sent for friend searching. I have two current entries in the database zukeru and zukeru2. when i search z i only get zukeru returned in my console output. When i search 2 i still get zukeru and im really not sure why.
Also how to i remove a specific field from a php nested tupple. I don't want to include the password field for obvious reason. Sorry im new to php learning as i go so far its not as bad as I thought it would be kinda similar to python.
returned object when searching the number 2, but i get zukeru and not zukeru2 doesn't make sense.
Object {0: "2", 1: "you wish you could see", 2: "zukeru", 3: "deleted for security", 4: "grant", id: "2", email: "deleted for security", username: "zukeru", password: "deleted for security", name: "grant"}
this is the search string i used for the above result. You can see i searched 2 and got back zukeru and not zukeru2
profile.php:92 searchstring=2
<?php
$db = new mysqli(security reasons removed.);
extract($_POST);
//I think i can remove this session start ?
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=mysqli_fetch_array($fetch);
//echo $search_string
echo json_encode($friends);
?>
Here is my jquery incase you wanted to see
function search(){
var url = "search_friends.php";
$.ajax({
type: "POST",
url: url,
data: $("#search_friends").serialize(), // serializes the form's elements.
success: function(data)
{
//console.log(data);
var returned_friends = JSON.parse(data);
var html_built = '<br>';
console.log(returned_friends);
console.log($("#search_friends").serialize());
if (returned_friends){
$.each( returned_friends, function( key, value ) {
if (key =="username"){
html_built += '<li><a href="#"><button class="btn btn-primary" style="width:100%;" id="'+value+'" onClick="add_friend(this.id)"> Send '+value+' A Friend Request</button></li>';
}
});
}
html_built += ""
document.getElementById("list_friends").innerHTML = html_built;
}
});
return false;
}
this is what im currently using and I get undefined method. It cant find fetch_all(); and im using php 5.4
here is the console error returned.
<br />
<b>Fatal error</b>: Call to undefined method mysqli_result::fetch_all() in <b>/home/gzukel/public_html/search_friends.php</b> on line <b>7</b><br />
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends=$fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}
?>
so something like this?
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=[]
while($row = $fetch->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
array_push($friends,$row['username']);
}
//echo $search_string
echo json_encode($friends);
?>
You Could use fetch all:
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends= $fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}

PHP json_encode() - SQL limit and AJAX js

I have this PHP:
function getList() {
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array('result' => $result));
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this javascript:
$.ajax({
type: 'GET',
url: rootURL + '/' + myAPI,
dataType: "json",
success: function(list) {
var list = list.result;
console.log (list);
}
error: function( jqXHR, textStatus, errorThrown ) {
console.log (" errors: " );
console.log (jqXHR);
console.log (textStatus);
console.log (errorThrown);
}
});
now everything was working fine until I added some rows in the list table of my DB.
So now the js list result from AJAX is empty:
{"result": }
The error I receive from AJAX is:
Object { readyState=4, status=200, statusText="OK", more elements...}
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
so I tried to remove: dataType: "json", but result is still empty.
the only way to make it works is to limit the SQL query like this:
$sql = " SELECT * FROM list LIMIT 9 ";
and it works:
{"result":
[
{"ID":"1","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"2","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"3","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"4","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"5","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"6","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"7","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"8","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"9","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
]
}
I don't understand why there is such a limit. I also tried:
$sql = " SELECT * FROM list LIMIT 10 ";
and so on, but the result is still empty:
{"result": }
Can you help me please?
Thanks
Read the manual at http://php.net/json_encode. It says:
All string data must be UTF-8 encoded.
Make sure your data is in UTF-8 encoding in the database. If not you have to convert it first.
If it is working with LIMIT 9 and not working with LIMIT 10 so problem is in your records after 9th row so please check your 10th row It may have any 'special character', 'new line character' which is creating problem.
There are 2 points I'd like to point out in your code to have a look at. First of all, the construction of the error should be using the json_encode function, which will ensure valid format, so instead of doing echo '{"error":{"text":'. $e->getMessage() .'}}'; you should do
$response = new stdClass();
$response->error = new stdClass();
$response->error->text = $e->getMessage();
echo json_encode($response);
Note, that it looks overly complex, but I tried to retain the format you specified in your example.
The other thing is that Javascript will not like type: 'json' if the correct headers are not set. So what I suggest your PHP function should look like is this:
function getList() {
$response = new stdClass();
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response->result = $result;
unset($db);
} catch(PDOException $e) {
$response->error = new stdClass();
$response->error->text = $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($response);
exit();
}
I hope this helps!

PHP populated FullCalendar, looks right, but data wont show

I am using mySQL to store information about check-out dates, and then depending on the object I would like to display the times that are already taken with FullCalendar.js
I am using PHP to pull in rows and then loop through them populating the where events are created, the code looks right when I check it on the page, but data is not loaded.
Here is the code generating the page:
function getAllTimes(){
if(!empty($_GET['id']))
{
$query = "
SELECT userID, startDate, endDate
FROM checkout
Where equID =" .$_GET['id'];
global $db;
$stmt = $db->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll();
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$('#calendar').fullCalendar({
events: [";
$counter = 0;
foreach($rows as $row):
if($counter == 0)
{
echo "
{
title : '".$row['userID']."',
start : '".$row['startDate']."',
end : '".$row['endDate']."'
}";
$counter = $counter+1;
}
else
{
echo ",
{
title : '".$row['userID'].",'
start : '".$row['startDate'].",'
end : '".$row['endDate']."'
}";
$counter = $counter+1;
}
endforeach;
echo "
]
});
}}";
echo "
</script>";
}
else
echo "ID must be specified";
}
getAllTimes();
And this is the outcome when loaded, yet events are not added to the calendar.
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
events: [
{
title : 'ArtemBeer',
start : '2014-01-16 00:00:00',
end : '2014-01-16 00:00:00'
},
{
title : 'ArtemBeer,'
start : '2014-01-15 00:00:00,'
end : '2014-01-16 00:00:00'
},
{
title : 'ArtemBeer,'
start : '2014-01-09 02:02:00,'
end : '2014-01-10 03:03:00'
}
]
});
}}
</script>
Your data (JS) has a bad comma:
start : '2014-01-15 00:00:00,'
should be:
start : '2014-01-15 00:00:00',
Also use your Chrome Inspector to see JS errors via the console, otherwise you will be guessing all day long.

Categories

Resources