I have a problem that I unable to save data that are parsed from Javascript into PHP. The problem came when I implement WordPress. On single index.html it is working and data able to store in the database.
On Javascript file : (send data)
var dbParam = JSON.stringify(data);
console.log(dbParam);
var obj, dbParam, xxmlhttp;
xxmlhttp = new XMLHttpRequest();
xxmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// document.getElementById("demo").innerHTML = this.responseText;
}
};
xxmlhttp.open("GET", "http://localhost/trackpage/dummy-data/saveDB.php?x=" + dbParam, true);
xxmlhttp.send();
console.log("send");
On PHP file: (get data)
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli ("localhost", "root", "", "laravelcrudwebapp");
$stmt = $conn->prepare("INSERT INTO tracks (data1,data2) VALUES (?, ?, )");
$stmt->bind_param("ss",$obj->data1,$obj->data2);
$stmt->execute();
$stmt->close();
$conn->close();
If you're going to send your data as a GET parameter, you have to URL-encode it first:
var dbParam = encodeURIComponent(JSON.stringify(data));
However, I will point out that it is extremely bad practice to perform write operations via GET requests. You're leaving yourself wide open for all sorts of abuse and cross-side scripting attacks. For starters, you can read this post, as well as do some research on Google:
https://softwareengineering.stackexchange.com/questions/188860/why-shouldnt-a-get-request-change-data-on-the-server
Related
I'm do output with json_encode to sending to javascript, with this code.
<?php
include "Connection.php";
$syntax_query = "select * from product";
$thisExecuter = mysqli_query($conn, $syntax_query);
$result = array();
while($row = mysqli_fetch_assoc($thisExecuter)){
array_push(
$result,
array(
"id" => $row["product_id"],
"name" => $row["product_name"]
)
);
}
echo json_encode($result);
?>
so output show like this,
[{"id":"121353568","name":"Baju Casual - Black"},{"id":"556903232","name":"Tas LV - Red"},{"id":"795953280","name":"Sword - Wood"},{"id":"834032960","name":"Scooter - Iron Plate"}]
and code javascript like this
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var obj = this.responseText;
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
so obj.id its not working, output show undifined.
I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.
If Jquery is imported then ignore the steps
Here are steps,
Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
Import the js file in the HTML file in script tag as shown '
Now, this is the ajax example to call the PHP file and to get a response
function showHint() {
//since you have used GET method I have used here GET but You can use POST also here
$.ajax({
url: 'Download.php',
type: 'get',
//if any value you want to pass then uncomment below line
// data: {'name_to_pass':'value'},
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
success: function(res)
{
// open DevTool console to see results
console.log(JSON.parse(res));
}
});
}
Hope this will help you out, thank you
Maybe you need a JSON.parse in the response, something like JSON.parse(this.responseText).
And also I can see the result is an Array so you will need to iterate obj
obj.forEach(item => {
document.getElement("txtHint").innerHTML = item.id;
});
you should define the response type as json
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
**var obj = this.responseText;**
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
When you get the responseText it's text, not an object.
var obj = this.responseText; should be let obj = JSON.parse(this.responseText);
Then you can access obj.id as a property.
I know how to pass data from JS to PHP using AJAX, but have no idea how to select data to JS from db using AJAX+php.
I tried to find examples of it but nothing clear found.
Could anyone show me how can I get data from SQL? How I tried:
js function
getdata() {
// ?
var result // I want result to store here
var data = new FormData();
data.append('somekey', 'somevalue');
// AJAX CALL
var xhr = new XMLHttpRequest();
// query for getting some data from SQL
xhr.open('POST', "../php/get_answer.php", true);
xhr.onload = function(){
result = this.response // I presume that I can get result here
};
xhr.send(data);
console.log("RESULT GETTING JSON")
console.log(result)
}
get_answer.php
<?php
include("config.php");
$con = setConnection();
$id = $_COOKIE["id"];
$query = "SELECT results FROM `survey_results` WHERE user_id='$id'";
$n = mysqli_query($con, $query);
$results = 0;
while ($row = mysqli_fetch_assoc($n)) {
$results = $row['results'];
}
// return results ?
$con->close();
?>
In your php file, you can return your data as JSON string.
To do this, tell the client it's json by settings the response header to
header('Content-Type: application/json');
and return the results or data with
echo json_encode($data);
For the Javascript part, XMLHttpRequest is now an old way to make Ajax request but it's a good start to learn.
Fisrt, in your code you have to check if XMLHttpRequest is available in the navigator and try to use the old IE fashion way if not. To do this:
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
now you have your object so you have to set a listener witch listen for change in the state of XMLHttpRequest. If all seems ok the result go there:
xhr.onreadystatechange = function()
{
console.log("Wait server...");
if(xhr.readyState == 4) // 4 : request finished and response is ready
{
if(xhr.status == 200) // HTTP OK
{
console.log("Got data!");
result=xhr.responseText; // or result = JSON.parse(xhr.responseText) to have your data as js object
//It's here you have to modify your dom to show your data, change a variable, etc...
} ;
else // bad http response header like forbiden, not found, ...
{
console.log("Error: returned status code", xhr.status, xhr.statusText);
}
}
};
now you can set the URI and send your request:
xhr.open("GET", "../php/get_answer.php", true);
xhr.send(null)
;
If you want more informations about states and status, have a look at XMLHttpRequest Object Methods
[SOLVED]
I have a terrible headache, because I am new to JS and AJAX/JSON and cannot seem to figure out why this is happening. I am getting a JSON formatted response that looks like this when output on my client web page:
[{"ticket_id":"2","ticket_name":"super_rugby_18_Aug_2017","ticket_desc":"Brumbies vs Sharks, 14:30","ticket_price":"420.00"}]
The problem is, that I cannot parse the responseText with JSON. But whenever I hardcode the parsed string to be [{"ticket_id":"2","ticket_name":"super_rugby_18_Aug_2017","ticket_desc":"Brumbies vs Sharks, 14:30","ticket_price":"420.00"}], the problem goes away.
But of course, I need the database request to be parsed and not the hardcoded string. Please help. Here is my code that is not working:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var input = String(this.responseText);
var jsonObj = JSON.parse(input);
document.getElementById("history").innerHTML = jsonObj[0].ticket_id;
}
}
Hardcoded 'string' variable that can be parsed:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var string = '[{"ticket_id":"2","ticket_name":"super_rugby_18_Aug_2017","ticket_desc":"Brumbies vs Sharks, 14:30","ticket_price":"420.00"}]';
var jsonObj = JSON.parse(string);
document.getElementById("history").innerHTML = jsonObj[0].ticket_id;
}
}
Here is the output of stringify:
"\r\n\r\n\r\n\r\n\r\n\r\n\r\n[{\"ticket_id\":\"1\",\"ticket_name\":\"IIC_match3\",\"ticket_desc\":\"\",\"ticket_price\":\"589.99\"},{\"ticket_id\":\"2\",\"ticket_name\":\"super_rugby_18_Aug_2017\",\"ticket_desc\":\"Brumbies vs Sharks, 14:30\",\"ticket_price\":\"420.00\"}]\r\n\r\n" The array is filled in this php loop:
php loop I use to send the JSON array
$rows = array();
while ($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
$json = json_encode($rows);
echo $json;
SOLUTION:
Guess what the problem was? My web service is running in a Linux VM environment, and my calling web client was too. Now when I tried doing the httprequest from a WINDOWS machine to the VM, the JSON.parse works! What could be wrong with my Linux configuration?
//Sent an ajax http post request to a php file on the server, the post //request is a simple object.
var xhr = new XMLHttpRequest();
var person = {
"firstName" : "Adebowale",
"lastName" : "Johnson",
"ago" : 43
}
xhr.open("POST","phfile.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
var status = xhr.status;
if((status >= 200) && (status < 300) || (status === 304)) {
alert(xhr.responseText);
}
}
};
xhr.send(JSON.stringify(person));
//if I do alert(xhr.responseText);
//I get object{} from the browser.
//On the server, using php, how do I access the object, if I do echo or //print_r, I get the empty object --- object{} with none of the properties.
//As you can tell from the tone of my question, am still very new to all //these, am just trying to learn please.
//on my phfile.php, I set up the following php code...
<?php
print_r
//How do I access the object I sent to this file please
?>
I dont see the need for JSON.stringify(person) in your AJAX request, since all the keys of the Object are already in strings.
Since you are using POST method, you can directly access the object like
print_r ($_POST['person']);
You can read raw POST data using STDIN:
$post_data = fopen("php://input", "r");
$json = fgets($post_data);
$object = json_decode($json);
$firstName = $object->firstName;
$lastName = $object->lastName;
$age = $object->age;
You could simplify all of this by just passing the data as URL-encoded form fields:
xhr.send('firstName=' + encodeURIComponent(person.firstName) + '&lastName=' + encodeURIComponent(person.lastName) + '&ago=' + encodeURIComponent(person.ago);
Then you can just access them as $_POST['firstName'], etc. in PHP.
I have tried and tested various methods for completing this task for about a day now. Please be forewarned that I am building this simply, and then working my way up!
I have a form that consists of a textarea, and two input fields. The input fields allow a XMLHttpRequest to send information pertaining to a username, and message - sent to a chatroom that I am trying to make.
The problem that I have with my request, is simply that I can send the information, and insert a row into a database, but I can't get any information back! You will see from the code below, that I have put an alert in, to check what the response text is, but it comes back as null (not undefined, but ""). Please check the code below:
function insertMessage() {
var username = document.getElementById('username').value;
var message = document.getElementById('message').value;
var queryString = "username=" + username + "&message=" + message;
// send the username and message information to be inserted into the database
var url = 'classes/chatroom/chatroom.upload.php';
// create xml request
var request = createCORSRequest("POST", url)
// create a function that will receive data sent from the server
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(queryString);
}
function createRequest(method, url) {
var thisRequest = new XMLHttpRequest();
if ("withCredentials" in thisRequest) {
// thisRequest has 'withCredentials' property only if it supports CORS
thisRequest.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { // if IE use XDR
thisRequest = new XDomainRequest();
thisRequest.open(method, url);
} else {
thisRequest = null;
}
return thisRequest;
}
The code that pertains to the insertion of a database row is:
<?php
include 'chatroom.config.inc.php'; // the database file
$message_username = $_POST['username'];
$message_content = $_POST['message'];
if ($message_username == "Username: Once entered, you don't have to enter again" || $message_username == "") {
$message_username = "Guest";
}
if ($message_content == "Message:" || $message_content == "") {}
else {
$users->post_message($message_username, $message_content); // insert database row using PDO query
}
?>
Could anyone provide a clue as to where I'm going wrong?
The code looks good to me, your PHP code is inserting the data in DB but it isn't returning back any text or value.
For values to be retrieved on the client side i.e. on successful completion of your ajax request, you will have to send the data to client side.
Try using php's echo function and return the text / value.