Showing data and posted values separately in ajax post - javascript

i have a task which is about ajax post data and also ask the script to show data...I have 3 files.. HTML file perform an ajax to the php script, passwrapper.php and then include the another script to show all data in the json format on the console.log in the html file.. I implemented some ajax post values such as 'Abdullahlahlahlah' and 'Muslim' so that the passwrapper.php will receive those data and echo on the console separatley from the whole data... Developer said ajax cannot echo 2 times...... Is it totally impossible???? If there is no way, please tell me other options...
Requirement: Please do not modify the student.php as i want the that php script to echo all the data in json..
Modify the paswrapper.php and html file..
When i run the html file, the error states
Status Code: 200
ErrorThrown: SyntaxError: Unexpected token < in JSON at position 1634
jqXHR.responseText:
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]
Also there is the posted values on the console.log which states LastRowname = Abdullahlahlahlah LastRowReligion = Muslim
HTML File
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="results"</div>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullahlahlahlah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'");</script>';
}
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
in my network tab
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]<script>console.log("LastRowname = Abdullahlahlahlah LastRowReligion = Muslim");</script>
my requirement:
i want to echo all the data(except the posted values) on the html file.
i want to show the posted values on the console.log. it can either be in the passwrapper.php or html file..... Please help me....

ajax cannot echo 2 times;
1.student.php
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
//echo json_encode($json_array);
return $json_array;
2.passwrapper.php
<?php
include 'student.php';
$data['student_arr']=executePass();
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>
3.html file
success: function(data){
console.log(data.post_str);
$('#results').text(JSON.stringify(data.student_arr));
},

passwapper.php
<?php
include 'student.php';
ob_start();
executePass();
$string = ob_get_contents();
ob_end_clean();
$data['student_arr']=json_decode($string);
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>

Related

Query result in the error response in the JQuery function

I have a problem, clicking in a < tr > of a table I call a javascript function which in turn calls a function in php to get data in a database. The click on the table row works, sql works, and from the console.log command I know there is an answer in reponseText. but it does not work and I get the error back, I'll post the code. I hope you can help me.
file config.php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
file cards.php
<?php
class card
{
private $_db;
function __construct($db){
$this->_db = $db;
}
public function view_card_id($id)
{
$rows = array();
$statement = $this->_db->prepare('SELECT * FROM card_details WHERE card_id = :card_id');
$statement->execute(array(':card_id' => $id));
$numrows = $statement->fetch(PDO::FETCH_ASSOC);
if($numrows < 1) {
$this->error = "Error";
return false;
} else {
$statement->bindColumn("card_id", $cid);
$statement->bindColumn("a", $a);
$statement->bindColumn("b", $b);
$rows[] = array('card_id' => $numrows['card_id'], 'a' => $numrows['a'], 'b' => $numrows['b']);
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$row = array('card_id' => $cid, 'a' => $a, 'b' => $b);
$rows[] = $row;
}
return $rows;
}
}
file index.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
?>
html code ....
<script src="/js/Cards.js" type="text/javascript"></script>
file Cards.js
$('#table-cards tr').click(function() {
var id = $(this).find("a").text();
$.ajax({
type: 'POST',
url: '/classes/cardsFunc.php',
dataType:'text',
data: {functionname: "view_card", id: id },
success: function(response){
//Use response
alert("Server echo: "+response);
console.log(response);
},
error: function(msg){
console.log(msg);
alert("Error: "+msg);
}
});
});
In the Cards.js file, once the $ .ajax function is called, it does not return to success but to error, but in the console.log I see the array of the executed query under the responseText entry.
that is, in the error response, I see the result of the query, which in theory should be in the response of success.
I also tried to use
$.post('/classes/cardsFunc.php', { functionname: 'view_card', id: id }, function(data){
});
but nothing
file cardsFunc.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
thank you for the time you have dedicated to me
I noticed that if I recreate the connection to the db in the file cardsFunc.php, everything works, but I do not understand why, since everything is in the config.php file.
Like this:
file cardsFunc.php
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>

Using extra php files to get the ajax post request and then load the php script

i have a task which is very complicated for me and also explain to you.. I will give my summary on what i m supposed to do.. there are 3 files which are the
1.html file which perform ajax post to the passwrapper.php
2. passwrapper.php will receive the ajax post request and include another file which is 3.student.php which contain codes on how to perform connection to the database and convert all data to json and then show all the data..
I was asked to perform ajax post multiple items.. In other words, i was asked to receive name and religion from the last row of database.. here is my code below...
html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: true,
lastReligion: true,
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
executePass();
}
else
{
//how to get name and religion from the last row and then perform executepass() to show all data and also data from the last row
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
my question is how to get last data from the last row which are student_name and student_religion in the passwrapper.php and also perform executepass() to show all data... please do not modify the sql code. i also do not want get data from the success. for example: data[count(data)-1]['student_name']...
my question is how to get the last values which are student_name and student_religion in the passwrapper.php... and also perform the executepass() function to show all data.. please help me... you can write the last data to the files or show in the html console..
Best would be to change executePass() so it ends with return $json_array; instead of echoing it. Then passwrapper.php could do:
$students = executePass();
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
echo json_encode($students);
}
else {
file_put_contents("all_students.json", json_encode($students);
$last_student = end($students);
echo json_encode(array($last_student));
}
And other scripts that want to return all the students can do:
$students = executePass();
echo json_encode($students);
If you can't do that, use the output buffering functions to capture the output from executePass() instead of sending it to the client.
else {
ob_start();
executePass();
$json = ob_end_clean();
file_put_contents("all_students.json", $json);
$students = json_decode($json, true);
$last_student = end($users);
echo json_encode(array($last_student));
}

data not passed between pages in live server

I came across weird problem with my site only after uploaded it to the live server. In localhost I've no issue with these.
The problem is for login and register function. Let me talk about login first.
I keyed in the credentials and found that the page is called in the f12 network tab.However that page doesn't retrieve any data! So I put aside this jquery/ajax for a while and manually checked the php pages if they return any data but still they don't.
Now the flow like this:
login form filled up by user-> ajax request from php script-> php request from class file and return to ajax -> ajax give access to admin dashboard.
Now as I told you, I excluded ajax request and only checked with php and class file. Again it doesn't return anything from the class file to the php script though I only echoed "something"! Its not even go through any function!
Then I omitted, class file, checked the php script with ajax file.I only echo "wexckdsewndxw" and changed tha datatype in ajax to 'text'..still it doesn't get any value!
So in conclusion, data between pages are not passed at all! SO I suspect its something to do with crossDomain issue as mentioned here:
How does Access-Control-Allow-Origin header work?
But not sure how this works and how I should alter my code.
My code for reference:
login-user.js
/*login user*/
<!--login form submission starts-->
$("document").ready(function(){
$("#login-user").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "login-this-user.php",
data: data,
success: function(data) {
alert(data);
console.log(data);
var i;
for (i = 0; i < data.length; i++)
{
console.log(data[i].email);
console.log(data[i].activate);
console.log(data[i].status);
if($.trim(data[i].status)=='0')
{
//alert("not verified");
$('.invalid-popup-link').trigger('click');
}else
{
//alert("verified");
location.replace("admin/dashboard.php");
}
}//end for
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
return false;
});
});
<!--login form submission ends-->
login-this-user.php
<?php
session_start();
include('config.php');
include('class.login.php');
$return = $_POST;
//$return ='{"email":"admin#gmail.com","pass":"admin","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$status = $login->checkLogin2($data["email"],$data["pass"]);
$_SESSION['user_id']=$status;
$login = new checkLogin();
$profile = $login->check_profile($data["email"]);
$activated_id=array();
foreach($profile as $k=>$v){
array_push($activated_id,array("email"=>$v['email'],"activate"=>$v['activate'],"status"=>'0'));
$_SESSION['email'] = $v['email'];
$_SESSION['activated_id'] = $v['activate'];
}
//header('Content-Type: application/json');
echo json_encode($activated_id);
?>
class
<?php
session_start();
?>
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin2($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT * FROM authsessions WHERE email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
$salt=$row['salt'];
$hashAndSalt=$row['hashpword'];
$user_id=$row['UUID'];
}
if (password_verify($this->password, $hashAndSalt)==true) {
$status = "verified";
$_SESSION['user_id'] =$user_id;
$_SESSION['logged_in']=1;
}else
{
$status = "not verified";
$_SESSION['user_id'] =0;
$_SESSION['logged_in']=0;
}
return $_SESSION['user_id'] = 1;
}
public function check_profile($param)
{
$this->email = $param;
$sql="SELECT * FROM authsessions WHERE email = '{$this->email}'";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$profile=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$profile[] = $row;
}
return $profile;
}
}
?>

updating MYSQL table gives success msg, but does'nt update the table

the AJAX msg gives successful, but the data doesn't update in DB, can you help plz!
html code:
<div class="row">
<input type="text" ng-model="updateId" class="form-control" placeholder="user Id To Update Phone">
<input type="text" ng-model="updatePhone" class="form-control" placeholder="user New Phone">
</div>
<div class="col-xs-3">
</div>
<div class="col-xs-2">
<button ng-click="updateuser()" type="button" class="btn btn-primary">Update </button>
</div>
</div>
javascript code:
$scope.updateuser = function () {
var data = {
updateId: $scope.updateId,
updatePhone: $scope.updatePhone
};
$.ajax({
data: data,
type: "post",
url: "update.php",
success: function(data){
alert("Data Updated");
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'Unauthorized') {
alert('custom message. Error: ' + errorThrown);
} else {
alert('custom message. Error: ' + errorThrown);
}
}
});
};
update.php code:
<?php
header('Content-Type: application/json');
include 'connect.php';
$db = new database();
$db->setDb_name('training');
$db->connect();
if(isset($_POST)){
$id = $_POST['updateId'];
$phone = $_POST['updatePhone'];
$data = $db->update('user',array('phone'=>$phone),array('id',$id));
echo json_encode($data);
}
mysql_close();
?>
the update() function:
public function update($table,$rows,$where)
{
for($i = 0; $i < count($where); $i++)
{
if($i%2 != 0)
{
if(is_string($where[$i]))
{
if(($i+1) != null)
$where[$i] = '"'.$where[$i].'" AND ';
else
$where[$i] = '"'.$where[$i].'"';
}
}
}
$where = implode('=',$where);
$update = 'UPDATE '.$table.' SET ';
$keys = array_keys($rows);
for($i = 0; $i < count($rows); $i++)
{
if(is_string($rows[$keys[$i]]))
{
$update .= $keys[$i].'="'.$rows[$keys[$i]].'"';
}
else
{
$update .= $keys[$i].'='.$rows[$keys[$i]];
}
// Parse to add commas
if($i != count($rows)-1)
{
$update .= ',';
}
}
$update .= ' WHERE '.$where;
$query = #mysql_query($update);
}
}
I am using angularJS, and when trying to run updating in update.php it works correctly, but using AJAX it gives "Data Updated" msg but actually doesnt update table.. why?
First of all, the ajax success callback from (I'm assuming) jQuery just means the HTTP request succeeded. This means it got a 200 response code. With most minor and some major errors in PHP the request will still be successful. If you want to know what went wrong, enable error reporting in PHP and be sure the errors are displayed:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Now, you should be able to see any errors. Use something like Chrome's developer console to see what error happened in your PHP code. Another option would be to log the error in PHP and check the error log after the request.

how to ajax Get result in a php file from another php file echo [duplicate]

This question already has an answer here:
how to show long poll result with php echo
(1 answer)
Closed 8 years ago.
I am using a long polling script, where I want show result into user.php page "#updatapost" div which get result from update.php page echo'' with Ajax,
Please see my code for clear about my problem
Here, If I used any text as below for test purpose, Its work well
success: function(data){
$("#updatetime").append("Test working");
But I want to append here my update.php page echo' ';
my script used at user.php page
function waitForMsg(){
$.ajax({
type: "GET",
url: "update.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
/* Here above I want to append update.php page echo */
$("#updatepost").append(data.responseText);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
}
$(document).ready(function () {
waitForMsg();
});
My user.php page where result want to show
<div id="updatepost"> result will goes here from update.php page echo''; </div>
My update.php page
$u = mysqli_query($dbh,"SELECT * FROM updateside WHERE `parent_id`='".$parent."' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
while ($row = mysqli_fetch_array($u)) {
$from_id = $row['from_id'];
$parent_id = $row['parent_id'];
$to_id = $row['to_id'];
$sub = $row['sub'];
$detail = $row['detail'];
echo '<div class="upbox" id="'.$parent_id.'">
// All result of above query
</div>';
}
If you want to append data from server you must return current result. In your example you return text but in js you try apped this text- that is your problem. This is a example:
user.php
$u = mysqli_query($dbh,"SELECT * FROM updateside WHERE `parent_id`='".$parent."' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
while ($row = mysqli_fetch_array($u)) {
$result['from_id'] = $row['from_id'];
$result['parent_id'] = $row['parent_id'];
......
....
header('Content-Type: application/json');
echo json_encode($result);
exit;
}
and your success method
success: function(data){
if(data) {
//create your html structs as you access data : data.from_id or data.parent_id
}
},

Categories

Resources