You can look at the application here: application
I know the code doesn't work in jsfiddle but I have included my code in the jsfiddle so that you can see the whole code and the way it is laid out. jsfiddle
Now if textbox is empty, it displays "false" in alert and displays a message which is fine.
The problem though is this:
If I type the correct or incorrect room number value in the textbox, it always states it is "false" and does not come with a javascript message.
What should happen is if textbox value matches database, then it should alert "true" and display a javascript message "room is Valid", if textbox value doesn't match database then it should alert "False" and display a javascript message "room is Invalid" How can I achieve this?
You can test the application, enter in these figures in the textbox if you wish for testing:
Valid room number CW5/10 , Invalid room number CN2/10.
Below is where error occurs:
var js_var = [];
<?php while($data = mysql_fetch_assoc($roomquery)){ ?>
js_var.push(<?php $data['roomChosen']; ?>);
<?php }?>
Jsfiddle application url updated above
I think you are lacking echo:
<script>
var js_var = [];
<?php while($data = mysql_fetch_assoc($roomquery)){ ?>
js_var.push(<?php echo $data['roomnumber']; ?>);
<?php }?>
</script>
use it as
<script>
var js_var = [];
<?php while($data = mysql_fetch_assoc($roomquery)){ ?>
js_var.push(<?php echo $data['roomnumber']; ?>);
<?php }?>
function checkroomnumber(){
var roomnumber = document.getElementById("roomnumber").value;
for (i = 0 ; i<js_var.length; i++){
if (js_var[i]==roomnumber){
alert("room is correct");
return true;
}
}
alert("room is incorrect");
return false;
}
</script>
<input type="textbox" name="roomnumber" id="roomnumber" />
<input type="button" name="checkroom" value="checkroom" onclick= "checkroomnumber();" />
Related
del_id = $('.button').attr('rel');
alert(del_id)
PHP:
while ($row=mysqli_fetch_assoc($rs)) {
?>
<div class="itemsin" >
<span data-toggle="confirmation" rel="<?php echo $row['id']?>" class="button" id="rmlb">Click to Remove </span>
</div>
<?php
}
}
?>
I tried this but it's alerting only the first value out printed by loop please give me a suggestion
First of all, please post corrected and formatted code in future.
Here is what you need:
Collected all PHP output data in an JS array or object
Create a loop in JS to print all array values.
You need to be carefull with alerting each value because it will give a you a popup box for each array item and the annoying popup will never finish. I suggest outpoint them in console to see the result.
Your JS Code:
del_id = document.querySelectorAll (".button");
for(var i = 0; i < del_id.length; i++){
attrValue = $(this).attr('rel');
console.log(attrValue);
//You can also alert it if you wish to:
//alert(attrValue);
}
I have column name status in Database it contains values(0,1) ,in front end i have image if i click the image it will redirect to the next page i am using ajax here, what i want before redirect it should perform if condition i want to check the database column status if the column contain any row '1' it should redirect if all rows in column '0' its not checking the if condition it will redirecting can anyone guide me how to perform this .below is my code(i.e now in row status all values are 0 it will not redirect it want to show alert but its redirecting)
html
<img id='redirect' src="/image/exporttt.png" style="margin:-30 0 0 0px;cursor:pointer;" >
$sql_selectsupplier = "********";
$result1 = mysql_query($sql_selectsupplier);
while($rows=mysql_fetch_array($result1))
{
$reditect=$rows['status'];
}
Ajax
<script>
$(document).ready(function() {
$("#redirect").click(function() {
if($reditect=1){
var clientid=document.getElementById("client").value;
$.blockUI(
{
message: '<h2>Please wait...</h2><img src="/image/loader.gif" />',
timeout: 2000
});
$.ajax({
type:"post",
data:"clientid="+clientid,
success:function(data){
window.location = '?action=clientroutingchange&clientid='+clientid+'';
$("#result").html(data);
$('.blockUI').hide();
}
});
}
else{
alert("no changes made")
}
});
});
</script>
From your code it's not clear which one is PHP code, and which one is out of the PHP block.
Inside your block you have
if($reditect=1){ which does not seem like a javascript code.
Is that php?
If yes, then you are using it wrong way. = is an assignation operator, so you do assign the value 1 explicitly this way.
I would suggest, if you are using PHP conditions, also to move thme outside the script block:
<?php if ($reditect == 1): ?> # `==` for comparison
<script>
var clientid=document.getElementById("client").value;
// .. all the code
</script>
<?php else: ?>
<script>
alert('.....');
</script>
<?php endif; ?>
If it was an Javascript condition, then you need to assign the value of the php variable to the js var
<script>
var reditect = "<?= $reditect; ?>";
if (reditect == '1') {
// something
</script>
Use == for comparision
if($reditect==1)
and your $redirect is a php variable which doesn't make sense in script
So, use
var reditect = <?php echo $reditect ?>
and check by,
if(reditect==1)
I have a form which I want to show the response in div via AJAX. Here is the form image from funds_transfer.php.
I test it with manual method=post and submit with the form and it works nicely. Here is the partial PHP code from funds_transfer_backend.php:
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
echo "Please complete the form!";
$response = -1;
}
else {
// other code goes here..
$display = array('response' => $response); // for ajax response later
echo json_encode($display);
PHP gave me this output:
Please complete the form!{"response":-1}
Now I want to implement it with AJAX and it's currently not working. Here is my current no working html + jQuery code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
//other code goes here..
<p>Transfer your funds to other account
<script type="text/javascript">
// Pre populated array of data
var myData = new Array();
<?php
$sql="SELECT * FROM `account` WHERE client_id='$id'";
$result=mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "myData.push('".$row['funds']."');";
$result_array[] = $row['id'];
}
?>
</script>
<form id="example" name="example">
Select your account<select id="selector" name="index_num" style="margin-left: 10px;">
<option value="-1">Account Number</option>
<?php //echo $result_array[0];
$num = count($result_array) - 1;
$i=0;
while($i<=$num)
{
echo "<option value=\"$i\">$result_array[$i]</option>";
$i++;
}
?>
</select>
<br />
Funds : RM <input type="text" id="populateme" name="funds" disabled/><br>
Recipient Account Number <input type="text" id="recipient_box" name="recipient" /> <br>
Amount : RM <input type="text" id="amount_box" name="amount"/><br>
<input type="button" value="Submit" onclick="update();">
<input type="reset" value="Reset">
</form>
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<script type="text/javascript">
document.example.selector.onchange = updateText;
function updateText() {
var obj_sel = document.example.selector;
document.example.populateme.value = myData[obj_sel.value];
}
</script>
</p>
The SQL query above will fetch data from db and populated it in the select box and disabled text box. No problem with that it's currently works nicely.
The problem is there's no response in div id="stage after submit and validation data.response==-1 . I'm not sure what's the problem here probably the form didn't submit at all. Please help and thanks in advance.
Add id
<select id="index_num" name="index_num" style="margin-left: 10px;">
because you index_num value is not sending and you get a notice as response with your
json. Also remove from funds_transfer_backend.php this line -> echo "Please complete the form!"
Remove the comma on this line:
amount : five,
I think you should use $('form[name=YourFormName]').serialize();
....
var posted = $('form[name=YourFormName]').serialize();
$.post("funds_transfer_backend.php", posted ,function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
...
if you're using chrome, launch the Developer Tools (ctrl+shift+I), go to the Network tab, then submit your form. if the form is in fact being submitted, you'll be able to inspect both the request and response to see exactly what is being submitted to and returned from the server. if your form is not being submitted, due to a JavaScript error for example, the error will appear in the Console tab.
similar debugging tools exist for FireFox as well.
a couple other things to note:
1) your JavaScript is populating the "two" variable incorrectly. it references an element with id "index_num", however the id on that element is "selector". that being said, you should in fact just use the serialize() approach that Vu mentioned.
2) your PHP code is echoing a raw error message before later on echoing the actual JSON response. this results in invalid JSON. you should store the error into a variable and push that error onto the associative array with a proper key (e.g. "message"). then you can display that on your page like so:
$('#stage').show().html(data.message);
First you are echoing the error in the PHP and you are expecting a JSON in the response in the AJAX success. So first remove the following line in the server/PHP script, or say don't echo anything other than the JSON.
echo "Please complete the form!";
And ensure that your PHP output is as follows on the correct scenario.
{"response":-1}
Now your data variable in the AJAX success will contain json format only. Do a parseJSON before checking if (data.response==-1) as follows.
function(data){
data = $.parseJSON(data);
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
}
Probably a dead simple and idiotic question (I'm totally new to javascript):
I have this code that loads a new post by clicking on a "next" or "back"-link. The clicks variable is used to scroll up and down in the sql-limit-statement (using the swapContent function), means you move backward or forward in the database by clicking the links. It works easy and perfectly:
<script type="text/javascript">
var clicks = -1;
function increase()
{
clicks++;
return false;
}
function decrease()
{
clicks--;
return false;
}
</script>
<div id="<?php echo $post['id'].'-multipost'; ?>">
<?php include('views/posts/_postmultipost.php'); ?>
</div>
<div id="<?php echo $post['id']; ?>-next" class="rightbutton" style="display:block;">
next
</div>
<div id="<?php echo $post['id']; ?>-back" class="leftbutton" style="display:none;">
back
</div>
The only problem: As you see I have several posts (post-IDs). But the javascript var "clicks" is always the same. How can I add the post-id into the javascript variable name "clicks", well, something like this :
var <?php echo $post['id']; ?>-clicks = -1;
Of course it doesn't work this way, but I have no clue how to manage it. Any advice? Sorry for this stupid question...
Thanks for your help!
UPDATE
Ok, got the solution: Bryan was right!!!
Changed the code to:
<script type="text/javascript">
var clicks = {};
clicks['<?php echo $post['id']; ?>'] = -1;
function increase()
{
clicks['<?php echo $post['id']; ?>']++;
return false;
}
</script>
The javascript in html stays as it is:
>
Clicks is now an object and will output the following in the swapContent-Function:
count: Array
(
[80] => 0
)
In php you would access the value like this:
foreach($count as $key=>$value) { $count = $value }
In javascript it seems to work a bit different like this:
for(x in clicks)
{
var clicks = clicks[x];
}
Seems to work perfectly now, thanks for your help!!
I'm not incredibly familiar with PHP, so I don't know about php echo. However, would using an object work?
var postClicks = {};
postClicks['<?php echo $post['id']; ?>'] = -1;
As far as I understand you are trying to get this:
var something-clicks = -1;
But in JS something-clicks is an expression - substraction of two variables.
Name tokens in JS cannot contain '-' in contrary with CSS.
You have a syntax error:
onmousedown="increase(); javascript:swapContent('next', clicks, '<?php echo $post['id']; ?>', '<?php echo $post['title']; ?>', '<?php echo $_SESSION['user']['id']; ?>');"
that javascript: is the problem. That property is expected to contain raw JS, and that token is invalid. the javascript used as a protocol is for use on the href property of an a tag.
Other than that, it looks alright. Just type clicks in the JS console of your browser to get the current value returned. Or add console.log('clicks:', clicks); to your function so that the result is logged out on each click.
I have an error in my PHP on this line:
var strRooms = <?=$js_var?>;
It is saying that this has an invalid markup, what does this mean?
You can look at the application here: application
Now if you type in nothing in the textbox, then it doesn't display a message saying "Please Enter in a Room Number", if you type in a invalid room number then it doesn't show a message stating "This Room is Invalid". Why is it not working?
I know the code doesn't work in jsfiddle but I have included my code in the jsfiddle so that you can see the whole code and the way it is laid out. jsfiddle
So how can this error be fixed and how can the JavaScript validation message appear as they should do?
var strRooms = <?php echo json_encode($js_var); ?>;
This will guarantee that it'll work, regardless of what type of variable $js_var is.
Try this var strRooms ="<?php echo $js_var; ?>";
Have you tried quotes?
var strRooms = "<?=$js_var?>";
or
var strRooms = '<?=$js_var?>';
Use this in case of empty textbox
var strRooms ="<?php echo !empty($js_var) ? $js_var : 'Error message'; ?>";