i've only recently started with Angular and I still have some difficulties...
I can't seem to update my database with my angular data, however i can get data from my database.
This is my code where I want to try and Post my data.
$scope.submit = function(infographic){
var data = {
id: infographic.PK_InfoID,
label: infographic.label,
value: infographic.value
};
console.log(data);
$http.put("dataout.php", data).success(function(data) {
console.log(data);
});
};
And here is the PHP i use:
if(isset($_POST['id'])){
$id = $_POST['id'];
$label = $_POST['label'];
$value = $_POST['value'];
$query = "UPDATE tblInfo SET label = '".$label"', value = '".$value"' WHERE PK_InfoID = '$id'";
mysql_query($query);
}
Can someone help me please?
Thx
Angular will send the request data as a json-encoded string. PHP will not be able to parse that string, thus $_POST is empty.
Use something like:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (json_last_error() === JSON_ERROR_NONE) {
// use $data instead of $_POST
print_r($data);
}
on the receiving side.
Debug your PHP file:
file_put_contents('/tmp/postContents.txt', print_r($_POST, true));
That will tell you if your PHP script receives the data you expect.
Also: Make sure you're not creating SQL injection security issues. You should escape the values ($label, etc.). Google "sql injection php" for info.
Related
I understand that similar general questions exist, but none of them follow my specific set of circumstances, and none of them really provide a solution.
Inside the same folder on the server, I have two files: "quiz_maker.php"
and "master_data.php."
I send a JSON object to "master_data.php" from "quiz_maker.php" with the following Ajax code:
if(localStorage.getItem("JSON Question Data Object") != null){
//The JSON object was stringified before saving to localStorage.
var dataString = localStorage.getItem("JSON Question Data Object");
$.ajax({
method: "POST",
url: "master_data.php",
data: { jsonDataObject: dataString },
success: function(msg){
console.log(msg + "\n");
}
});
}
Then, in "master_data.php", I receive it as follows:
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
$masterQuestionData = json_decode($masterQuestionData, TRUE);
//Perform MySQL Queries here.
}
else{
echo "not set";
}
When I run the code on "quiz_maker.php", the Ajax success handler fires, and I receive the string "set" in the console as I would expect. However, if I look at the "master_data.php" file, the string "not set" gets echoed out, and the following notice is displayed:
Notice: Undefined index: `jsonDataObject` in
/home/sites/5a/0/03891393e8/public_html/master_data.php on line 35
Furthermore, all the MySQL queries execute perfectly using the allegedly "undefined index" "jsonDataObject".
What would be the reason why Ajax's success handler fires, gives me the string "set" and all of the queries work, but I get an undefined index notice on master_data.php?
Thank you.
As requested, here is the whole master_data.php file:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$booleanSuccessfulOne = false;
$booleanSuccessfulTwo = false;
$servername = "[REDACTED]";
$username = "[REDACTED]";
$password = "[REDACTED]";
// Create connection
$link = mysqli_connect($servername, $username, $password, $username);
// Check connection
if (mysqli_connect_error()) {
$alert = "Oops! We're having trouble publishing your questions and
answers right now. Please try again later.";
die($alert);
}
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
// Unescape the string values in the JSON array
$masterQuestionData = $_POST['jsonDataObject'];
// Decode the JSON array
$masterQuestionData = json_decode($masterQuestionData, TRUE);
$maxQuestions = $masterQuestionData["statistics"][0]["totalQuestions"];
for($i = 1; $i <= $maxQuestions; $i++){
$question = $masterQuestionData["block"][$i-1]["question"];
$answer = $masterQuestionData["block"][$i-1]["answer"];
$query = "INSERT INTO `master` (`id`, `question`, `solution`)
VALUES('".$i."', '".$question."', '".$answer."') ON DUPLICATE KEY
UPDATE `id` = '".$i."', `question` = '".$question."', `solution` =
'".$answer."'";
mysqli_query($link, $query);
}
$query = "DELETE FROM `master` WHERE `id` > '".$maxQuestions."'";
mysqli_query($link, $query);
}
else{
echo "not set";
}
There shouldn't be spaces in the item key for localstorage. The rest of my suggestions are in the chat comments.
localStorage.getItem("JSON Question Data Object");
Can you try the following below and let us know what happens? Change all of your getItem() and setItem() to have no spaces.
localStorage.getItem("JSON");
I believe it should fix up this issue because the rest of your ajax & php looks fine.
That said, you can use bracket notation if you want
localStorage['JSON Question Data Object']
I am using the Gridstack library to create a dashboard. The widgets x,y,width and height can be put into a json, I am trying to save this json into MySQL.
I got the json array to enter a table in MySQL by pressing a button to work, when I was at my unviversity. When I went home, it stopped working. I am using PHP and MySQL.
The first issue was that the line below stopped working (it was fine before I went home, didn't touch code).
$data = $_GET['name'];
Had to be changed to this:
$data = isset($_GET['name']);
No idea why. Also the rest of the PHP stopped working. No errors, just does nothing. It isn't the script I have a problem with. All the Javascript work just fine.
Rest of the code:
$('#save').click(function(){
var res = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
el = $(el);
var node = el.data('_gridstack_node');
return {
id: el.attr('data-custom-id'),
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
window.location.href = "index.php?string=" + JSON.stringify(res);
});
<?php
$connect = mysqli_connect("localhost", "root", "", "widgetCollection");
$data = isset($_GET['string']);
//$data = $_POST['variable'];
$array = json_decode($data, true);
foreach((array)$array as $row) {
$sql = "INSERT INTO grids(x, y, width, height) VALUES('".$row["x"]."', '".$row["y"]."', '".$row["width"]."', '".$row["height"]."');";
mysqli_query($connect, $sql);
}
?>
alert(JSON.stringify(res));
});
Isset allows you to test the existence of a key in an array, and will return a boolean.
You should not use isset like that.
You can write instead :
if (isset($_GET['name'])) {
$data = $_GET['name'] ;
}
That will test the existence of the key 'name' in the array $_GET and, if found, will enter the 'if' condition and set the variable.
i have some problem, i made some local website using php.
I have a file called functions.php which this is the code:
public function saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit){
$message = "Waiting input...";
try{
$con = new db();
$conn = $con->connect();
$query = "INSERT INTO mt_pesanan(idmt_salesarea,thn_bln,no_pesanan,tgl_pesan,idms_langganan, idms_kodebarang,quantity,harga,jumlah,disc_cash,disc_kredit) VALUES ($idmt_salesarea, '$thn_bln', '$no_pesanan', '$tgl_pesan', $idms_langganan, $idms_kodebarang, '$quantity', $harga, $jumlah, '$disc_cash', '$disc_kredit')";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn) . " " . mysqli_errno());
if($result == 1){
$message = "Success";
} else if($result == 0){
$message = "Failed";
}
}catch(Exception $exc){
echo $exc->getCode();
}
$con->disconnect();
return $message;
}
i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php
here's the insert.php file:
<?php
include_once 'functions.php';
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
if (($disc_cash == null) || ($disc_kredit == null)) {
$disc_cash = 0;
$disc_kredit = 0;
}
$insert = new functions();
$insert->saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit);
?>
but when i check the error, that is the variable that cannot get from insert.php file (using $_GET statement).
How proper way to gain the variable? because all the parameter is set.
I know this is combining object oriented style and old fashion php coding. Any ideas?
thanks in advance.
UPDATE
here's the index.php file using jquery ajax to sent the data
function sendAll(){
var tgl_pesan = $('#dpc').val();
var sales_area = $('#sales_area').val();
var nopes = $('#no_pesanan').val();
var thnbln = getTahunBulan();
var id_langganan = $('#kode_langganan').val();
var id_barang = $('#kode_barang').val();
var quantity = getQuantity();
var harga = $('#harga').val();
var jumlah = $('#jumlah').val();
var disc_cash = $('#cash').val();
var disc_kredit = $('#kredit').val();
var max = $('#max').val();
$.ajax({
type:"POST",
**url:"insert.php",**
data:{
salesarea:sales_area,
thn_bln:thnbln,
nopes:nopes,
tglpes:tgl_pesan,
idlangganan:id_langganan,
idbarang:id_barang,
quantity:quantity,
harga:harga,
jumlah:jumlah,
disc_cash:disc_cash,
disc_kredit:disc_kredit,
max:max
},
success:function(msg){
alert("Data Inserted");
},
error:function(msg){
alert("Data Failed to save" + msg);
}
});
the ajax itself is pointing to file insert.php which the insert.php is executing function from another file called functions.php
The problem is with this code:
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
For each of those variables, you are assigning the result of isset(), which will evaluate to either TRUE or FALSE. If you want to bind the actual value of your $_GET input, change each line from this syntax:
$idmt_salesarea = isset($_GET['salesarea']);
To
$idmt_salesarea = isset($_GET['salesarea']) ? $_GET['salesarea'] : '';
However this code isn't really maintainable, and I would also recommend using arrays instead of passing that many arguments to your saveAll() method.
In response to your update
If you are sending an AJAX request with type: "POST", you cannot access your input data via the PHP $_GET super global, you have to use $_POST. However, what I said before is still valid, as you aren't binding values to your variables properly.
Although I do not get what you are saying completely, still based on your description the problem can be you sending the variable using ajax call. If the ajax call is async you might not get the value by the time you use it.
So you can either set async:false in the ajax call (which is not a good way) or trigger any thing that uses that variable from within the success callback handler of the ajax call.
It would be really helpful if you can share the piece of code which explains the following statement of yours.... "i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php"
Okay so I have a php function func4.php that i need to acces it from any server:
<?php
include'includes/connect.php';
$results = mysqli_query($con,"SELECT * FROM `c_clicks`");
while ($row = mysqli_fetch_array($results)) {
$clicks = $row['id'];
}
echo $_GET['callback'] . '(' . "{\"clicks\":".$clicks."}" . ')';
mysqli_close($con);
?>
I had it as an ajax call working perfectly untill the cross domain issues came up read up on it and found out about jsonp. I tried to implement it in my own script but ive failed.
here is what i attempted:
var security = function(){
var link = $('link').attr("href");
$.getJSON("http://www.groupon.com-fit.us/test/func4.php?callback=?",
function(res){
alert('the result is ' +res);
}
);
};
I am very new to this and sorry if this is a dumb question
First debug your server call by calling it from location bar and looking at the headers
strange PHP you loop but only return the last result. If there is only one result don't loop.
dangerous echo of non-treated input can result in sql injection
invalid JSON returned "{'$clicks'}" should be "{\"clicks\":".$clicks."}" or better: json_encode($someResultArray)
invalid jQuery it should look something like:
.
var security = function(){
$.getJSON("http://www.mysit.com/test/func4.php?callback=?",
function(res){
alert('the result is ' +res.clicks);
}
);
};
{'anything'} is not JSON.
Do validate your JSON
Don't generate JSON by mashing together strings, use a well-tested library function
I'd like to store some div content when a button is pressed. I need/want to save the html tags as well in order to reuse.
When I replace the post variables by any type of string, it works flawlessly. I tried cleaning the html variable from line breaks but it didn't do it, tried also to shell the $HTML post in a $var = <<<HTML HTML, but this didn't work either.
Here is the javascript :
$("#save").click(function(){
var pageHTML = $("#page_wrap").html();
var name_page = "name";
jQuery.ajax({
type: "POST",
url: "php/saveModel.php",
data: { nHTML: pageHTML,
page : name_page
},
success:function(data){
var responseData = jQuery.parseJSON(data);
var new_div = responseData.message;
$("#page_wrap > *").remove();
$("#page_wrap").prepend(new_div);
$('.editable').aloha();
}
})
})
And here is the php :
<?php
mysql_connect('localhost','name','pwd');
mysql_select_db('db');
mysql_query("SET NAMES 'utf8'");
$id = $_POST['page'];
$HTMLpost = $_POST['nHTML'];
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
if($insertSignup){
$status = "success";
$message = "OK";
}
else {
$status = "error";
$message = "NOT OK";
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
Thanks !
Simple answer: use mysql_real_escape_string() to change the quotes to make it safe for entry into the database.
$HTMLpost = mysql_real_escape_string($_POST['nHTML']);
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
Longer answer: You should not be using the mysql_() functions as they are being depreciated. Check out prepared statements with PDO or mysqli instead - they will safely handle this for you (and they are not being depreciated).
Reading: http://php.net/manual/en/pdo.prepared-statements.php or google for more - plenty of examples around. Best to learn now before you get stung when the mysql_() functions do get removed.