I have a basic javascript code for my saving entry.
Scenario:
I have two forms, the first form,[view_netbldg.php], is for my data entry then when the user click the "ADD" button it will proceed to the next form [save_netbldg.php]. So in my save_netbldg.php form there is a if else condition where the code will know first if the variable of $bldgName or $netName are empty. Everything is okay, but my concern is this when the code detect either of the two variables are empty the code below I'm using will be executed.
Here's my code:
if($bldgName == "" || $netName == "")
{
echo "<script type='text/javascript'>\n";
echo "alert('Please complete the fields for Building Name or Network Name');\n";
echo "</script>";
header("location:view_netbdlg.php");
}
*The result of the program is, its not displaying the alert instead it will jump to the header
The correct way is, if the $bldgName == "" || $netName == "" == true** an alert will display and when the user click the ok button it will proceed to the next form which is "view_netbdlg.php". I don't need a confirmation message here because its only an error message something like that.
Advance thank you.
You are confusing php with javascript, You can solve this by
if($bldgName == "" || $netName == "")
{
echo "<script type='text/javascript'>\n";
echo "alert('Please complete the fields for Building Name or Network Name');\n";
echo "window.location='view_netbdlg.php';\n";
echo "</script>";
}
That happens because when the document loads, it stops when it finds a script tag.
In your case, you're trying to echo data in an undetermined part of the document, when it is already loaded.
Here's my solution:
PHP File (test.php):
<?php
if(!isset($_POST['bldgName']) || !isset($_POST['netName']) {
die("false"); //returns false if the values are NOT set
} else {
die("true"); //returns true if the values are set
}
?>
In your file (file.html):
<form method="post" action="test.php" id="formtest">
<input type="text" name="bldgName" />
<input type="text" name="netName" />
</form>
<script type="text/javascript">
if(getAjaxResponse(document.getElementById("formtest") == "true") {
alert("Please complete the fields for Building Name or Network Name");
window.navigate("view_netbdlg.php");
}
function getAjaxResponse(frm){
var elem = frm.elements;
var params = "";
url = form.action;
for(var i = 0; i < elem.length; i++){
if (elem[i].tagName == "SELECT"){
params += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) + "&";
} else {
params += elem[i].name + "=" + encodeURIComponent(elem[i].value) + "&";
}
}
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}
</script>
you have written the the code under script and never invoked that script
for that you have to use functions and call the function manually...
For more about function call refer
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call
You could try:
if($bldgName == "" || $netName == ""){
header('Refresh: 10; URL=your url');#10 second delay
echo "Please complete the fields for Building Name or Network Name";
exit;#make sure rest of page doesn't render!
}
Related
I am using jQuery to send a part number from one php file to another.
The part number is received correctly in the destination php file, but when when I try to use it, it does not work.
Here is the strange thing: To test,when I use $mpn=STA-12 (or any other value that exists in table2), in destination php file, the connection is established and the relevant data is extracted, BUT when THE SAME DATA is fetched, it does not work
Here is the destination PHP file:
<?php
$row['mpn'] = $_GET['q'];
include("order/connection.php");
echo "mpn is here : ".$row['mpn']; // It displays STA-12 but doesn't data get fetched!
$mpn=$row['mpn'];
//$mpn="STA-12"; // *** When I actually put this line in, it all works ***
$stmt = $pd->prepare("SELECT * FROM table2 WHERE part_number = :part_number " );
//$stmt->execute(array());
$stmt->execute(array(':part_number' => $mpn));
$row = $stmt->fetch(PDO::FETCH_BOTH);
//... rest of the code
?>
This jQuery script copied from W3:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","serv.reply3.3.php?q="+str,true);
xmlhttp.send();
}
}
And this is where it is called from:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Choose</option>
<option value=" <?php echo $row["mpn"]; ?> ">items</option>
</select>
</form>
The problem is finally solved.
Since the code was copied from another example, the jQuery variable sent over, contained some EXTRA information that when ECHO'ed didn't show.
echo "mpn is here : ".$row['mpn']; that displayed STA-12, actually contained ' string(6) " STA-12" ', which was discovered by doing:
var_dump( $row['mpn']).
This had my head scratching for days.
I am following a tutorial on W3Schools for AJAX PHP. https://www.w3schools.com/php/php_ajax_php.asp
Here is the twist: I am doing this in wordpress. The following is a method that DOES work, but it is less than ideal.
1) Create the following gethint.php in the root directory.
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
...
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
2) Using the CSS & Javascript toolbox plugin, add this code to the header:
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
3) Create a page with the following code (in plain text):
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
While this works, having to create a php file and adding to the root directory seems like bad practice. It would be better to have this php file stored in the plugins directory. However that causes this line of the header script to fail as 404:
xmlhttp.open("GET", "/gethint.php?q=" + str, true);
Simply changing the relative path won't work, because theoretically, different users can have their plugin folder in different locations.
I figure I should be using the wp_ajax_ and wp_ajax_nopriv_ hooks, but my attempts I have failed, so I am probably doing it wrong. Please help.
Doing ajax in WordPress should all be sent to /wp-admin/admin-ajax.php,
to do that, in your plugin's main file or the index.php file,
register your ajax action like this:
// let's do the ajax thing here
add_action( 'wp_ajax_theNameOfMyCustomAjax', 'theFunctionThatMyAjaxWillCall' );
function theFunctionThatMyAjaxWillCall() {
// include your ajax file here, in this case
// I assumed that we placed the gethint.php in
// /wp-content/plugins/yourpluginname/gethint.php
include( plugin_dir_path( __FILE__ ).'gethint.php' );
// don't forget to add "die;" every time you return a response to your ajax
//Example: echo $hint ?? "no suggestion"; die;
// or you can add the termination code right here
die; // this will prevent the ajax response to have 0 in the end.
}
Now, in your javascript, instead of calling the filename of your ajax file, you can now use the global ajaxurl javascript variable like this:
xmlhttp.open("GET", ajaxurl+"?action=theNameOfMyCustomAjax&q=" + str, true);
i have an ajax function where i am simply calling a php page which has a mysql transaction to be run. On checking mysql log, i have verified that the transaction runs successfully but xmlhttp object jumps to the else statement readyState and status.
my js code:
function promoteOptionsAllot(stid,cid,nsid,elid,flag){
anchor = document.getElementById('promoteAnchor'+elid);
imgContainer = document.getElementById('promoteStatus'+elid);
if(flag == 1){
opt1 = encodeURIComponent(document.getElementById('promote_option1').value);
opt2 = encodeURIComponent(document.getElementById('promote_option2').value);
opt3 = encodeURIComponent(document.getElementById('promote_option3').value);
opt4 = encodeURIComponent(document.getElementById('promote_option4').value);
params = "stid="+encodeURIComponent(stid)+"&course="+encodeURIComponent(cid)+"&sem="+encodeURIComponent(nsid)+"&element="+encodeURIComponent(elid)+"&popt1="+opt1+"&popt2="+opt2+"&popt3="+opt3+" &popt4="+opt4+"&flag="+encodeURIComponent(flag);
}
else if(flag == 2){
params = "stid="+encodeURIComponent(stid)+"&course="+encodeURIComponent(cid)+"&sem="+encodeURIComponent(nsid)+"&element="+encodeURIComponent(elid)+"&flag="+encodeURIComponent(flag);
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.removeChild(document.getElementById('prBox'));
document.body.removeChild(document.getElementById('prBackground'));
result = xmlhttp.responseText;
if(result == "done"){
anchor.innerHTML = "<span style='color:#198D19;'><b>Promoted</b></span>";
imgContainer.src = "tick.png";
}else {
alert("There was a problem serving the request. Please try again.");
imgContainer.src = "cross.jpg";
}
}
else{
imgContainer.src = "alert.gif";
}
}
xmlhttp.open("POST","promoptallot.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
Its an onclick event of a link and in clicking the link although the transaction is successful but somehow the imagecontainer shows alert.gif which means it never runs the code inside the readystate == 4 and status == 200 statement.
Please don't suggest using jquery. I know its a stable framework and other things but i need an answer using this only.
Checking the console, i found the problem at line document.body.removeChild(document.getElementById('prBox'));
document.body.removeChild(document.getElementById('prBackground'));
These lines had to be executed on a case basis and i didn't put it inside the if statement.
now after putting it like if (flag ==1){ document.body.removeChild(document.getElementById('prBox'));
document.body.removeChild(document.getElementById('prBackground'));
} it works as intended.
Thanks.
I'm building off of a question I had asked and resolved earlier: front end mysql, deleting a row
Basically, I've got a front end where users can view a DB. Instead of having a delete button next to each row, I'd like to have a checkboxes that can be selected for multiple rows. Then, the user only clicks a single delete button and all the selected rows are removed. I don't know much php and mysql at all, so I'm not sure how to approach the code that I already have.
Currently, the onclick calls a delete function. Can anyone help?
I've got a php file that outputs the html for the mysql data into a long strong, the part I need to change is:
$display_string .= "<td class='blank'><input type=\"button\" VALUE=\"Delete\" onclick='delFunction(" . $row['ID'] . ")' ></td>";
Next my delete function:
function delFunction(ID){
// confirm delete
if (!confirm(\"Are you sure you want to delete?\")) return false;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");
} catch (e) {
try{
ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");
} catch (e){
// Something went wrong
alert(\"Your browser broke!\");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = \"?ID=\" + ID
ajaxRequest.open(\"GET\", \"delete_row.php\" + queryString, true);
ajaxRequest.send(null);
}
To my understanding of your problem, I am posting some codes for both front and back ends
Front-End Sample Code
<body>
<form action="delete.php" method="post">
<input type="checkbox" name="del_chk[]">Item1
<input type="checkbox" name="del_chk[]">Item2
<input type="checkbox" name="del_chk[]">Item3
<input type="checkbox" name="del_chk[]">Item4
.
.
<input type="submit">
</form>
................
Your back-end code would now be...
<?php
if(isset($_POST['del_chk'])){
$chkbox=$_POST['del_chk'];
foreach($chkbox as $key=>$value) {
//Now you can get your value and use it in mysql delete statements
//for example
$del_query="DELETE FROM `yourtable` WHERE `pri_key`=$value;";
if(mysql_query($del_query)) {
echo "Successful Deletion of: ".$value;
}
else
{
echo "Unsuccessful Deletion of: ".$value;
}
} //end foreach
}
?>
I don't know much of ajax. but you can use ajax to call this page..
I have written a simple application that displays a list of candidates for a job, then, upon clicking a hire button, should alter a database to reflect the newly hired candidate and display the rest as unhired. However, the function is not working properly. The problem I am having is the AJAX function never seems to provide a response, and I cannot figure out why. The database is also not getting updated. My files are below.
The line document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>"; is updating a div at the bottom of my html page, showing that the the readyState is 4 and the status is 200, which should mean that the AJAX function returned properly, but the echo'd response is not being displayed. Even when I remove all code from the new_hire.php file and simply make the file echo "hello";, nothing is returned in the responseText.
resumes.php:
<html>
<head>
<script type="text/javascript">
function new_hire(name){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>";
//this line, when removed, does not change anything. I left it in for debugging purposes.
document.getElementById("errors").innerHTML+=xmlhttp.responseText;
if (xmlhttp.readyState=4 && xmlhttp.status=200){
var others = xmlhttp.responseText.split("|");
for (i=0;i<others.length;i++){
tag = others[i].replace(" ","_");
document.getElementById(tag).innerHTML="";
}
}
}
xmlhttp.open("POST","new_hire.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("hiree="+name.replace(" ","%20")+"&position=Salespeople");
var name_tag = name.replace(" ","_");
document.getElementById(name_tag).innerHTML="(Current Employee)<br>";
}
</script>
</head>
...
</html>
new_hire.php (AJAX response file):
<?php
$hiree = $_POST['hiree'];
$pos = $_POST['position'];
$con = mysql_connect("host.name","user","pass") or die('Could not connect: ' . mysql_error());
mysql_select_db("dbname",$con);
$clear = mysql_query("UPDATE $pos SET employed=false WHERE 1=1;");
mysql_fetch_array($clear);
$reset = mysql_query("UPDATE $pos SET employed=true WHERE Name='$hiree';");
mysql_fetch_array($reset);
$people = mysql_query("SELECT Name FROM $pos WHERE employed=false;");
$array = array();
while ($row = mysql_fetch_array($people)){
array_push($array,$row['Name']);
}
mysql_close($con);
$response = join("|",$array);
echo $response;
?>
Please note that your if statement is not using the comparison operator == but rather the assignment operator = so you are using: if (xmlhttp.readyState=4 && xmlhttp.status=200) instead of if (xmlhttp.readyState==4 && xmlhttp.status==200)