AJAX does not recognize json array - php

Ajax does not want to recognize my $google['cities'] when called as data.cities.
The output is: 12 undefined undefined.
It works well (output are database records) if i remove $google['number']=12, and define database array just as $google[]=$row.
Any ideas?
PHP:
<?php
$con = mysql_connect("localhost","root","");
if(!$con) {
die("Connection Error: ".mysql_error());
}
mysql_select_db("avtost", $con);
$pasteta = $_POST["white"];
$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");
mysql_close($con);
$google=array();
while ($row=mysql_fetch_array($places)) {
$google["cities"]=$row;
}
$google['number']=12;
if (mysql_num_rows($places)>0) {
echo json_encode($google);
} else { echo 'Ni rezultatov';}
?>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
dataType:'json',
data:{white:white},
success: function(data){
var result='';
$.each(data.cities, function(i,e) {
result += '<div>'+e.sDo+'</div>';
});
$("#res").append(data.number);
$("#res").append(result);
}
});
});
});
</script>

you are overwriting the cities key in $google every time you loop for a row in $places.
you can use:
while ($row=mysql_fetch_array($places)) {
$google[]=$row;
}
$google[]=12;
and then simply grab the last value value of the array if you want to get the number key, or just pass the number as a separate variable $number.

Some tips:
1) you should be using prepared statements to secure your code (mysqli prepared). This will give you something like:
// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
$google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...
2) Improve your variable, table and column names. They are a bit confusing.
3) Instead of returning 'Ni rezultatov', you should return JSON. Such as, {"status":"FAILED"}, subsequently returning {"status":"OK", ... } for successful requests.

I solved it myself:
PHP:
while($row=mysql_fetch_array($places)){
$google['cities'][]=$row;
}
$google['number']=12;
echo json_encode($google);

Related

AJAX not working, success function is working?

the success function is working but the data is not going in the database
$(document).ready(function() {
$("#ChatText").keyup(function(e){
if(e.keyCode == 13) {
var ChatText = $("#ChatText").val();
$.ajax({
type:'POST',
url:'InsertMessage.php',
data:{ChatText:ChatText},
success:function(){
$("#ChatText").val("");
}
});
}
});
setInterval(function(){
$("#ChatMessages").load("DisplayMessages.php");
},15000000);
$("#ChatMessages").load("DisplayMessages.php");
});
PHP
<?php
session_start();
include "connectToDB.php";
if(isset($_POST['ChatText'])){
$uid = $_SESSION['userid'];
$gid = $_SESSION['GameId'];
$ct = $_POST['ChatText'];
$sql = "INSERT INTO `chats`( `ChatUserId`, `chatGameId`, `ChatText`) VALUES ('$uid','$gid',$ct);";
$result = mysqli_query($_db , $sql);
}
?>
one thing u could do to debug is that echo your sql query and see if you get the correct query that works. You can event try out that query in phpMyAdmin and see whats going on. Hard to tell anything without debug.

Ajax request not changing HTML

I created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information.
Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.
This is my code:
<script>
$(document).ready(function(){
$("#show-form-button").click(function(){
$("#show-form-button").hide();
$("#bot-form").show();
});
$("#distrito").on('change', function() {
var selected = $(this).val();
makeAjaxRequest(selected);
});
});
function insertResults(json){
alert("cenas");
$("#teste").val(json["nome"]);
}
function makeAjaxRequest(placeID){
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
}
});
}
</script>
And this is my PHP script:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$placeId = $_GET["placeId"];
$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";
$result = $conn -> query($query) or die("Query failed");
if($result -> num_rows > 0)
{
while ($row = $result -> fetch_assoc())
{
echo $row['nome'];
echo json_encode($row);
}
}
?>
Any idea what can be wrong?
I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.
Thanks for your patience and sorry for my bad english.
1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called
2) dont echo your JSON for each row like that, that's not valid either. –
Instead do this:
$response = [];
while ( $row = $result->fetch_assoc() ){
$response[] = $row;
}
echo json_encode($response);
3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];
Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
},
error: function(xhr, status, error){
console.log(xhr);
}
});
4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:
function insertResults(json){
alert("cenas");
$("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
}
In your PHP do this:
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
Also don't forget to do mysql_close($con) at the end. Hope this helps you!
From what I see you are using val() on h3 change your function to the following and use html(), The .val() method is primarily used to get the values of form elements such as input
function insertResults(json){
alert("cenas");
$("#teste").html(json["nome"]);
}

Check if cell number exists in database

i want to check if the cell number a user is trying to enter already exists.
But the code below always calls this "Cell Number in use",
what im i doing wrong? Still starting with php.
<?php
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = (isset($_POST["cell"])?
$_POST["cell"] : null);
$query=mysql_query("SELECT * from users where cell='$cell' ");
$find=mysql_num_rows($query);
echo $find;
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
This should work:
<?php
if(isset($_POST['cell'])) {
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = (isset($_POST["cell"])?
$_POST["cell"] : null);
$query=mysql_query("SELECT * from users where cell='$cell' LIMIT 1");
$find=mysql_num_rows($query);
die($find);
}
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
So if you send "data" to the script it'll look for results, output the count, and exit.
If not, it'll display the rest of the page.
Also note how I put a LIMIT 1 there, just a little performance optimization, since you only want to know if the data is there or not.
Edit: This is a better approach in terms of performance and security:
<?php
if(isset($_POST['cell'])) {
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = $_POST["cell"];
$query = mysql_query("SELECT COUNT(*) AS number from users where cell='".mysql_real_escape_string($cell)."' LIMIT 1");
$find = mysql_result($query, 0);
die($find);
}
?>
I see your post url is:
url:"formpost"
if js code and the php in the same file, the return data of ajax will be whole html and javascript instead of just "echo $find;"; of course your data will never be 0;
First thing to do is to see what is the value of data returned. That will give you some idea where the problem is. Also, it is better to use count() than to get all rows just so you can do mysql_num_rows().
SELECT COUNT(*) from users where cell='$cell'
will return the number of rows with cell that equals $cell. Interpret that result and then echo what you need. Also check if query was successful (handle errors). If the $_POST['cell'] is not set there is no reason to query the database for cell number that is null, just return desired value immediately. You also got comments that you are vulnerable to sql injections so you should consider fixing that too.
if you are receiving the result from the same page in your ajax call its as if you have browsed to the page so the returned content will include everything on the page including your javascript. Try either using a different page as the ajax target or doing somthing like this:
<?php
if(isset($_POST["cell"]))
{
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = $_POST["cell"];
$query=mysql_query("SELECT * from users where cell='$cell' ");
$find=mysql_num_rows($query);
echo $find;
}
else
{
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
<?php } ?>
Which should mean that the javascript is only written out if you dont have a post value.

Ajax post success function returning both success and error

Okay so I am trying to get ajax to post to my php file, lookup a mysql field and if it exists echo 'clientsuccess' otherwise echo 'Client already exists'
but on success function it returns both values despite the fact that they're in an php if statement.
I am quite possibly missing something incredibly simply, but any help is greatly appreciated.
PHP:
<?php
session_start();
$clientArray = $_POST['clientArray'];
$clientArray = explode(',', $clientArray);
$count = 0;
foreach($clientArray as $clientField)
{
trim($clientField);
if(empty($clientField)) {
$clientField = '-';
}
}
$con = mysql_connect("localhost",$_SESSION['MysqlUser'],$_SESSION['MysqlPass']);
if (!$con)
{
die('Could not connect with '.$_SESSION['MysqlUser'].mysql_error());
}
mysql_select_db("smeinsti_SPW_Inventory", $con);
$checkclient = mysql_query("SELECT ClientName FROM Clients WHERE ClientName = '".$clientArray[0]."'", $con);
if(mysql_num_rows($checkclient)==0)
{
$sql="INSERT INTO Clients (`ClientName`, `PhoneNumber`, `Email`, `Address`, `OrderDate`)
VALUES
('$clientArray[0]', '$clientArray[1]', '$clientArray[2]', '$clientArray[3]', CURDATE())";
$clientArray[0] = $_SESSION['ClientName'];
echo "clientsuccess";
} else {
echo 'Client already exists';
}
?>
JS:
function NextPage()
{
var ClientData = [];
$('form#order-form.create input[type=text]').each(function() {
ClientData += $(this).val() + ',';
})
alert(ClientData);
var parameters = {
clientArray: ClientData
};
$.ajax({
type: "POST",
async:false,
url: "write_client.php",
data: parameters,
success: function(result){
var res=result;
if(res = 'clientsuccess') {
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
}
});
}
Your condition Equal symbol is not correct! Put '=='
if(res == 'clientsuccess') { //Double Equal to
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
mysql_num_rows returns the number of selected rows and not the fields of a certain row. Use mysql_fetch_row to fetch the row you have selected with your query:
You could also use mysql_result to fetch a row and get a certain field:
$client exist = mysql_result($checkclient, 0, 0);
This fetches the first row (zero based) and returns the first field (zero based).

my post doesn't insert in my database

I am creating a facebook like posting system..
My problem today is it doesn't seem to insert the value i get from the text area into my data base..
here is my java script:
$("#share").click(function()
{
//var typeNew = document.getElementById("content").value;
var update = $( "textarea#content" ).val();
//document.write(update);
if(update.length == 0)
{
alert("empty, please type something.");
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
}
else
{
//$("#flash").show();
$("#flash").html('<img src="loader.gif" />Loading Comment...').fadeIn("slow");
$.ajax({
type: "POST",
url: "post_update.php",
data: 'update=' + update,
success: function(msg)
{
$("#flash").ajaxComplete(function(event, request, settings){
//alert("Successfully Inserted")
$("#flash").hide();
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
});
}
});
}
return false;
});
then here is my php code:
<?php
$post=$_REQUEST['update'];
$post=$_POST['update'];
//echo '$post';
# $db = new mysqli('localhost', 'root', '', 'wall');
if(mysqli_connect_errno())
{
echo "Error! Could not connect to database. Reset fields.";
exit;
}
$sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
$result = $db->query($sql);
if($result){
echo 'OK';
}
else{
echo 'FAIL';
}
$db->close();
?>
can someone tell me what's wrong?
it worked well when the delete function was in error but now that it's functional my share function does not work..
In your PHP code you have the following lines:
$post=$_REQUEST['update'];
$post=$_POST['update'];
You shouldn't have these both. In Your case, You actually need only the second one but for testing, try commenting it out leaving only the $_REQUEST line. Now you can pass parameters by GET too.
To see, if the query is correct, print it out too like this:
echo $sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
Now direct your browser to that location your.domain/post_update.php?update=testmessage and see the output.
If everything seems to be working, replace the POST/REQUEST lines with this:
$post=$db->real_escape_string($_POST["update"]);
I ran into this the other day. Use autocommit or start and commit transactions. Also, try a semicolon at the end of your statement (probably not the issue).
http://dev.mysql.com/doc/refman/5.0/en/commit.html
If your $post is coming out to be fine then try:
$post = $db->real_escape_string($_POST["update"]);
if (!db->query("INSERT INTO posts(update,date_posted) VALUES('$post' ,NOW())")) {
echo $db->sqlstate; //show error
}
else {
echo "inserted";
}
Assuming the column type of update is varchar / charand date_posted is datetime:
$sql = sprintf("INSERT INTO posts(update,date_posted) VALUES('%s',NOW())",
mysql_real_escape_string($post));
$result = $db->query($sql);
Please change the column name "update" to anyother. it may works. And Avoid some predefined varibales for column names.
Hope it helps.

Categories