I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js
Related
Alright so here's the situation. I have the following code block in my php file, and for some reason, whenever it comes to check data, it doesn't accept. I've printed out the value of data, and it is indeed "accepted" (without quotes obviously). Am I comparing these wrong somehow? Running basically the exact same code in another section of my website and it works fine.
$(document).ready(function () {
$("#sign").click(function () {
jQuery.ajax({
url: "loginConfirm.php",
data: { // Correct
username: $("#username").val(),
password: $("#password").val()
},
type: "POST",
success: function (data) {
if ($("#username").val() === "") {
//Do nothin
} else if (data === "accepted") {
alert("Here");
redirectSignIn();
} else {
alert("There");
$("#signInTitle").html(data);
}
},
error: function () {}
});
});
});
EDIT: php code I'm calling in the url below
<?php
// The global $_POST variable allows you to access the data sent with the POST method
// To access the data sent with the GET method, you can use $_GET
$username = htmlspecialchars($_POST['username']);
$userpassword = htmlspecialchars($_POST['password']);
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("SELECT count(*) FROM loginInfo WHERE userName='" . $username . "' AND password='" . $userpassword . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0)
echo "accepted";
else
echo "denied";
?>
You cant validate if ($("#username").val() === "") { in success function. For that you are suppose to validate it before making Ajax call.
I would like to give some advice here that first you have to validate the inputs of the user if validate then you can call ajax.
and then you not required to check the value of the username in AJAX process.
Like....
if($("#username").val() === "" && $("#passoword").val() === "")
{
//AJAX call
}
else
{
//alert to enter the valid inputs
}
hope you get it my concept...
I need to get a value inside a div content. After a button click and doing stuff on the server side, my PHP function does:
echo "0";
or
echo "1";
depending on what my function does. So let's say if it's 0, the AJAX response will be $("div#divResult").html(data); where I put the 0 in the div divResult.
What I am trying to do now is I want to execute a js function to read whether it's 0 or 1 in divResult.
This is how I execute it:
<div id="divResult"><script>getDivResult();</script></div>
And my js function:
function getDivResult()
{
var result = $("div#divResult").text();
if(result === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(result === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
}
Somehow the getDivResult function is not executing. The 0 and 1 does display on in the div though. Any help on this? I've tried .html too by the way.
EDIT:
Here's the AJAX that I use for the button click and return the response from PHP which is either 1 or 0:
$.post(page, {
name : name,
badge_number : badge_number,
category : category,
priviledge : priviledge,
action : "insert"
}, function(data) {
$("div#divResult").html(data);
});
2nd EDIT:
function insertRow($name, $badge_number, $priviledge, $category)
{
$table_info = "TBL_USER_LOGIN";
$query_string = "select badge_number from $table_info where badge_number = $badge_number";
$result = #mysql_query($query_string) or die (mysql_error());
$checkBadge = mysql_num_rows($result);
if($checkBadge>0)
{
//echo "Badge Number $badge_number already exists. Please check again.";
echo "0";
}
else
{
$query_string = "insert into $table_info(name, badge_number, priviledge, category) values('$name', '$badge_number', '$priviledge', '$category')";
$result = #mysql_query($query_string) or die (mysql_error());
//echo "Your details have been entered! Please click on 'View Users' to display all users.";
echo "1";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="delete")
{
$id = rtrim($_REQUEST['id']);
$order = $_REQUEST['order'];
echo deleteRow($id);
echo selectAll($order);
}
elseif($action=="insert")
{
$name = $_REQUEST['name'];
$badge_number = $_REQUEST['badge_number'];
$priviledge = $_REQUEST['priviledge'];
$category = $_REQUEST['category'];
echo insertRow($name, $badge_number, $priviledge, $category);
}
elseif($action=="update")
{
$order = $_REQUEST['order'];
echo selectAll($order);
}
?>
You shouldn't need to append the return data to the page at all. Why don't you run your function immediately after the AJAX request completes, like so:
$.ajax({
success: function(data) {
if(data === "0") {
alert("Badge Number already exists, please check again.");
}
else if(data === "1") {
alert("Your details have been entered!")
ADD_USER_POPUP.close();
}
}
});
place getDivResult() to onclick in which button you click like
< button onclick="getDivResult()">Click me< /button>"
i think it will be work with you.
enclose the echo with a div then trying getting the value by the id.
or
try echoing via json enconde
json_encode
then fetch the value by using AJAX
i think, this script <script>getDivResult();</script> was replaced the content of #divResult by ajax code $("div#divResult").html(data);. Instead of that, place the script inside head section rather than inside #divResult to execute that.
Where is your ajax? How do you do it?
It looks like you're using jQuery. Try reading the documentation
https://api.jquery.com/jquery.get/
You can try something like this:
$.get( "ajax/test.html", function( data ) {
if(data === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(data === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
});
data should be your 0 or 1
When you do .html(data) all the existing elements wipedoff and replaced by new content:
$("div#divResult").html(data);
I guess you should do this:
$("div#divResult").html(data);
getDivResult(); // call after it. and put the function globally.
Run your function
getDivResult();
after
$("div#divResult").html(data);
in ajax
I have a function in php that need an id and i need to add a variable in my ajax url the id
PHP Code:
function get_json_selected($purpose)
{
//echo $this->input->post("ids");
$ids = explode(",", $this->input->post("ids"));
$site_url = site_url($this->router->class);
if ($purpose == "EQUIPEMENT"){
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get("equipments a")->result_array();
echo json_encode(array("spares" => $result));
} else {
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get($this->active_table." a")->result_array();
echo json_encode(array("spares" => $result));
}
}
Ajax Code:
this is just example of the variable of id.
$purpose = "EQUIPMENT"; // how can i add this php variable to ajax url
url: "<?=site_url('equip_request/get_json_selected');?>", // this is the current code how can i add id in this url
or is this code right?
url: "<?=site_url('equip_request/get_json_selected/'.$purpose);?>"
var purpose = '<?php echo json_encode($purpose); ?>';
url: 'example.php?=' + purpose;
+ is the concatenator in javascript. hope this helps. spend plenty of time and add plenty of security to echoing that var into javascript. else you could find yourself viction of xss.
Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}
I've been trying to build a registeration form for a website I am building. I can do the basics but I want it to check the username availability without reloading the page.
JAVASCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
var username = $("#Username").val();
$.post("scripts/check_username.php", {username: username}, function(data)
{
if(data == 'false')
{
alert('Username not available');
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
HTML
<form id="registerForm">
<table>
<tr><td>Username</td><td><input id="Username" class='textInput' type='text' name='username' required></td></tr>
PHP SCRIPT
<?php
include 'open_connection.php';
$result = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$result = 'false';
}
echo $result;
?>
When I leave the textbox it says username available no matter what. I placed a username "test" in the database... no luck
Please help
PHP:
$output = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$output = 'false';
}
echo $output;
Ans Script:
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
$.post("scripts/check_username.php", {username: $("#Username").val()}, function(data)
{
if(data =='false')
{
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
By the way, don't use mysql_* function, they're deprecated. use Mysqli or PDO. Next thing is you forgot to put semi-colon that the end of your statements !
You specify $("#Username").value do you mean to use $("#Username").val()?
$('#Username').value is probably returning you rubbish which will not exist in your DB.
Do you use Developer Tools or Firebug?
It would be easy to see where the issue lies if you examined the $.post to check_username.php:
(1) is the correct post request being sent? I think your data object should be {"username":username}
(2) is your script responding true? or something else? You only know it's not returning false by the way your if statement is structured.