I am sending data to a php file using AngularJS on ng-click. I have 2 buttons and I am trying to send it to the same php file to insert into the db using switch case but it is not updating the db.
How can I fix my php?
insert.php
<?php
include_once('conn.php');
$data = json_decode(file_get_contents("php://input"));
switch($data){
case 'getvou':
$vou = $data->getvou;
$sql = $mysqli->query("UPDATE audiencia SET vou = '".$vou."'");
$mysqli->close();
break;
case 'getnaovou':
$naovou = $data->getnaovou;
$sql = $mysqli->query("UPDATE audiencia SET nao_vou = '".$naovou."'");
$mysqli->close();
break;
}
?>
script.js
$scope.add_vou = function(){
$scope.vou += 1;
$http.post("http://localhost/insert-audiencia.php", {'getvou': $scope.vou}).then(function(resp){
console.log(JSON.stringify(resp));
console.log(resp);
});
}
$scope.add_nao_vou = function(){
$scope.nao_vou += 1;
$http.post("http://localhost/insert-audiencia.php", {'getnaovou': $scope.nao_vou}).then(function(resp){
console.log(JSON.stringify(resp));
console.log(resp);
});
}
$data will be a JSON object, which will not equal either of those strings, so no case will be matched in your switch.
With the way you're currently sending the data, you need to be checking instead to see if the JSON object has a property.
if (property_exists($data, 'getvou')) {
// one query
} elseif (property_exists($data, 'getnaovou')) {
// other query
}
isset($data->getvou) etc. will also work for this.
Related
PQGrid: How I can save changes from grid to DB when I have a View as data source
I have read all examples from the homepage/forum etc. Furthermore I tried to transfer from jqGrid / other Gridtools to PQGrid. No chance.
The code below shows the PopUp-Editing opportunity and when I change any value, e.g. Prio = Priority, the values in the grid are edited, but when I reload the data, I got the original value from database.
Likewise I have created a PHP-file (Vormerkungen_Grid_Speichern.php) for parameter 'editurl' by a template, but nothing happens. He don't call this special file.
<?php
// FILENAME: Vormerkungen_Grid_Speichern.php
// Datei dient nur zum Speichen von Veränderungen im Grid
require ('./system_connector_mysql.php');
$artikelnr = $_POST['ArtikelNr'];
$aufgabe = $_POST['Aufgabe'];
$prio = $_POST['Prio'];
echo $_POST['ArtikelNr'];
echo $_POST['Aufgabe'];
echo $_POST['Prio'];
switch ($_POST["oper"]) {
case "add":
// do mysql insert statement here
break;
case "edit":
$query = "UPDATE tab_vormerkungen SET Aufgabe = '$aufgabe', Prio=$prio WHERE ArtikelNr=$artikelnr";
mysql_query($query) OR ('Vormerkungen_Speichern.php - Zeile 13 |' . mysql_error());
$datei = fopen('Vormerkungen_Speichern.txt', 'w');
fwrite($datei, $query);
fclose($datei);
break;
case "del":
// do mysql delete statement here
break;
}
?>
// FILENAME: Vormerkungen.php
function editRow() {
var rowIndx = getRowIndx();
if (rowIndx != null) {
var row = $grid.pqGrid('getRowData', { rowIndx: rowIndx });
var aufgabeAlt = row.Aufgabe;
var $frm = $("form#crud-form");
$frm.find("input[name='artikelnr']").val(row.ArtikelNr);
$frm.find("input[name='aufgabe']").val(row.Aufgabe);
$frm.find("input[name='prio']").val(row.Prio);
$frm.find("input[name='VFG']").val(row.VFG);
$("#popup-dialog-crud").dialog({ title: "Vormerkung " + row.ArtikelNr + " bearbeiten", buttons: {
Update: function () {
//update row.
row = [];
row.ArtikelNr = $frm.find("input[name='artikelnr']").val();
row.Aufgabe = $frm.find("input[name='aufgabe']").val();
row.Prio = $frm.find("input[name='prio']").val();
// Umsetzung im Grid
$grid.pqGrid('updateRow', { rowIndx: rowIndx, row: row, checkEditable: false });
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
}).dialog("open");
}
}
Thank you #Tony Tmov (Sarcasm). PQGrid has a better license for me, that is the reason why I have choose PQGrid.
I think my biggest problem is the data source. If I didn't have a view as a data source, I wouldn't have a problem with storing it in the database.
But I also have no other choice with the data source.
I have these jQuery code.
I generate 6 digits random number and I need to pass it into .post Serialize every time button is clicked. I want the number generate inside jQuery click function.
Somehow I cannot pass the value of "var tac_no" into .post Serialize.
Here's my code for jQuery
$('#request_code').click(function(e){
var tac_no = Math.floor(100000 + Math.random() * 900000);
var data_tac = $("#form-tac").serialize()+"&type="+"updateTable";
$.post("php/ajax-request-tac.php",data_tac).done(function( data ){
if(data==true)
{
alert('Request Success');
}
else if(data==false)
{
alert('Request failed');
}
});
return false;
});
And here's my php code
<?php
require 'conn.php';
function oracle_escape_string($str)
{
return str_replace("'", "''", $str);
}
if((isset($_POST['type'])) && ($_POST['type']=='updateTable'))
{
$sqlNextSeq = "SELECT SEQ_TAC.nextval AS RUNNO FROM DUAL";
$stid2 = oci_parse($ociconn,$sqlNextSeq);
oci_execute($stid2);
$row = oci_fetch_array($stid2, OCI_RETURN_NULLS);
$query = "insert into table
(
ID,
TAC_NO
)
values
(
'".$running_no."',
'".oracle_escape_string($_POST['tac_no'])."',
)
";
oci_execute(oci_parse($ociconn, $query));
echo true;
}
?>
Any idea how to do that ?
Appreciate if someone can help me. Thanks.
Personally, I'd generate the random number in PHP, but I think the issue is that you're not passing the data properly into PHP with thepost() function:
$.post("php/ajax-request-tac.php",data_tac).done(function( data ){
Instead you should pass it in as an object:
$.post("php/ajax-request-tac.php",{data_tac: data_tac, tac_no: tac_no}).done(function( data ){
Append that number to tac_no directly,
$('#request_code').click(function(e) {
var tac_no = Math.floor(100000 + Math.random() * 900000);
var data_tac = $("#form-tac").serialize() + "&type=" + "updateTable"+"&tac_no="+tac_no;
$.post("php/ajax-request-tac.php", data_tac).done(function(data) {
if (data == true) {
alert('Request Success');
} else if (data == false) {
alert('Request failed');
}
});
return false;
});
Anyway its front end code, user can always see what you are sending, so security won't be covered.
How do I get the html space characters out of my dynamic text loaded from a text file?
This is what my loaded text looks like in my .swf:
Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D
And it's my actionscript:
var select_obj:LoadVars = new LoadVars();
select_obj.onLoad = function(success:Boolean) {
if (success) {
isi.text = select_obj;
trace (select_obj);
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
select_obj.sendAndLoad(filepath + "morfologi.php", select_obj, "GET");
Here is my PHP script:
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$qResult = mysql_query ("SELECT isi FROM materi WHERE id = 1");
$nRows = mysql_num_rows($qResult);
$rString ="";
for ($i=0; $i< $nRows; $i++){
$row = mysql_fetch_array($qResult);
$rString .= $row['isi'];
}
echo $rString;
?>
To get your values sent by your script, you should return them as a URL-encoded query string containing name/value pairs like this :
message=hello&from=user1&to=user2
which can be returned by your PHP script :
<?php
echo "message=hello&from=user1&to=user2";
?>
then the LoadVars object will decode (parse) that variable string automatically for you as properties of the LoadVars object :
var result:LoadVars = new LoadVars();
result.onLoad = function(success:Boolean) {
if (success) {
trace(result.message); // gives : hello
trace(result.from); // gives : user1
trace(result.to); // gives : user2
trace(result); // gives : to=user2&from=user1&message=hello&onLoad=%5Btype%20Function%5D
} else {
trace('error !');
}
};
result.sendAndLoad(filepath, result);
Hope that can help.
Use urldecode() function:
<?PHP
$string = "Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D";
//$string = $_GET['variable'];
$rString = urldecode($string);
echo $rString;
I wanna erase %20, %2E%2E%2E%, and etc..
For that you can try either decodeURIComponent or just decodeURI. Read that manual for differences (but for your current result, any of these two is good).
An example with your code :
var result:LoadVars = new LoadVars();
var filepath:String;
filepath = "localhost/adaptasi/";
result.sendAndLoad(filepath + "morfologi.php", result, "GET");
result.onLoad = function(success:Boolean)
{
if ( success )
{
text_morfo.text = result;
text_morfo = decodeURIComponent( text_morfo );
trace("success route : "); trace( text_morfo );
}
else { trace("error in result..."); }
}
Also I don't know what else your AS & PHP code will add later so if you need a quick testing tool you can try this link. Just put your traced results into the bottom box and choose option (like unescape, decodeURI etc). This will quickly help you see which command is best to use in your AS code.
I've read multiple similar posts on this, and my code seems to match the suggestions, but still no data returned.
Here's my JS:
$.post('php/get_last_word.php', { user_id : userID },
function( data ) {
currentLanguage = data.language_id;
currentWord = data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
},'json');
And the relevant php:
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$encoded = json_encode($row);
echo $encoded;
}
And the resulting log:
Connected successfully{"language_id":"1","word_id":"1"}
So the json array is being echoed, but it's not ending up in data, because currentLanguage and currentWord are not being populated. Is this a problem with asynchronicity? Or something else?
Make sure you have a valid json coming back to your variable from your PHP script
IF your json object is like this,
{"language_id":"1","word_id":"1"}
You can access the values like this
currentLanguage = data.language_id;
currentWord = data.word_id;
Example JsFiddle http://jsfiddle.net/NuS7Z/8/
You can use http://jsonlint.com/ to verify your jSon is in correct form or not.
Specifying json as the data type value in your post request will make sure the reponse is coming back as json format to the success callback.
$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
currentLanguage = data.language_id;
currentWord = data.word_id;
});
You can also use getJson to simply get json data. getJson is a shorthand of ajax Call with datatype as json
http://api.jquery.com/jQuery.getJSON/
Try changing your JS to:
$.getJSON('php/get_last_word.php', { user_id : userID },
function( response ) {
if (response.success) {
currentLanguage = response.data.language_id;
currentWord = response.data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
} else {
alert('Fail');
}
});
and your PHP to:
<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$success = true;
$data = $row;
}
// I generally format my JSON output array like so:
// Response
header('Content-Type: application/json');
echo json_encode(array(
'success' => $success,
'data' => $data
));
?>
That way its more organized and don't forget to set the content type.
Hope that helps.
i try to send some data from html to process page. i want to do this use javascript.
the javascript is:
$('#search').click(function(){
var param = serialize({
action:"searchmodelqp",
jhead:"aaData",
month:$("#search_month").val(),
year:$("#search_year").val(),
export:"excel"
});
$('#link2excel' ).replaceWith("<div id='link2excel'><a href='shows_merchan.php?" + param + "' target='_blank'>Export result as Excel file</a></div>");
});
and i send it to this:
if(getVar('export')=='excel'){
$expexcel = 'excel';
} else {
$expexcel=0;
}
switch(getVar('action')){
case 'searchmodelqp':
modelqp(getVar('jhead'),getVar('month'),getVar('year'),getVar('export'));
break;
}
function modelqp($jsonhead,$month, $year,$export){
$Month = mysql_real_escape_string($month);
$Year = mysql_real_escape_string($year);
switch($jsonhead){
case 'aaData':
//i put mysql query here
break;
}
if($export==0) {
//do something
} else {
//do something
}
how do i do to make it clear?because i have no result for this(script do nothing).
change your data as below
data:action="searchmodelqp&jhead="aaData"&month=$("#search_month").val()&year=$("#search_year").val()&export="excel"
i change at this part:
var param = jQuery.param({action:"searchmodelqp",jhead:"aaData",month:$("#search_month").val(),year:$("#search_year").val(),export:"excel"});