error in Loop Json from query in ajax - javascript

I am trying to retrieve information of BD with ajax.
The thing is when i receive the data from the script php, it send me a json file, but i cant print the values, this is my code.
JS:
$(document).ready(()=>{
$('table').on("click", "p", function(){
let value = $(this).attr('value')
if (value=='true') {
$(this).addClass('disabled')
let data = $(this).attr('data-value')
var info = {
"numSelection":data,
"sort": "97"
}
$.ajax({
data:info,
url:"js/service.php",
type:"post",
beforeSend:function(){
console.log("Estamos en proceso con ajax")// Here we are fine
}
}).done(function(data){
console.log(data)//this print the json file in console
correctly
$.each(data,function(i,item){//here is the error in console
console.log("Index: "+i)
console.log("Item: "+item)
})
})
}
});
});
in this step i receive this error un console:
Uncaught TypeError: Cannot use 'in' operator to search for '957' in + the content of the json file
and this is my php script with the sql
<?php
// var_dump();
// error_reporting(E_ERROR | E_WARNING | E_PARSE);
include('conn.php');
$sql = "SELECT * FROM participantes WHERE sorteos_id=".$_POST['sorteo'].";";
$result = mysqli_query($conn, $sql);
$resultado = mysqli_fetch_array($result);
$enviar = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$enviar[]=$row;
}
} else {
echo "0 results";
}
echo json_encode($enviar);
?>
If I do not send the information in json format, it is sent in an array but with an annoying message
Notice: Array to string conversion in C:\UwAmp\www\testing\js\service.php on line 19
Array
I am new coding so i accept any suggestion

Thank you so much guys for trying to help me with this. But they gave me many ideas, so i found my answer...
My mistake was, dont specify what format i am waiting, just have to add
dataType: "json in the config of $.ajax.
$.ajax({
data: info,
url: "js/service.php",
type: "post",
dataType: "json", //this to receive json
beforeSend: function() {
console.log("Estamos en proceso con ajax")
}
}).done(function(data) {
console.log(data)
$.each(data, function(i, item) {
console.log("Index: " + i)
console.log("Item: " + item)
})
})
php
$result = mysqli_query($conn, $sql);
$resultado = mysqli_fetch_array($result);
$enviar = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$enviar[]=$row;
}
} else {
echo "0 results";
}
echo json_encode($enviar);//this to send json

Related

Convert a Ajax Json String to a JS Object for my Ajax Get Script

I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.

php ajax jquery responseText not returned

I am trying to write an insert query with jquery, ajax and php. The record is getting inserted but returns a status error. First I tried to echo the message in php as it didn't work I tried it with print json_encode but both returned the status as error. Why doesn't it return the responseText?
{readyState: 0, responseText: "", status: 0, statusText: "error"}
This is the addmember.php file
<?php
require '../database.php';
function random_password( $length = 8 ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%^&*()_-=+;:,.?";
$password = substr( str_shuffle( $chars ), 0, $length );
return $password;
}
$password = random_password(8);
//$regno=$_POST['regNo'];
$adminno=$_POST['adminNo'];
$batch=$_POST['batchText'];
$type=$_POST["memberType"];
$initials=$_POST["initialName"];
$fullname=$_POST["fullName"];
$address=$_POST["address"];
$telephone=$_POST["contact"];
$email=$_POST["email"];
$nic=$_POST["nic"];
$dob=$_POST["birthDate"];
$priv=$_POST["memberType"];
$userid="";
$sql="select username from memberinfo where username='$adminno'";
$result=mysqli_query($con,$sql);
if(mysqli_num_rows($result)==0){
$sql="insert into memberinfo(username,nic_no,class,name_initial,full_name,address,telephone,email,date_of_birth) VALUES ('$adminno','$nic','$batch','$initials', '$fullname', '$address', '$telephone','$email','$dob')";
$result1=mysqli_query($con,$sql);
$sql = "select * from memberinfo where username='$adminno'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$userid = $row['user_id'];
}
}
$sql="insert into userlogin(user_id,username,privilege,password) VALUES ('$userid','$adminno','$priv','$password')";
$result2=mysqli_query($con,$sql);
if ($result1 && $result2) {
$message = "<p>New record created successfully</p>";
} else {
$message = "<p>Error: " . $sql . "<br>" . $con->error.".</p>";
}
} else{
$message = "<p>Admission no already exists.</p>";
}
print json_encode($message);
$con->close()
?>
This is the .js file with the ajax function
$(document).ready(function(){
$('#addmember').click(function(){
console.log("addmember");
var adminno=$("#adminNo").val();
var nic=$("#nic").val();
var batch=$("#batchText").val();
var initials=$("#initialName").val();
var fullname=$("#fullName").val();
var address=$("#address").val();
var telephone=$("#contact").val();
var email=$("#email").val();
var dob=$("#birthDate").val();
var priv=$("#memberType").val();
//$("#result").html("<img alt='ajax search' src='ajax-loader.gif'/>");
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
dataType: "json",
data:{'adminNo':adminno, 'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response);
},
error:function(response){
console.log(response);
}
});
});
});
Status zero normally means the page is navigating away. Stop it from happening.
$('#addmember').click(function(evt){ //<--add the evt
evt.preventDefault(); //cancel the click
You are not returning valid JSON from the server. You're json encoding a string, but valid JSON requires an object, or array to encapsulate the day coming back.
So at the very least:
echo json_encode(array($message));
No need for the JSON response. Simply return the message from your PHP script as shown below (note the use of echo and the semicolon following close()):
PHP
$con->close();
echo $message;
Also, remove the JSON filetype from your AJAX call and instead append response.responseText rather than response:
JS
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
data:{'adminNo':adminno,'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response.responseText);
},
error:function(response){
console.log(response);
}
});

Ajax Javascript Get JSON value

Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");

Error in $.ajax call

I have an $.ajax call in one of my pages that links to a simple php page.
I am getting my alert for the error: property. I am not getting anything back in the errorThrown variable or in the jqXHR variable. I have never done this kind of thing before and i am not seeing what is wrong with my page.
JQuery $.ajax call :
function jsonSync(json) {
$.ajax({
type: 'POST',
url: 'http://www.cubiclesandwashrooms.com/areaUpdate.php',
dataType: 'json',
data: json,
context: this,
success: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error has occured! \n ERR.INDEX: Sync failed, ' + jqXHR.responseText + ';' + textStatus + ';' + errorThrown.message);
return false;
}
});
And this is my PHP Page :
$JSON = file_get_contents('php://input');
$JSON_Data = json_decode($JSON);
//handle on specific item in JSON Object
$insc_area = $JSON_Data->{'insc_area'};
//mysqlite connection.open() equivilent
$insc_db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($insc_db)) {
die('Could not connect: ' . mysql_error());
echo "Failed to connect to MySql: " . mysqli_connect_error();
//mysqli_close($insc_db);
}
//$insc_area.length equivilent
$insc_area_size = sizeof($insc_area);
//cycle through reult set
for ($i = 0; $i < $insc_area_size; $i++) {
//assign row to DataRow Equivilent
$rec = $insc_area[$i];
//get specific column values
$area = $rec->{'area'};
$id = $rec->{'srecid'};
//sqlcommand equivilent
$query = "SELECT * FROM insc_products WHERE id='$id' LIMIT 1";
$result = mysqli_query($insc_db, $query);
$num = mysqli_num_rows($result);
//dataReader.Read equivilent
while ($row = $result->fetch_array()) {
$query = "UPDATE insc_products SET area='$area' where id = '$id'";
$res = mysqli_query($insc_db, $query);
//checking if update was successful
if ($res) {
// good
error_log('user update done');
echo 'update was successful';
} else {
error_log('user update failed');
echo 'error in update';
}
}
}
echo 'testing php';
dataType: 'json'
means: give me json back. your PHP file isn't returning json formatted data
similar question: jQuery ajax call returns empty error if the content is empty
to buid a json response fill an array in the php file with the return information and use echo json_encode($array); at the end of the file. if you are using dataType:'json' because the code is copy/pasted, and you won't need the response to be in json format, simply remove this option...
Add following line in php file, $JSON_Data encode then it will work.
echo json_encode($JSON_Data);

How to get my data back

I'm new to dynamic data and trying to
read data from a mysql database using PHP
turning this data to JSON
fetching the data through javascript (jQuery)
Inserting it into my page.
As far as I can see, 1) and 2) work fine, 3) seems to kind of work and 4) is where it breaks.
I've set up the database and the table, query & echo the data like so (api.php)
<?php
include 'db.php';
$con = new mysqli($host,$user,$pass,$databaseName);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM $tableName";
$myArray = array();
if ($result = $con->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$con->close();
?>
Now I get it through javascript...
jQuery(function($) {
$.ajax({
url: 'php/api.php',
data: "json",
dataType: "",
success: function(data) {
var r = new Array(), j = -1;
for (var key=0, size=data.length; key<size; key++){
r[++j] ="<tr><td>";
r[++j] = data[key][0];
r[++j] = "</td><td>";
r[++j] = data[key][1];
r[++j] = "</td><td>";
r[++j] = data[key][2];
r[++j] = "</td></tr>";
}
var joined = r.join('');
console.log(joined);
$('#maintable tbody').html(joined);
}
});
});
... and throw it in the tbody element of my table.
The result is absolutely not what I expected:
See http://i.imgur.com/hRNrmdC.jpg (sorry for the partly german interface)
The Answer to the GET request is valid JSON, at least in theory (checked by http://jsonlint.com/ ), but to me it seems the data is treated as a string and split into an array of chars (each char a "key" in data[]), therefore "data[key][1] returns nothing.
var json = JSON.stringify(eval("(" + data + ")"));
and continuing with json[key][0] didn't help...
Now I wonder why and especially, what went wrong and how its fixed.
You have mixed up the keys in your ajax call:
data: "json",
dataType: "",
Should be:
dataType: "json",
as you are not sending or using any data at all.

Categories

Resources