How to get div content that was echoed by PHP - javascript

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

Related

Passing js variable to php using ajax does not work

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

Get data php with ajax without display it

Is it possible to get data php with Ajax without display them ? Simply stock data in JS variable?
I need this data to manipulate dates but no show it.
When I tried to simply return data without echo, etc. Data ajax in JS is empty
Ps : sorry my English is bad
try it this way
File *.php
<?php
$var_1 = null;
$var_2 = null;
/** ... */
$response = new stdClass;
$response->var_1 = $var_1;
$response->var_2 = $var_2;
echo json_encode($response);
?>
File *.html or *.js
<script>
var state = {};
$.ajax({
url: 'getData.php',
type: 'post',
dataType: 'json',
success: function (response) {
console.warn(response);
state = response;
}
});
</script>
Assuming you are trying to pass data from a PHP file to HTML/JS where it happens that your PHP file is also included in the HTML that's why it's displaying the echo (if I understood correctly!)
Using AJAX PHP example from w3school.
HTML sample file:
<?php include "PHP_SAMPLE_FILE.php" ?>
<header>
<meta name="temp_files" content="<?= htmlspecialchars($jsonData) ?>">
<!-- The rest of HTML content -->
JS sample file:
if (str.length == 0) {
// do something if there was nothing entered
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText.includes('{')){
result = JSON.parse(this.responseText);
// do something if response is JSON
} else {
// do something if response is null
}
}
}
xmlhttp.open("GET", "PHP_SAMPLE_FILE.php?q="+str, true);
xmlhttp.send();
}
PHP sample file:
$q = $_REQUEST["q"] ?? $_POST["q"] ?? "";
$sql = "GET SOMETHING FROM DATABASE";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[] = $row;
}
}
$jsonData = json_encode($json ?? null);
if($q != ""){
echo $jsonData;
}
What happens exactly is that once the page loads initially it won't display the output of the PHP query as we have surrounded the echo with an if statement that requires to have query value (q) to search and it shouldn't be empty (""). Of course, assuming that once the page is loaded the data is shared with the client-side through defined PHP variables using various approaches, using a meta tag in the header for instance.
Once the data is received from the PHP file through echo, we use the JSON.parse function to parse it as in this scenario JS receives it as a string.
Hope that helped :)!

Data from jQuery callback is failing to compare

I'm trying to make a "sign in status" thing.
Here is a summary of what is happening.
User fills our field and jQuery request is sent.
Credentials are validated.
Screen displays a welcome message.
So I can get the welcome message sent back to me if the credentials are valid (or error if credentials are false), but here is where the issue resides...
I am having a really difficult time storing anything in PHP as a global variable using my only jQuery (no included file) approach... So my workaround was to take the passed message (Let's just say when credentials are valid, I pass back something like "X" or "1"), and then when the data comes back in the jQuery, I put an if statement in the callback, but it isn't working.
I know that the data being passed is matching what is being compared, and i've tested many different things to pass back, but the comparison is not being done.
Perhaps it isn't possible to do things like if statements in a jQuery callback, but also maybe I'm doing something wrong.
HTML:
<label>Sign In</label>
<br>
<label>Username</label>
<input type="text" id="name1">
<label>Password</label>
<input type="text" id="pass1">
<br>
<button type="submit" id="button2">Sign In</button>
<div id = "xx1">Status: Offline</div>
<div id = "xx2"></div>
jQuery:
$(document).ready(function(){
$("#button2").click(function(){
var name1=$("#name1").val();
var pass1=$("#pass1").val();
var key = "signIn";
$.ajax({
url:'rpc.php',
method:'POST',
data:{
name1:name1,
pass1:pass1,
key:key
},
success:function(data){
if(data === '1')
{
document.getElementById('xx1').innerHTML = "Status: Online";
}
document.getElementById('xx2').innerHTML = data;
//var p = data;
}
});
});
});
(xx2 is updating by the way)
Lastly, relevant bits of my rpc.php:
else if($_POST['key'] === "signIn")
{
$name1=$_POST['name1'];
$pass1 = $_POST['pass1'];
if($name1 !== "" && $pass1 !== "")
{
$sql = "SELECT * FROM whatever";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($name1 === $row["username"])
{
$UNTrue = true;
if (password_verify($pass1, $row['password'])) {
$PassTrue = true;
}
}
}
} else {
//echo "0 results";
}
if($UNTrue === true && $PassTrue === true)
{
echo "1";
$conn->close();
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Incorrect Username or Password) </p>";
$conn->close();
}
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Please Fill Required Fields) </p>";
$conn->close();
}
}
So data is "1" in this scenario, as displayed to my via xx2, and xx1 remains as "Status: Offline".
I'm wondering if I have to store the data in a JavaScript variable first, and then later somehow referencing it again ASAP.
The other option would be to figure out how to use PHP global variables without file inclusion.
Is it possible even though you're echoing "1", it's getting interpreted as a number? Assuming the data response you get in the success callback is literally just what your PHP script echoes, that's the first thing that jumps out to me, since (1 === "1") is false.

Comparing strings in JQuery not working

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...

Will this huge javascript array loaded from a database crash my website?

So on this website I'm making (who knows if i'll actually finish it lol) when someone opens up the new user page, php echos into a javascript script all the usernames from the database to create an array.
<script type="text/javascript">
var allUsers = ['!' <?php
$result = mysql_query("SELECT username FROM users ") or die("error " .mysql_error());
$usersArray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$usersArray[] = $row['username'] or die("error ". mysql_error());
}
foreach ($usersArray as $name) {
echo ',' . json_encode($name );
}
?> , ];
the point of this is to have a live checker so if you type in a username that already exists, red text shows up next to the username input. But let's say I get 1,000,000 users (completely theoretical). Fortunately, the array only gets created at the beginning of the web page load. But will the function that checks if the username already exists in the huge array and gets called everytime someone changes the text in the username input put too much stress on the script and crash the website? If so, is there a better way to do what I'm describing?
Here's the rest of the code
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
function onUserChange() { //gets called onkeypress, onpaste, and oninput
if(contains(allUsers, str)) {
div.innerHTML = "Username already exists";
div.style.color = "red";
userValid = false;
}
}
</script>
Something along these lines. ( with jQuery and PDO ) - note - code is not tested.
var keyTimer, request;
$('namefield').blur(function(){
onUserChange();
});
$('namefield').keyup(function(){
onUserChange();
});
function onUserChange() { //gets called onkeypress, onblur
keyTimer = setTimeout(function(){
if(request && request.readystate != 4){
//cancel a previous request if a new request is made.
request.abort();
}
request = $.post(
'http://yoursite.com/location/of/username/script.php', //post data to server
{username : $('namefield').val()},
function(data){
if(data == 0 ) { //might be a string here
alert( 'the name is ok to use.' );
}else{
alert( 'someone has this name already.' );
}
}
);
}, 500); //overwrite previous timeout if user hits key within 500 milliseconds
}
Then in the backend
$sql = 'SELECT id FROM users WHERE username = :username';
//insert from post username but we are good programers and are using PDO to prevent sql injection.
//search for the username in the db, count the number of users or rows should be 1 someone has it 0 no one has it assuming its unique.
$stmt = $Pdo->prepare($sql);
$stmt->execute(array(':username', $_POST['username']));
echo $stmt->rowCount();
exit();
etc.....
Do not do it. My counsel is to use ajax to load the php file that will make a query asking only for the user that was typed in the input and retunr only a boolean value(exists=true / notexists=false)
Code example:
HTML(yourFile.html):
<script>
jQuery(document).ready(function(){
//When the value inside the input changes fire this ajax querying the php file:
jQuery("#inputUser").change(function(){
var input = jQuery(this);
jQuery.ajax({
type:"post",
url:"path/to/file.php",
data:input.val(),
success: function(data){
//if php returns true, adds a red error message
if(data == "1"){
input.after('<small style="color:#ff0000;">This username already exists</small>');
//if php returns false, adds a green success message
} else if(data == "0"){
input.after('<small style="color:#00ff00;">You can use this username</small>');
}
}
});
});
});
</script>
<input id="inputUser" type="text" name="username" value="">
PHP(path/to/file.php):
<?php
$username = $_REQUEST['username']; // The value from the input
$res = mysqli_query("SELECT id FROM users WHERE username='".$username."'"); // asking only for the username inserted
$resArr = mysqli_fetch_array($res);
//verify if the result array from mysql query is empty.(if yes, returns false, else, returns true)
if(empty($resArr)){
echo false;
} else{
echo true;
}
?>
As I can see you need to load the PHP code when your website is loading.
First, I recommend you to separate the code. The fact that you can mix Javascript with PHP doesn't mean it is the best practice.
Second, yes, it's not efficient your code since you make Javascript load the result so you can search into it next. What I suggest you is making the search in the server side, not in client side, because as you say, if you have 100 elements maybe the best is to load all the content and execute the function, but if you have 1,000,000 elements maybe the best is to leave the server to compute so it can make the query with SQL.
Third, you can do all this using Ajax, using Javascript or using a framework like jQuery so you don't have to worry about the implementation of Ajax, but you only worry about your main tasks.

Categories