alert always pop up using ajax - javascript

I have a problem about my code in ajax.
AJAX
<script type="text/javascript">
var stopTime =0;
var scoreCheck = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkScoreRoundOne',
success:function(output){
if(output !=' '){
$('#maincontent1').html(output);
bootbox.alert("We have a winner", function(){
});
stopTime = setTimeout(scoreCheck, 1000);
}
else {
clearTimeout(stopTime);
}
}
});
}
stopTime = setTimeout(scoreCheck,1000);
</script>
CONTROLLER
public function checkScoreRoundOne(){
$id = $this->session->userdata('userID');
$battleID = $this->lawmodel->getBattle($id);
foreach($battleID as $row){
$Rscore = $row->requestedScore;
$Cscore = $row->challengerScore;
if($Cscore == '1'){
$rID = $this->lawmodel->getID($row->challengerID);
foreach($rID as $row){
echo $row->username."Got the correct answer";
}
}
else if($Rscore == '1'){
$cID =$this->lawmodel->getID($row->requestedID);
foreach($cID as $row){
echo $row->username."Got the correct answer";
}
}
else
echo "Answer the question";
}
}
My problem is ajax will always alert even it did not meet the condition in my controller.
I cant test my project if it is correct or not..Im using codeigniter..
Im new in ajax plss help..:(
Edited
How can i make the alert popup only when it meet the condition in my controller? :(
Like when Cscore == '1' alert will popup..

If i get your question right, then this line
if(output !=' '){
in your request should be something like
if(output != "Answer the question"){
Why?
When you don't meet $Cscore == '1' or $Rscore == '1' you return the string "Answer the question". And knowing that whatever you return will be the content of the output variable it will never be only a space ' '!

Move the foreach code to the model and instead use return instead of echo.
Say:
Model:
public function getID($row->challengerID){
//some code
if($Cscore || $Rscore){
foreach($cID as $row){
return $row->username."Got the correct answer";
}
}else{
return false;
}

Related

Calling javascript function in my PHP code

I searched up some questions on stackoverflow and used the suggested solutions, however, I can't seem to get my php code working the way I'd like.
When I visit projects.php?message=success or projects.php?message=removed, the JavaScript function does not execute. In my debugging, I've confirmed the JavaScript is working correctly by attaching it to a button with the onclick property.
My php code:
<?php
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$alert= GET('message');
if ($alert == success) {
echo '<script type="text/javascript"> window.onload=success(); </script>';
} elseif ($alert == removed) {
echo '<script type="text/javascript"> window.onload=removed(); </script>';
}
?>
My JavaScript code:
<script>
function success() {
$.notify({
// options
icon: "pe-7s-cloud-upload",
message: 'New project entry was successfully added.'
},{
// settings
type: 'success'
});
}
function removed() {
$.notify({
// options
icon: "pe-7s-trash",
message: 'Project entry was successfully deleted.'
},{
// settings
type: 'danger'
});
}
</script>
You need quotes around the texts and properly set window.onload:
<?php
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$alert = GET('message');
echo "<script>window.onload = function () { ";
if ($alert == "success") echo "success();";
else if ($alert == "removed") echo "remove();";
echo " };</script>";
?>
If those two are all you need, you can also do this:
$alert = GET('message');
if ($alert == "success" || $alert == "remove") {
echo "<script>window.onload = $alert;</script>";
}
Edit:
To clarify an issue from the comments: to set window.onload to a function, one cannot use
window.onload = myFunc(); // WRONG!
(This will call the function, then set window.onload to the result)
The correct way is:
window.onload = myFunc;
// OR
window.onload = function () {
myFunc();
};
I've tested is the inexistent constant you're using called success.
As #Chris G said
Change the if for :
if ($alert == "success")

How to get div content that was echoed by PHP

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

Can't evaluate true / false return from AJAX call

I'm trying to implement a ReCaptcha with AJAX to verify it so that I can stop the page from submitting if the ReCaptcha fails.
Here's my JavaScript:
function verify_recaptcha(){
jQuery.post(
'verify_recaptcha.php',
{
recaptcha_challenge_field: jQuery('#recaptcha_challenge_field').val(),
recaptcha_response_field: jQuery('#recaptcha_response_field').val()
},
function(data){
if(data == "true"){
alert("ReCaptcha Verified");
}
else{
alert(data);
}
}
);
}
And the contents of verify_recaptcha.php
<?php
require_once('recaptchalib.php');
$privatekey = "-- my private key --";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
echo "false";
} else {
echo "true";
}
?>
The problem is that my test Alert is showing "true" if the recaptcha verifies (and false if it doesn't), which I don't think should be possible. It should evaluate data == "true" in that if statement and display "ReCaptcha Verified".
Most anything I search on the subject the problem is that people are trying to return a value out of the AJAX call, which I know I can't do and am not doing here.
What am I missing?
Reframed your code a bit. Try,
PHP:
...
...
$json = array();
if (!$resp->is_valid)
$json['result'] = true;
else
$json['result'] = false;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
JS:
...
...
jQuery.post(
'verify_recaptcha.php',
{
recaptcha_challenge_field: jQuery('#recaptcha_challenge_field').val(),
recaptcha_response_field: jQuery('#recaptcha_response_field').val()
})
.done(function(response){
console.log(response);
if(response.result == true)
{
// Entered captcha is correct
}
else
{
// Entered captcha is incorrect
}
});
Explanation:
1) Always return boolean true/false and not in form of string.
2) Use .done(). Won't make much difference from your code, but .done() make your ajax call code much clear.
3) Always open your console and try printing objects and see the output if it is what you are expecting.

AJAX not returning a variable from php

I know there is a few questions like this on here. but I have done a lot of researching and bug fixing all day to try work out why my ajax does not return a response from the php file. All I want is for it to tell me a user has been registered so I can let the user move on with the signing up process. And I just need someones wise guidance to tell me what I am doing wrong!!
so I wont bore you with the validation part of the js file just the ajax
if(ValidationComplete == true){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(register, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data: data,
dataType: 'json',
success: function(result){
alert(result.status);
console.log(result.data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
return false;
} else {
return false;
}
currently with this, if I remove the dataType bit the alert bit happens but currently with it there nothing does.
again I will just skip to the chase on the php file
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password',
'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
echo json_encode(array("response"='true'));
Any help would be amazing!!!!!
updated code:
<?php
if( isset($_POST['firstname']) &&
isset($_POST['surname']) &&
isset($_POST['email']) &&
isset($_POST['day']) &&
isset($_POST['month']) &&
isset($_POST['year']) &&
isset($_POST['password']) &&
isset($_POST['re_type_password'])){
$first_Name = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());
if(!empty($first_Name)&&
!empty($surname)&&
!empty($email)&&
!empty($day) &&
!empty($month) &&
!empty($year) &&
!empty($password)&&
!empty($re_type_password)){
if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
echo 'the data enetered is to long';
} else {
if($password != $re_type_password){
echo 'passwords do not match, please try again.';
} else{
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
echo 'Email address already on databse';
} else{
if($day>31 || $month>12){
echo 'date of birth wrong';
} else{
$dob= $year.'-'.$day.'-'.$month;
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password'
,'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
email($email, 'Email Confirmation', "hello ". $first_Name." ,
\n\n you need to activate your account so click the link ");
$return_data['status'] = 'success';
echo json_encode($return_data);
} else {
echo #mysql_error();
}
}
}
}
}
} else {
echo "<p id='error'> All fields are required. Please try again.</p>";
}
}
?>
<?php
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
?>
</body>
</html>
the last line it should be
echo json_encode(array("response"=>'true'));
see the added > in the array declaration, that is used to assign arrays with keys.
also in general you should put a error capture in your ajax statement, see this answer for more info
EDIT: Ok wow, that's some spaghetti code you have there, but after a little clean-up your problem is too many closing braces } you have to remove the } just before the following line also get rid of the closing and opening tags around this line, they serve no use.
} // <------- THIS ONE!
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
I should also mention two other issues with your code
You are accepting input from the user without cleaning it up and testing it properly. This is no no read here to find out more
You are using mysl_ functions, these are old and depreciated they are also security risks. Check out PDO instead
EDIT:
Add ini_set('error_reporting',1); to the top of your php script.

JavaScript Prompt Box Cancel Button?

I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});

Categories