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")
Related
Currently I have this code as shown below.
Whereby, when I click on the button, it will show either success or fail.
I have another php script on another webpage to call from it.
Currently I call the php script, using the php file name. I would like to check is there a way for me to call the php file using a function in the url?
The reason is because, in the php script, I would have several functions to call from. I do not want to create multiple php file.
below is my code.
<script>
function bookBTN(x) {
$.getJSON('http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + x, function(data) {
if (data.avail == "yes") {
alert("Success");
}
else { alert("Failure"); }
});
}
</script>
<script>
function viewBTN(x) {
$.getJSON('http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x, function(data) {
if (data.avail == "yes") {
alert("Success");
}
else { alert("Failure"); }
});
}
</script>
movieOne.php
<?php
$seatNum= $_GET["seatNum"];
getSeatNum1($seatNum);
function getSeatNum1($seatNum) {
$seatNum = $_GET["seatNum"];
$url = 'http://movie.com/movieOne?seatNum=' . $seatNum;
$result = file_get_contents($url);
echo $result;
?>
<?php
$seatNum= $_GET["seatNum"];
getSeatNum2($seatNum);
function getSeatNum2($seatNum) {
$seatNum = $_GET["seatNum"];
$url = 'http://movie.com/movieOne?seatNum=' . $seatNum;
$result = file_get_contents($url);
echo $result;
?>
When I only run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + x and having only 1 php function inside movieOne.php , it works fine.
When I run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + xand http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x , having only 1 php function inside movieOne.php , it works fine too.
However when I run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + xand http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x , and have 2 different function (as the code above), the button doesn't work.
If you want to call function from url like codeigniter do, i have an example for you
URL example: http://localhost/jastip/ajax/request.php/get_orders
(function () {
$url_function = explode('/', $_SERVER['REQUEST_URI']);
$function_name = get_defined_functions()['user'];
if (in_array($url_function[4], $function_name)) {
$index = array_search($url_function[4], $function_name);
$dynamic_fun = $function_name[$index];
$dynamic_fun();
} else {
var_dump("Page not found");
die;
}
})();
function get_orders()
{
echo "get orders";
}
function get_something()
{
echo "get something";
}
I'm total beginner to ajax (don't know jquery at all) so i've been using simple ajax without jquery, what i want to do is simple to call codeigniter's controller method. Dont know what i'm wrong at. Here's my ajax function and controller:
function usernameOnChange() {
var username = document.getElementById("register_username").value;
if (username.length == 0) {
document.getElementById("usernameGlyph").className = "glyphicon glyphicon-remove";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("usernameGlyph").className = 'glyphicon glyphicon-ok';
}
};
var link = "<?php echo base_url("index.php/Test/checkUsername?username="); ?>" + username ;
xmlhttp.open("GET", link, true);
xmlhttp.send();
}
}
And here's my controller (it's still test controller just to see that my ajax-codeigniter php connection is working).
<?php
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper("url");
$this->load->library("form_validation");
$this->load->helper("security");
$this->load->helper("form");
}
public function checkUsername($username) {
echo "<script>alert('CODEIGNITER RESPONDED!');</scirpt>";
}
}
?>
Thanks in advance!
Before you start with ajax, need to understand that ajax required to have good output from the PHP to get perfect result of the call. In your codeigniter controller, you are echoing a script tag. Please dont do that when you use a ajax call.
Sample Codeigniter Controller function
<?php
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper("url");
$this->load->library("form_validation");
$this->load->helper("security");
$this->load->helper("form");
}
public function checkUsername($username) {
$output = array('status'=>200,"message"=>"Your Ajax is called");
header('Content-Type:application/json;');//Please do not forgot to set headers
echo json_encode($output);
}
}
Here the controller will give perfect output which javascript can read it easiliy
For jQuery
<script type="text/javascript">
$.get('<?php echo base_url("index.php/Test/checkUsername?username=xyz"); ?>',function(data){
alert(data['message']);
});
</script>
First of all your this line will produce error or unexpected result.
var link = "<?php echo base_url("index.php/Test/checkUsername?username="); ?>" + username ;
//double quote inside double quote
It should be like this
var link = "<?php echo base_url('index.php/Test/checkUsername?username='); ?>" + username ;
You also need to know how site_url and base_url function produce links
Finally I think your link should be like this.
var link = "<?php echo base_url('index.php/Test/checkUsername/'); ?>" + username ;
//you can remove index.php if you set your config file properly.
Okay, so here's solution that I've found out and it works fine. It changes icon-span of input field to tick if login username that is typed at the moment exists in database. Otherwise it changes icon to cross. Don't forget to add "&" when sending via "get" more than 1 parameter to controller's method.
$("#login_username").keyup(function() {
$.ajax({
type: 'GET',
url: '<?php echo base_url().'index.php/Test/checkLoginUsername'; ?>',
data: 'type=' + $('#logintype').is(':checked') + '&username=' + $("#login_username").val(),
success: function(newClassType) {
$("#usernameLoginGlyph").removeClass().addClass(newClassType);
}
})
});
Here's my controller method that echos result class type of icon.
public function checkLoginUsername() {
// type = true for customer; false for artist
$type = $this->input->get('type');
$username = $this->input->get('username');
if ($type === "true") {
if ($username === "" || $this->Customer_model->getCustomerByUsername($username)) {
echo "glyphicon glyphicon-ok";
} else {
echo "glyphicon glyphicon-remove";
}
} else {
if ($username === "" || $this->Artist_model->getArtistByUsername($username)) {
echo "glyphicon glyphicon-ok";
} else {
echo "glyphicon glyphicon-remove";
}
}
}
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'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.
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;
}