First, I realize there are a lot of other similar posts. I have read through many, and I have still not been able to this it to work. That being said.....I have a 2 dimensional javascript object that is created dynamically. I am trying to pass it to PHP so I can save insert it into a MySQL table. It looks like the easiest way to do this is with an Ajax post.
Here is my javascript:
var jsonString = JSON.stringify(TableData);
$.ajax({
type: 'POST',
url: 'submit.php',
data: jsonString,
success: function(){
alert("OK");
}
});
I always get the success alert so I don't think the problem is there.
Here is my PHP file.
<?php
$servername = "localhost";
$username = "SME";
$password = "mypass";
$db = "p3";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
if (!$conn) {
die("Could not connect to database");
} else echo "hey hey";
$data = json_decode("jsonString");
print $data;
?>
I am not really sure what I am doing wrong. Both of the files are in the same folder so I don't think it's a URL problem. Any help would be appreciated.
I see the problem. In order to access the what you're passing on, you need to get it from the $_POST variable which is an array. You can iterate over that array to get what you need and insert it in to your database after doing '$data = json_decode($_POST);`
Notice that your type in AJAX is post this is the same as the form method. It might also help in your ajax if you added `dataType: "json" to your parameters.
$.ajax({
type: 'POST',
url: 'submit.php',
data: jsonString,
dataType: 'json'
success: function(){
alert("OK");
}
So it looks like in your PHP you're not actually grabbing the posted data.
This is how I would recommend getting the data:
<?php
// Check if the posted value is not empty
if (!empty($_POST('jsonString')) {
$jsonData = json_decode($_POST('jsonString'));
}
?>
Then you can do what you need to do with the $jsonData.
The main problem was in my PHP code. Here's the answer.
$data = json_decode($_POST['denied'], true);
I was then able to insert into my MySQL table like this:
foreach($data as $user) {
$sql = "INSERT INTO deniedusers (firstname, lastname, username, email, password) values ('".$user['fname']."', '".$user['lname']."', '".$user['uname']."', '".$user['email']."', '".$user['password']."')";
I appreciate everyone's answers. Thanks!
Related
So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support
I want to fetch data based on ajax call
this is my code to get the id
<h3> <a class='click' data-id='<?=$rows["id"];?>'><?=$rows['title'];?></a</h3>
This is my jquery code
$(document).ready(function() {
$(".click").on('click',function() {
var id= $(this).attr("data-id");
alert(id);
$.ajax({
type: "POST",
url: "getevents.php",
data: {id:id},
dataType: "html",
success: function(response){
console.log(response);
}
});
})})
</script>
getevents.php
<?
if(isset($_POST['id'])){
echo $_POST['id'] ;
}
$singleevent = mysqli_query($link, 'SELECT * FROM `events` WHERE `id`=."'$id'" ') or die('error');
while($row= mysqli_fetch_array($link , $singleevent)){
print_r($row);
}
?>
$_POST['id']; gets printed in console but not the response . i tried echo and print_r() both in while loop but nothing is in response .
Please help me with this
There are a couple of problems in your PHP. First, you forget to reassign the variable, then you improperly concatenate the variable in your query. You also probably do not want the query to run if the id is not set, so you need to re-arrange your brackets:
<?
if(isset($_POST['id'])){
$id = $_POST['id'] ; // set the variable for the query
$singleevent = mysqli_query($link, "SELECT * FROM `events` WHERE `id` = $id") or die('error');
$row= mysqli_fetch_array($singleevent, MYSQLI_ASSOC);
print_r($row);
}
?>
I am assuming that your $link is a good and correct connection to your database. You also do not need a while loop, assuming that the id selects a single row of data. You also need to fetch the array properly, using the result of the query and MYSQLI_ASSOC like this:
$row= mysqli_fetch_array($singleevent, MYSQLI_ASSOC);
Which I have included in the code block.
NOTE
If PHP short tags are not enabled you will need to change <? to <?php
WARNING
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!
I am trying to send some data from JS to PHP and make a DB request, which goes back into my JS.
Problem is, I only get "null" as result.
I checked and double checked my Query which is perfectly fine.
Here the JS:
var selectedEngin = getSelectedText(enginID);
selectedEngin = selectedEngin.slice(0, -1);
var roleNameList = new Array();
$.ajax({
url: '/getRoleNames.php',
type: "POST",
dataType:'json',
data: { engin : selectedEngin },
success: function(data){
console.info(data);
}
});
And the PHP:
include_once ("config.php");
$userAnswer = $_POST['engin'];
$row = array();
$query="select ROLE_NAME from type_vehicule_role WHERE TV_CODE
='".$userAnswer."' ORDER BY ROLE_ID" ;
$result=mysqli_query($dbc,$query);
$row=mysqli_fetch_array($result);
echo json_encode($row);
If I give back "test" instead of $row, it works perfectly as well.
Hope you can help me! Thank you!
Have a nice day!
$dbc has to contain the info with the parameters to connect to the DB. In your case the $result is null as your connection cause an error.
Try using this to get all of the data properly encoded prior to feeding it to the json_encode() call.
include_once ("config.php");
$userAnswer = $_POST['engin'];
$row = array();
$query="select ROLE_NAME from type_vehicule_role WHERE TV_CODE
='".$userAnswer."' ORDER BY ROLE_ID" ;
$result=mysqli_query($dbc,$query);
$row=mysqli_fetch_array($result);
// Walk the array and encode everything in UTF8
$utf8Row = array_map(utf8_encode, $row);
// JSONify the encoded array
echo json_encode($utf8Row);
Thanks to BA_Webimax I found the problem and got an answer:
The problem was the charset. I solved it using mysqli_set_charset($dbc,"utf8"); in the PHP.
Thank you for your help guys!
Have a nice day!
So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)
Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.
So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.
function selectChar(uname, cname)
{
var data = {
username : uname,
charname : cname
};
$.ajax({
data : data,
type : 'Get',
url : 'start.php',
dataType:"json",
success : function (result) {
var data_character = JSON.parse(result);
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
}
});
}
The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.
function selectChar(uname, cname)
{
$.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
});
}
and finally the PHP code that queries the database and echos the data back.
<?php
$conn = new mysqli($hostname,$username,$dbpassword, $dbname);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_GET['username'];
$charname = $_GET['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
//Send the array back as a JSON object
echo json_encode($result);
?>
I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!
P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.
try this:
php get post and return json_encode
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$charname = $_POST['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
//Send the array back as a JSON object
echo json_encode($rows);
?>
JS ajax response and request
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
processData: false,
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
I would also try echo json_encode($_POST) to see if the you get the following response back :
{username: "hello", charname: "hl"}
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)