I am making reservation website using fullcalendar. I insert event into my DB using Ajax. However, the problem is that success function was not working, but every data was successfully inserted into DB. Also I changed success to error, but still nothing happened.
Here is code where I insert event into DB
select: function(start, end, allDay)
{
var teacher = prompt("Enter ResourceID");
if(teacher)
{
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$.ajax({
url:"http://show981111.cafe24.com/login-system/addevent.php",
type:"POST",
data:{userName: '<?php echo $name; ?>' , newlyBookedDate:start, courseTeacher : teacher, userBranch:'<?php echo $userBranch; ?>', userID: '<?php echo $userID; ?>'},
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Added Successfully");
}
})
}
},
Here is where I get the php variables that I use above
<?php
session_start();
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$name = $_SESSION['userName'];
$userBranch = $_SESSION['userBranch'];
$userID = $_SESSION['userID'];
}
?>
This is code for addevent.php
<?php
// Values received via ajax
$userName = $_POST['userName'];
$newlyBookedDate = $_POST['newlyBookedDate'];
$courseTeacher = $_POST['courseTeacher'];
$userBranch = $_POST['userBranch'];
$userID = $_POST['userID'];
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=show981111', 'show981111', 'pass');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// insert the records
$sql = "INSERT INTO DAYSCHEDULE (newlyBookedDate, userID, userName, courseTeacher,userBranch ) VALUES (:newlyBookedDate, :userID, :userName, :courseTeacher, :userBranch)";
$q = $bdd->prepare($sql);
$q->execute(array(':newlyBookedDate'=>$newlyBookedDate, ':userID'=>$userID, ':userName'=>$userName, ':courseTeacher'=>$courseTeacher,':userBranch'=>$userBranch ));
?>
if your data inserted into DB then take the response from your controller/W to the success function parameter and see the log.
$.ajax({
url:"http://show981111.cafe24.com/login-system/addevent.php",
type:"POST",
data:{userName: '<?php echo $name; ?>' , newlyBookedDate:start, courseTeacher : teacher, userBranch:'<?php echo $userBranch; ?>', userID: '<?php echo $userID; ?>'},
success:function(response)
{
console.log(response);
calendar.fullCalendar('refetchEvents');
alert("Added Successfully");
}
});
if you are getting no error then in the success function should be
success:function(response)
{
console.log(response);
//calendar.fullCalendar('refetchEvents');
//if calendar is used as an id then
$("#calendar").fullCalendar('refetchEvents');
//or it is a class then
$(".calendar").fullCalendar('refetchEvents');
alert("Added Successfully");
}
Related
I am trying to refresh my a page if there is a change in orderStatus from database using Ajax and PHP. I set the current orderStatus as predefined data and then use Ajax to get the current orderStatus from database and finally compare if they are not the same. I want to refresh the page if they are not the same.
PHP (autorefresh.php)
<?php
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
Javascript
<script type="text/javascript" >
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"autorefresh.php", //put relative url here, script which will return php
data:{orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
window.location.href=window.location.href;
}
}
});
},5000);// function will run every 5 seconds
}));
The below code should work, Need to mention dataType:"json" else use JSON.stringify(data) to parse response
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
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
I am in need to send an ajax call to a function in following directory structure
Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile";
my view function
function uploadImage(){
var url = '<?php echo Yii::app()->request->baseUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; ?>';
console.log(url);
return false;
$.ajax({
url:'<?php echo Yii::$app->createUrl("Post/UploadMusicFile"); ?>',
method:'post',
data:{file:$('input[type="file"]')},
dataType:'',
contentType:false,
processData:false,
success:function(data){
var parsed_data = $.parseJSON(data);
},
error:function(data){
console.log("Error "+data);
}
});
}
function which i am posting to
public function UploadMusicFile(){
$file = Yii::$app->request->post('file');
echo "<pre>";
print_r($file);
echo "</pre>";
exit();
$target_dir = "/home/jmwglobaladmin/public_html/melmory/uploads/music_memory/";
$target_file = $target_dir . basename($_FILES["files"]["name"][0]);
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["files"]["tmp_name"][$key];
move_uploaded_file($tmp_name, $target_file);
$connection = Yii::$app->getDb();
$command = $connection->createCommand('select id from post order by id desc limit 1');
$result = $command->queryAll();
$new_id = $result[0]['id']+1;
$file_name = "abc.mp3";
$connection = Yii::$app->getDb();
$command_insert = $connection->createCommand('insert into memory_music (post_id,memory_music) values ("'.$new_id.'","'.$file_name.'")');
$result = $command_insert->execute();
}
}
}
I get the error of 404. How to pass proper url in yii to a function which is present in directory structure like mentioned above?
Basics. Your function is not an action.
Change this:
public function UploadMusicFile()
To this:
public function actionUploadMusicFile()
im not so sure how this works, but where does my success(data) value come from?
must I return a value in url: php/login.php?
$.ajax({
url: 'php/login.php', //must i return a value in login.php?
data: {username:username,password:password},
type: "POST",
dataType: 'json',
success: function(data)
{
if(data == true){
console.log("sdfsdfs " + data);
login.submit();
}
else{
console.log("NO DATA PRESENT");
}
}
//else do an alert("please lgo in again");
});
in php/login.php i query the DB to see if such a user exists and if password match
part of my login.php
<?php
echo $username = $_POST['username']; //not echo-ing
echo $password = $_POST['password'];
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember'];
if ($username&&$password) //check if the field username and password have values
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$connect=mysqli_connect($dbhost,$dbuser,$dbpass) or die("Unable to Connect");
mysqli_select_db($connect,"clients") or die("Could not open the db");
$sql = "SELECT * FROM clients.users WHERE username='$username'";
$login = mysqli_query($connect, $sql);
if (mysqli_num_rows($login))
{
while ($row = mysqli_fetch_assoc($login))
{
$db_password = $row['password'];
if ($password==$db_password)
{
$loginok = TRUE;
echo json_encode( true );
} else {
echo json_encode( false );
echo "Please re-enter username and password, they did not match";
header("Location: ../login.php");
}
?>
When you want to return some data using ajax, you need to echo data in your script that will be called by ajax. If the request is successful, it will return everything you echoed in your script into your parameter you specified in success function.
success: function(data)
{
// code...
}
so "data" will contain result from your script, then you can do whatever you want.
EDIT:
Well, i would solve it like this
$db_password = $row['password'];
if ($password==$db_password)
{
echo json_encode(array("status" => "ok", "message" => "Login successful!"));
} else {
echo json_encode(array("status" => "error", "message" => "Please re-enter username and password, they did not match!"));
//header("Location: ../login.php"); you don't need this
}
you can't echo json, then some text after it. You can, but it is not recommended at all.
I have a JQuery on click that sends a php query to MySql and then I want to send the data back 1 by 1 on JQuery.
But I only know how to send back results from php to JQuery as a whole.
my current JQuery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
alert(data);
}
});
});
});
my current php:
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['UserID'];;
echo $row['EmailAddr'];
}
?>
the outputs are both UserID and EmailAddr, I don't know how to just display either the UserID or EmailAddr out only
I tried alert(data[0]), but it only displayed one letter of the result.. Any ideas on how to do this?
UPDATE: After sean's help i have the current updated code
Jquery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
PHP
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
In your php, save the results to an array -
<?php
include 'dbAuthen.php';
$array = array(); // create a blank array
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// add each result to the array
$array[] = array('UserID'=> $row['UserID'], 'EmailAddr'=> $row['EmailAddr']);
}
echo json_encode($array); // json_encode() the array
?>
Then in your js/ajax you can loop through each value
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
// loop through each returned value
$.each(data, function(){
//alert each result, this is just an example as alert() for each result is not a great idea
alert("UserID:"+ this.UserID + " EmailAddr:" + this.EmailAddr);
});
}
});
});
});
jquery
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
php
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>