I am using the $.getJSON jQuery function to allow my site to interact with a server at a different domain. However, I've been stuck fixing a bug which causes the third and fourth data item to be undefined. I’m not sure where the problem is.
JavaScript:
$.getJSON(domain_path + 'display.php?url=' + purl + '&callback=?', function(data) {
var username = data['uname'];
var point = data['point'];
var email = data['email'];
var title = data['title'];
});
The email and title are undefined, but uname and point are correct.
JSON is generated by this PHP:
$url = mysql_real_escape_string($_GET['url']);
$result = mysql_query("SELECT * FROM user url='$url'")or die(mysql_error());
$row = mysql_fetch_array($result);
if($row){
$uname = $row['uname'];
$point = $row['point'];
$email = $row['email'];
$title = $row['title'];
$output = array('uname'=>$uname,'point'=>$point,'email'=>$email,'title'=>$title);
$out_string = json_encode($output);
echo $callback.'('.$out_string.');';
}
JSON results look like this:
284927410({"uname":"john","point":"104","email":"john482#yahoo.com","title":"teacher"});
I am able to get john and 104, but email and title come up undefined when I put them in an alert().
Is there some rule I missed? Or is there something wrong in the code?
I reproduced your environment and everything is working fine using this code:
$.getJSON("http://localhost:8081/test", function(data) {
alert(data.uname);
alert(data.point);
alert(data.email);
alert(data.title);
});
Where the path http://localhost:8081/test returns only
{"point":"104","title":"teacher","email":"john482#yahoo.com","uname":"john"}
Related
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.
When i tried to use var textField and String(), the result display null.What i posted below, it display Error #2007 Parameter text must be non-null. Trying to pass the echoed results from mysql through php on AS3, through a few dynamic text box.
But when i switch it to Trace(event.target.data), it shows the correct Data.
Here is my AS3 code
var Mend:URLRequest = new URLRequest("http://localhost/Autoresult.php");
Mend.method = URLRequestMethod.POST;
var variablesss:URLVariables = new URLVariables();
variablesss.nobed1 = result.text;
variablesss.LoZip=result2.text;
variabless.rangelow=result3.text;
Mend.data = variablesss;
var BLoader:URLLoader = new URLLoader();
BLoader.dataFormat = URLLoaderDataFormat.TEXT;
BLoader.addEventListener(Event.COMPLETE,Candler);
BLoader.load(Mend);
// handler for the PHP script completion and return of status
function Candler(event:Event){
var seVariables: URLVariables = new URLVariables(event.target.data);
result.text=seVariables.nobed1;
result2.text=seVariables.LoZip1;
result3.text=seVariables.rangelow1;
}
Here is my php code
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
$_SESSION['username'];
$username=$_SESSION['username'];
$result=mysqli_query($con,"SELECT * FROM Test WHERE username = '$username'")or die( mysqli_error($con));
$solutions = array();
$check_num_rows=mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result))
{
$solutions[0]=$row['nobed1'];
$solutions[1]=$row['LoZip1'];
$solutions[2]=$row['rangelow1'];}
echo "nobed1=.$solutions[0]&LoZip1=.$solutions[1]&rangelow1=.$solutions[2]";
?>
Thanks for your time
without looking into it too deeply, it seems like it might be a type miss-match.
you could try
var seVariables: URLVariables = new URLVariables(event.target.data + "");
that way it is converted to text
I managed to resolve my problem, changing the php, and putting the result in a string, pass it through to AS3, then split up the answer and put them into the dynamic text box.
Here is my code.
function Candler(event:Event){
var fromPhp:String = event.target.data;
var errors:Array = fromPhp.split(",");
trace(errors.length)
result.text= (errors[0].replace(/^\s+|\s+$/mg, ""));
result2.text= (errors[1].replace(/^\s+|\s+$/mg, ""));
result3.text= (errors[2].replace(/^\s+|\s+$/mg, ""));
result4.text= (errors[3].replace(/^\s+|\s+$/mg, ""));
}
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"
So I've been banging my head against my desk for a few hours on this one and i'm not getting anywhere so help would really be appreciated.
The code below has two jquery event handlers which fire off an ajax request. The first one uses GET and the data it gets back from the server is JSON encoded - it works fine. The second one ( "button#addTx" ) returns causes Firebug to produce this error:
uncaught exception: [Exception...
"prompt aborted by user" nsresult:
"0x80040111 (NS_ERROR_NOT_AVAILABLE)"
location: "JS frame ::
resource://gre/components/nsPrompter.js
:: openTabPrompt :: line 468" data:
no]
Line 0
which is no help to at all. The server side script is printing raw html to the screen and the aim is that a jquery html replace will be used to update to the page which initiates the request. The data is POSTed correctly as the database updates but beyond that I have no clue. I have rewritten it to try a GET and still produce the same error :-(
Help would be amazing - thank you, Simon
$(document).ready(function(){
$("button.delete").click(function(){
var txid = this.id;
var amountID = "#amount" + txid;
var amount = $(amountID).html();
// <![CDATA[
var url = "delete.php?txid=" + txid + "&am=" + amount;
$.ajax({
type: "GET",
url: url,
success: function(msg){
txid = "ul#" + txid;
$(txid).hide();
var values = msg;
var e = "#" + values.category + "AmountLeft";
var a = values.amount;
$(e).html(a);
}
});
});
$("button#addTx").click(function(){
// <![CDATA[
var url = "addTran.php";
//var dataV = var data = "category=" + document.getElementById("category").value + "&what=" + document.getElementById("what").value + "&amount=" + document.getElementById("amount").value + "&date=" + document.getElementById("date").value;
$.ajax({
type: "POST",
url: "addTran.php",
//async: false,
data: "category=Groceries&what=Food&amount=2.33&date=2/3/2011",
success: function(msg){
$("transList").replaceWith(msg);
}
});
});
});
and here is the server side script
<?php
session_start();
include('functions.php');
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
$category = $_POST['category'];
$what = $_POST['what'];
$amount = $_POST['amount'];
$date = $_POST['date'];
$category = mysql_real_escape_string($category);
$what = mysql_real_escape_string($what);
$amount = mysql_real_escape_string($amount);
$date = mysql_real_escape_string($date);
$date = convertDate($date);
//add trans to db
include('dbcon.php');
$query = "INSERT INTO transactions ( category, what, amount, date) VALUES ( '$category','$what','$amount','$date');";
mysql_query($query);
//grab the remaining amount from that budget
$query = "SELECT amount_left FROM cards WHERE category = '$category';";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$oldAmountLeft = $row["amount_left"];
//update the amount left
$amountLeft = $oldAmountLeft - $amount;
mysql_free_result($result);
//add new value to db
$query = "UPDATE cards SET amount_left = '$amountLeft' WHERE category = '$category';";
mysql_query($query);
//generate the list of remaining transactions, print to screen to send back to main page
$query = "SELECT txid, what, amount, date FROM transactions WHERE category = ('$category');";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$d = convertDateReverse($row["date"]);
$what = $row["what"];
$amount = $row["amount"];
$txid = $row["txid"];
?>
<li><ul class="trans" id="<? echo $txid; ?>"><li class="date"><? echo $d; ?></li><li class="what"><? echo $what; ?></li><li class="amount" id="amount<? echo $txid; ?>"><? echo $amount; ?></li><button class="delete" id="<? echo $txid; ?>">Delete</button><li></li></ul></li>
<?
}
mysql_free_result($result);
mysql_close();
header("Content-type: application/x-www-form-urlencoded"); //do I need this? I have a " header("Content-type: application/json"); " in the working one
?>
PROBLEM SOLVED: so in the html markup the form that holds the fields of data should have an
onsubmit="return false;"
in it!
Thanks for all the help guys, I have implemented all your suggestions and my code is now soooo much smaller and easier to manage!
Cheers
Simon
Thx for posting the solution. Similarly banged my head for a while trying to solve a similar problem with NS_ERROR_NOT_AVAILABLE without luck. Useful for for people using Django <--> Javascript to do XMLHttpRequests as well. On the Django side, there is an
error: [Errno 32] Broken pipe
...that corresponds with the NS_ERROR that appears in the firebug console for the JS failure.(googleBait) It's hard to know where to start tracing the problem - server side or client side.
Thx again.
i am sending some value to a php file like this:
$.post('php/xxx.php', { username: userName } );
and the php file echo'es out a var $test
how can i get it back into the js?
i was thinking to use this:
var get_back = $.get('php/xxx.php', ... );
but i am not sure how...
thanks
edit:
here is my php file:
include("connect.php");
$get_username = $_POST['username'];
$username = '';
$username = mysql_real_escape_string($get_username);
echo $get_username;
$result = mysql_fetch_assoc(mysql_query("SELECT username FROM database WHERE username='$username' LIMIT 1"));
if($result !== FALSE) {
echo $username;
}
i want to get back this echo $username; value
The various ajax functions in jQuery (ajax, post, get) accept callback functions where you can handle the returned data:
//define username outside so that
//it's available outside of the scope
//of the callback function
var username;
$.post('php/xxx.php',
{ username: userName },
function(data){
//per the comment below,
//assuming data will simply
//be the username
username = data;
});