How to use AJAX to call php file from javascript file - javascript

I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?

$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct

Related

Do not display data output in ajax

I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it

AJAX call returning json array undefined

I've seen that there has been a lot of questions about this but I did not find any specifics that could apply to my case so if I'm creating a duplicate, sorry for that.
I am trying to retrieve data from SQL database with php file that passes the data to ajax call. Everything seems to be working fine, just when I try to output data into console I get "undefined" variable, even when I tried accessing a precise part of the array with data.story for example. I have also tried data[0].story but that gave me an error that 'story' field of undefined cannot be accessed.
The code is below:
Thanks for your help guys.
my php file:
<?php
$con = mysqli_connect('localhost','root','password','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$array = array();
$sqlFetch = "SELECT s.storyTitle, s.story, s.lattitude, s.longitude,
u.nickname, u.platformUsed, u.sexuality, u.gender, u.age, s.category,
s.dateRecorded FROM stories AS s INNER JOIN users AS u ON u.email = s.email
WHERE s.postStatus != 'published'";
$result = mysqli_query($con,$sqlFetch);
if(!is_null($result->num_rows)){
$encode = array();
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
}
?>
and ajax code:
$.ajax({
type: 'post',
url: "http://localhost/wordpress/wp-content/themes/TinDA/js/loadData.php",
dataType: 'json',
data: "",
}).done(function(data){
console.log(data);
//tried also: console.log(data.story); and data[0].story;
});
It seems that you are mixing the mysqli connection for
Procedural Style with Object Oriented Style
Procedural:
$con = mysqli_connect('localhost','root','password','db');
$result = mysqli_query($con, "SOME SELECT STATEMENT");
while ($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
$rows = mysqli_num_rows($result);
if($rows){
json_encode(array('data' => $data, 'msg'=> 'successs'));
} else {
json_encode(array('data' => $data, 'msg'=> 'error or no records...'));
}
OOP:
$con = new mysqli('localhost','root','password','db');
if($con->connect_errno){
echo "WTF didn't work!!" . $con->connect_error;
}
$res = $con->query('SOME SELECT STMNT');
while ($row = $res->fetch_assoc()){
$data[] = $row;
}
$rows = $con->num_rows;
if($rows){
json_encode(array('data' => $data, 'msg'=> 'successs'));
}else {
json_encode(array('data' => $data, 'msg'=> 'error or no records...'));
}
I also like to use this version of ajax (different with 3.0 may not work).
You can then see the data errors. Note, you can have a successful ajax call and return but still have an error.
$.ajax( '/http://localhost/...', {
type: 'POST',
dataType: 'json',
success: function( json ) {
console.log( json );
},
error: function( req, status, err ) {
console.log( 'WTF!!', status, err );
}
});

How to pass multiple variables from a php file to ajax and use them?

I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console

How can I return an array object to a jquery $.ajax call?

I am trying to return an array object to my Jquery ajax call, but it seems to return as a String with Array length =1
PHP code:
$results = mysqli_query($link, $sql);
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$array = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ;
echo json_encode($array) ;
}
} else {
echo "0 results";
}
Response in Developer tools shows:
["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]
My Ajax Call:
function trend(data){
$.ajax({
url: "trendData.php",
cache: true,
type: "POST",
data: {arr:data},
success: function (data) {
originalData=[];
originalData.push(data)
trender(data)
}
});
}
In the Preview window for Network, it shows an Array:
I cannot get an array of , in this example, 3 objects and get the array.length of 3
Any help will be much appreciated.
You should collect all your data and return it as one json result and add a correct http-header (suggested by #Flosculus) so that the json format will be recognized:
$results = mysqli_query($link, $sql);
$data = array();
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$data[] = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ;
}
header('Content-Type: application/json');
echo json_encode($data) ;
} else {
echo "0 results";
}
I think you have to use JSON.parse(), if you're using jquery so your js script will look like
$.ajax({
url: "trendData.php",
cache: true,
type: "POST",
data: {arr:data},
success: function (data) {
var data = JSON.parse(data);
//see length of array
console.log(data.length);
}
});

Pass a variabile from php to js via JSON

At the lessons i learn how to pass result from a sql request to js via JSON/AJAX. I need the value of the row from this request in my js but it doesnt work. Via console i have an error: Uncaught SyntaxError: Unexpected token <
part of PHP:
<?php
//get all the course from db and reply using json structure
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_hyp");
$id = $_POST['id'];
if (mysqli_connect_errno()) { //verify connection
exit(); //do nothing else
}
else {
# extract results mysqli_result::fetch_array
$query = " SELECT * FROM course WHERE course_category='$id'";
//query execution
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
$myArray = array();//create an array
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = array_map('utf8_encode', $row);
}
$response = array();
$response['rows'] = $row;
$response['query'] = $myArray;
echo json_encode($response);
}
//free result
$a=num_rows;
$result,$a->close();
//close connection
$mysqli->close();
}
?>
first part of Script:
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "./query/cate_has_courses.php", //Relative or absolute path to file.php file
data: {id: i},
success: function(response) {
console.log(JSON.parse(response));
var course=JSON.parse(response.query);
var row=JSON.parse(response.rows);
Seem you use JSON.parse in wrong way.
The JSON.parse must be done one time only. The result of JSON.parse is store in course the the access to the data is due by response.query or respons.row .. and so on and not by JSON.parse(respose.query)

Categories