Javascriptvoid(0) wont call function - javascript

I have looked over my code and realized there where a few issues with the script. Now I have sorted it it will not pass through the checking you have the correct funds. i think it has something to do with the way i have declared my variable
<script type="text/javascript">
var money = "<?php echo $ir['money']; ?>";
var price = 5000;
function openAccount() {
var c = confirm("Are you sure you want to open a bank account for <?=money_formatter(price)?>?");
if(c) {
$('#main_text').html('Opening account');
$('#main_text').append('Checking you have the correct funds');
if(+money < +price) {
$('#main_text').append('<span style="color: red;">Incorrect funds, You need another <?=money_formatter((price)-$ir["money"])?>...</span>');
} else {
$.post('<?=file?>?open=true&print=1', function(data) {
if(data == 'not_enough_money') {
$('#main_text').append('Incorrect funds...');
} else if(data == 'opened') {
$('#main_text').append('You have succesfully opened your brand new bank account!>View Account');
}
});
}
}
}

You simply forgot two quotes.
Replace <a href="javascript:void(0); onClick=new_account();">
by <a href="javascript:void(0);" onClick="new_account();"> and everything will work.

Related

Trigger a php script using ajax - how and where to program this?

Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});

PHP code inside script tag for redirecting to another page

I have a list of users besides that are the delete button. Where in when you click the delete button a confirm() script will appear. I used this code but the one being deleted is always the last id.
button onclick="myFunction()">Delete</button></td>
<script>
function myFunction() {
if(confirm("Are you sure you want to delete this?") == true) {
window.location.href = "delete.php?id=<?php echo $r->id); ?>";
} else {
//
}
}
</script>
You can use this:
<button onclick="myFunction(<?php echo $r->id; ?>)">Delete</button></td>
<script>
function myFunction(id) {
if(confirm("Are you sure you want to delete this?") == true) {
window.location.href = "delete.php?id="+id;
} else {
//
}
}
</script>

Check if the user likes the facebook page or not

I'm trying to check if the user liked my page before use my app on it with the following code
<body onload="liked()">
<script type="text/javascript">
function liked() {
FB.api("me/likes/2002200279160150349", function(response) {
if (response.data.length == 1) {
alert("page liked already");
} else {
alert("page is NOT liked ");
}
});
}
</script>
</body>
determine that the user is authnticated in another page and logged in properly
Simple Approach use this method
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
But,This code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the "OAuth 2.0 for Canvas" advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}

Trouble using jQuery post inside non jQuery function

I have the following script inside a HTML page:
<script>
function Test(){
alert("i got here");
var username = document.registration_form.username.value;
alert(username);
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if (data = "0"){
alert('That username is already in use, please choose another');
return false;
};
if (data = "1") {
return true;
};
});
};
</script>
I'm trying to get the function test to return true or false if a username is already in my database.
checkname.php contains the following:
<?
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['name'];
$sql="SELECT * FROM members WHERE username='".$myusername."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count >= 1){
echo "0";
}
else {
echo "1";
}
?>
I've tried hardcoding a name and running the PHP and it works fine.
For some reason though when I run Test() the first 2 alerts come through fine, showing me the username enetered, but none of the subsequent alerts appear.
Oooo and jQuery has been added in the header like so:
<script src="create/js/jquery-1.4.4.min.js" type="text/javascript" ></script>
<script src="create/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
Any help much appreciated :)
First of all, your return statements from the callback to $.post will not return from your Test() function. You should call Test with a callback function that deals with the data from the server, something like this:
function Test(username, callback) {
$.post("checkname.php", {name: username}, callback);
}
Test(document.registration_form.username.value, function(data) {
if(data == "0") {
// Do something
} else {
// Do something else
}
});
Brad is also correct about the comparison - you're currently assigning "0" to data. You should get the alerts though, I think, even with the other errors. Maybe you need the absolute path to the checkname.php script? E.g. "/checkname.php" (note the slash)?
Off-hand, you should be using == for comparison in javascript. A single = is an assignment, == is a comparison. So having said that, if (data = "0"){ would become if (data == "0"){.
Other than that, I don't see anything too fishy. You're allowed to use jQuery functions within "traditional" javascript function(){}'s.
Also, make sure you sanitize the input from the $_POST['name'] using something like mysql_real_escape_string.
The problem may be that the PHP script is returning a new line before or after it prints 0 or 1. So the string returned wouldn't equal "0" or "1".
Try to change it to output JSON instead.
if($count >= 1){
$ret = 0;
}
else{
$ret = 1;
}
echo json_encode(array('status' => $ret));
And then change your $.post to:
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if(data.status = 0){
alert('That username is already in use, please choose another');
}
if(data.status = 1) {
alert('That username is not already in use');
}
}, 'json');
NOTE: The return false and return true don't do anything. You cannot return from an AJAX call.

Simple Password Javascript Code?

I need a Javascript application that, when run, prompts a password to be entered, and if the password is correct, the script causes the webpage to close. If the password is incorrect, the script prompts for the password to be entered again.
I'm planning on loading this script onto my cell phone, which doesn't have a password-protected keylock feature.
Don't know if this works on your cell phone, but it does with my browser:
<head>
<script language="JavaScript">
var pass_entered;
var password="cool";
while (pass_entered!=password) {
pass_entered=prompt('Please enter the password:','');
}
self.close();
</script>
</head>
Javascript "keylock" on a cell phone will probably be trivial to work around.
Anyway, if you really want to check password in Javascript, you can at least avoid putting it in plain text in page source.
Get MD5 JS implementation, and compare (salted!) password hashes instead.
Ok, we can have two approuches.
We can all read javascript, so if the person actually open your code he will see the password.
By ajax, check the password in a specific page.
function passWrdAPI() {
this.getHX = function() {
var hx;
try {
hx = new XMLHttpRequest();
}
catch(e) {
try {
hx = new ActiveXObject("Microsoft.XMLHttp");
}
catch(ex) {
hx = new ActiveXObject("Msxml2.XMLHttp");
}
}
return hx;
}
this.password = "mypass";
this.checkPwd = function(pass) {
if (pass != this.password) {
// Or close or redirect
alert('Wrong!');
window.close(); //or
location.href = 'http://www.google.com';
}
}
this.checkPwdPage(page, pass) {
var hx = this.getHX();
if (hx != null) {
hx.open('GET',page + "?mypwd=" + pass);
hx.onreadystatechange = function() {
if (hx.readyState == 4) {
if (hx.responseText == 'false') {
// Or close or redirect
alert('Wrong!');
window.close(); //or
location.href = 'http://www.google.com';
}
}
}
hx.send(null);
}
else {
alert('error!');
}
}
}
Usage:
for the first approach:
var check = new passWrdAPI();
check.checkPwd(THEPASSENTERED);
for the second:
var check = new passWrdAPI();
check.checkPwdPage(YOURPAGE, THEPASS);
I don't know if it will work on your cell phone =/
Sorry if I don't help.. bye bye!

Categories