Display search result in another page - php

Here is my api code for search data by pin code:
function findPlace(){
$request = \Slim\Slim::getInstance()->request();
$pinCode = json_decode($request->getBody());
try {
if(1){
$vendorSearchData = '';
$db = getDB();
$sql = "SELECT vendor_name,logo,phone_no FROM vender_list WHERE post_code LIKE :post_code";
$stmt = $db->prepare($sql);
$stmt->bindParam("post_code", $pinCode, PDO::PARAM_STR);
$stmt->execute();
//echo "<pre>"; print_r($stmt); echo"</pre>";die;
$vendorSearchData = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
if($vendorSearchData)
echo '{"vendorSearchData": ' . json_encode($vendorSearchData) . '}';
else
echo '{"vendorSearchData": ""}';
} else{
echo '{"error":{"text":"No access"}}';
}
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Here is the file, where I call function to find data. If its true, then will navigate to another page, but on that page I get blank page:
findPlace(searchVal){
this.authService.postData(this.vendorSearchPostData, "findPlace")
.then((result) => {
this.responseData = result;
if (this.responseData.vendorSearchData) {
this.dataSet = this.responseData.vendorSearchData;
this.navCtrl.push(SearchResultPage, { data: searchVal});
} else {
let toast = this.toastCtrl.create({
message: "No data Found",
duration: 2000
});
toast.present();
}
}, (err) => {
});
}
How display the search result on another page?

Related

php ajax request don't give any response or error

I've been trying to grab a username based on registered email when user enters his email and click on a button I've provide two data to my ajax request first is [cf] which identify which portion of code should be processed and second is the email but when clicking the button nothing happens and no errors appear in the console only when I open the page that have the php code of ajax request it says "Notice: Undefined variable: funcCall in D:\XAMPP\htdocs\lahj\framework\signin.php on line 19"
Here I will provide my code for ajax:
$("#login-next-btn").click(function(){
if(!$("#signin-email").val().trim()){
var email = $("#signin-email").val().trim();
$.ajax({
url: "framework/signin.php",
type: "POST",
data: {cf:'cf1',email:email},
dataType:"json",
success: function(data){
if(data.result != "0")
{
alert("helo");
$("#signin-box-header p:first-of-type").text("مرحبًا");
$("#signin-box-header p:last-of-type").remove();
$("#signin-box-header").append("<p id='sigin-email-display'>"+data.result+"</p>");
$("#first-loader").fadeOut(600,function(){
$("#second-loader").css({"display":"flex"}).fadeIn(400);
});
}
else
{
alert("fail");
}
}
});
}
});
and here is my php code in a file called signin.php in a folder called framework:
<?php
ini_set( 'error_reporting', E_ALL );
ini_set( 'display_errors', true );
include_once 'db.php';
$email = null;
$funcCall = null;
if(isset($_POST['email']))
{
$email = $_POST['email'];
}
if(isset($_POST['cf']))
{
$funcCall = $_POST['cf'];
}
if($funcCall == 'cf1' && !empty($email))
{
try
{
$database = new db();
$db = $database->openConnection();
$stmt = $db->prepare("select userName from khUsers where email = ?");
$stmt->execute(array($email));
$usersName = $stmt->fetchColumn();
$data = array('result' => $usersName);
echo json_encode($data);
}
catch (PDOException $e)
{
echo "There is some problem in connection: " . $e->getMessage();
$data = array('result' => "0");
echo json_encode($data);
}
}
?>
Add exit() function at the end of json_encode() function. it will show you result/error on your request in console.
if($funcCall == 'cf1' && !empty($email))
{
try
{
$database = new db();
$db = $database->openConnection();
$stmt = $db->prepare("select userName from khUsers where email = ?");
$stmt->execute(array($email));
$usersName = $stmt->fetchColumn();
$data = array('result' => $usersName);
echo json_encode($data); exit();
}
catch (PDOException $e)
{
echo "There is some problem in connection: " . $e->getMessage();
$data = array('result' => "0");
echo json_encode($data); exit();
}
}

AJAX code seems to be ok, but it doesn't show anything

So I have a live chat, and when the user clicks the button, this function should kick into action and insert it into the database and into the HTML conversation section.
The first problem is that if i use dataType: "json" , then it enters the AJAX error case instead of success. But if I pull it out, like below, it enters the success case. But here comes the second problem: only the first alert is displayed, and if I try to alert the response, it doesn't show anything (+neither the alert('yes') is displayed).
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}
EDIT1:
It might be useful to understand my files:
I have index.php which contains the actual chat. When the send button is clicked, it accesses the chat.js file that contains the script above. Then, this is the part of chat_action.php that deals with it and passes it further to Chat.php.
chat_action.php
session_start();
include ('Chat.php');
$chat = new Chat();
if($_POST['action'] == 'insert_chat') {
$chat->insertChat($_POST['to_user_id'], $_SESSION['userid'], $_POST['chat_message']);
}
Chat.php
<?php
class Chat{
private $host = 'localhost';
private $user = 'root';
private $password = "";
private $database = "chat_demo";
private $chatTable = 'chat';
private $chatUsersTable = 'chat_users';
private $chatLoginDetailsTable = 'chat_login_details';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
public function insertChat($reciever_userid, $user_id, $chat_message) {
$sqlInsert = "
INSERT INTO ".$this->chatTable."
(reciever_userid, sender_userid, message, status)
VALUES ('".$reciever_userid."', '".$user_id."', '".$chat_message."', '1')";
$result = mysqli_query($this->dbConnect, $sqlInsert);
if(!$result){
return ('Error in query: '. mysqli_error($this->dbConnect));
} else {
$conversation = $this->getUserChat($user_id, $reciever_userid);
$data = array(
"conversation" => $conversation
);
echo json_encode($data);
}
}
public function getUserChat($from_user_id, $to_user_id) {
$fromUserAvatar = $this->getUserAvatar($from_user_id);
$toUserAvatar = $this->getUserAvatar($to_user_id);
$sqlQuery = "
SELECT * FROM ".$this->chatTable."
WHERE (sender_userid = '".$from_user_id."'
AND reciever_userid = '".$to_user_id."')
OR (sender_userid = '".$to_user_id."'
AND reciever_userid = '".$from_user_id."')
ORDER BY timestamp ASC";
$userChat = $this->getData($sqlQuery);
$conversation = '<ul>';
foreach($userChat as $chat){
$user_name = '';
if($chat["sender_userid"] == $from_user_id) {
$conversation .= '<li class="replies">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$fromUserAvatar.'" alt="" />';
} else {
$conversation .= '<li class="sent">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$toUserAvatar.'" alt="" />';
}
$conversation .= '<p>'.$chat["message"].'</p>';
$conversation .= '</li>';
}
$conversation .= '</ul>';
return $conversation;
}
private function getData($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error($this->dbConnect));
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getUserAvatar($userid){
$sqlQuery = "
SELECT avatar
FROM ".$this->chatUsersTable."
WHERE userid = '$userid'";
$userResult = $this->getData($sqlQuery);
$userAvatar = '';
foreach ($userResult as $user) {
$userAvatar = $user['avatar'];
}
return $userAvatar;
}
}
EDIT2:
From the console:
chat.js:106
index.php:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.success (chat.js:107)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
you try to parsing not valid json, in your js maybe try this:
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
try {
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
} catch(e) { alert(e) }
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}

Notification appears to be successful even if no data has been added to database

So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code?
add-college.php
<?php
function findDuplicate($code) {
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$sql = "SELECT * FROM colleges WHERE collegecode = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $code);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
return true;
}
else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$code = $_POST['code'];
$name = $_POST['name'];
$result = array();
if (findDuplicate($code)) {
$result['message'] = 'duplicate';
}
else {
$sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $code, $name);
if ($stmt->execute()) {
$result['message'] = 'success';
}
else {
$result['message'] = 'error';
}
}
echo json_encode($result);
}
catch (Exception $e) {
echo json_encode($result);
}
?>
script.js
$("#save-new").click(function() {
var form = $("#add-college");
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
type: "POST",
data: {
code: code,
name: name
},
url: "../ajax/add-college.php",
dataType: "html",
success: function(data) {
if (data.message = "success") {
$.notify({
// options
message: 'College has been added.'
},{
// settings
type: 'success'
});
}
else if (data.message = "duplicate") {
$.notify({
// options
message: 'College already exists.'
},{
// settings
type: 'warning'
});
}
else {
$.notify({
// options
message: 'College cannot be added.'
},{
// settings
type: 'error'
});
}
$("#code").val("");
$("#name").val("");
$("#add-new").modal('hide');
showColleges();
}
});
});
data.message = "success" this is assignment operation, if you want to compare two string use == operator.
So, the correct statement would be for the if condition would be if(data.message == "success")
Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!

Error trying to search a video AJAX

I have created a code that allows you to search videos from the database. But everytime I write the video I want to search, in console, error appears... I really dont know why it doesnt print the result...
Could you help me?
I need help real fast
AJAX
$(document).ready(function($) {
var Search = function(title){ return $.post( "./include/php/busqueda_videos.php", { "title" : title }); }
$("#input_search").on('keyup', function(event) {
var output = "";
$(".videos_container").html("");
event.preventDefault();
var input = $("#input_search").val();
Search(input).done(function(response) {
if(response.success) {
$.each(response.videos, function(key, value) { var output = "<div class='video_main_container'><div class='video_container'><div class='video_thumb'><a data-id='"+value['id']+"'><img src='"+value['image']+"' alt='' /></a></div><div class='video_info'><p class='title'>"+value['title']+"</p><p class='usuario'>"+value['user']+"</p></div></div></div>"; });
$(".videos_container").html(output);
} else {
console.log("Error");
}
}).fail(function(jqXHR, textStatus, errorThrown) { console.log("Hubo un error"); });
});
});
PHP
<?php
if(isset($_POST['title'])) {
get_infvideo($_POST['title']);
} else {
$message = sprintf("No valid");
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $message, true, 403);
}
function get_infvideo($title) {
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseña = "";
$conexion = new PDO($dsn, $usuario, $contraseña);
$resultado = null;
$jsondata = array();
$videos = array();
$text ="";
if($title!="") {
$title= explode(" ", $title);
for($i=0; $i<count($title);$i++) {
if($text!="") {
$text .= " AND (title LIKE '%".$title[$i]."%' or user LIKE '%".$title[$i]."%')";
} else {
$text .= " (titulo LIKE '%".$titulo[$i]."%' or user LIKE '%".$title[$i]."%')";
}
}
}
if($conexion){
$sql = "SELECT * FROM video WHERE ".$text;
if($resultado = $conexion->query($sql)) {
while($fila = $resultado->fetch()) {
$fila['id'] = $fila['id'];
$fila['user'] = $fila['user'];
$fila['image'] = $fila['image'];
$jsondata['success'] = true;
array_push($videos, $fila);
$jsondata['videos'] = $videos;
}
} else {
$jsondata['success'] = false;
$jsondata['message'] = $sql;
}
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata, JSON_FORCE_OBJECT);
}
exit();
?>
The idea is to print the video (with his id, image, user, title) that you have searched...

Unable to pass variable value to ajax from php

My ajax:
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//$(".the-return").html("<br />JSON: " + data["json"] );
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
alert(data);
// window.location='success.php'
}
});
return false;
});
});
I declared a variable to store unique_id like this:
$unique_id=uniqid();
I'm inserting data like this:
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
echo $stmt2->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Now, I want to pass the above unique_id to ajax page but couldn't.
echo $unique_id;
It just doesn't alert anyting, but:
$abc="123";
echo $abc;
this shows the alert box with value 123!
Why is it so? WHy I coudn't pass unique_id value like this?
MY ENTIRE PHP SCRIPT:
<?php
//Function to check if the request is an AJAX request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$return = $_POST;
$return["json"] = json_encode($return);
//below code to store in database
$data = json_decode($return["json"], true);
/*....salting starts........*/
/*..........salting ends..............*/
echo $unique_id=uniqid();
$name=$data['name'];
$phone=$data['phone'];
$email=$data['email'];
$postcode=$data['postcode'];
$a=$data['sub'];
$b=$data['rate2'];
$subject_rate = array_intersect_key($b,$a);
/*...pdo.............................*/
$username="root";
$password="";
try {
//$pdo = new PDO('mysql:host=localhost;dbname=users', $username, $password);
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$stmt = $pdo->prepare('INSERT INTO authsessions (email,useruuid,salt,hashpword) VALUES(:email,:useruuid,:salt,:hash)');
$stmt->execute(array(
':email' => $email,
':useruuid'=>$unique_id,
':salt'=>$salt,
':hash'=>$hash
));
# Affected Rows?
$stmt->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query2
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
$stmt2->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query3
try
{
$stmt3 = $pdo->prepare('INSERT INTO tutoravailability (uuid,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening) VALUES(:uuid,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening)');
$stmt3->execute(array(
':uuid' => $unique_id,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening
));
# Affected Rows?
$stmt3->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query4
foreach($subject_rate as $v=>$k)
{
$key=$v;
$value=$k;
$post_unique_id= uniqid();
try
{
$stmt4 = $pdo->prepare('INSERT INTO posts (PostUUID,subid,date,pricing,post_status,UUID,Name,Phone,Email,Poscode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening,Status) VALUES(:PostUUID,:subid,now(),:pricing,:post_status,:UUID,:Name,:Phone,:Email,:Poscode,now(),:Reputation,:ReviewPlus,:ReviewNeg,:Sex,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening,:Status)');
$stmt4->execute(array(
':PostUUID' => $post_unique_id,
':subid'=>$key,
':pricing'=>$value,
':post_status'=>1,
':UUID'=>$unique_id,
':Name'=>$name,
':Phone'=>$phone,
':Email' =>$email,
':Poscode'=>$postcode,
':Reputation'=>78,
':ReviewPlus'=>65,
':ReviewNeg'=>3,
':Sex'=>$gender,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening,
':Status'=>0
));
# Affected Rows?
$stmt4->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
}
/*try
{
$sql = "SELECT *FROM authsessions WHERE useruuid =:uid";
$statement = $pdo->prepare($sql);
$statement->bindValue(':uid', $unique_id);
$statement->execute();
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array("id" => $row['useruuid']));}
header('Content-Type: application/json');
echo json_encode($json);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}*/
// $unique_id=uniqid();
}
?>
You need to use json_encode because the AJAX call says dataType: "json".
echo json_encode($unique_id);
It worked when you echoed 123 because a decimal number is valid JSON. But uniqid returns a hex string, and this isn't valid JSON. You need to encode it with quotes around it.

Categories