From php to JavaScript - run function and to php again - javascript

I have a problem with some PHP / JavaScript. I know a bit PHP but new to Javascript.
I'm trying to get the JavaScript alertify to work with php.
My Q's:
1: How can I parse a PHP variable to a Javascript alertify function
2: It need to be a if php statement, because
if ($id==1){*show alertify};
elseif($id==2){*Do nothing*};
3: And when back to PHP again.
4: What function do I need to call to get the alertify on page load?
The logic:
Please examples in JavaScript because i'm totally new :)
My code so far:
<?php include_once "config.php";
if(!isset($_SESSION['idUserType'])){
$sql = mysql_query("SELECT * FROM Test WHERE id = $id");
while($row = mysql_fetch_array($sql )){
$idStatus = $row["idStatus"];
if($idStatus==1){
echo '<BODY onLoad="confirm()">';
echo '<script>window.onload = confirm();</script>';
;}
elseif($idStatus==2){
$sqlsearchoutput .= 'Do nothing'
;}
}}?>
JavaScript code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="jscss/alertify.min.js"></script>
<script>
function reset () {
$("#toggleCSS").attr("href", "jscss/alertify.default.css");
alertify.set({
labels : {
ok : "ok",
cancel : "cancel"
},
delay : 5000,
buttonReverse : false,
buttonFocus : "ok"
});
}
// Standard Dialogs
$("#confirm").on( 'click', function () {
reset();
alertify.confirm("Comfirm", function (e) {
if (e) {
alertify.success("You clicked: Cancel");
} else {
alertify.error("You clicked: OK");
}
});
return false;
});
</script>

I think your problem is that the "JavaScript" is inserted into the document after the php echos:
if($idStatus==1){
echo '<BODY onLoad="confirm()">';
echo '<script>window.onload = confirm();</script>';
;}
You will need to have them both inserted at the same time.

Related

How to put PHP script in JS?

I have a page that allow users to access it. This page have certain things that not allow user to see that particular thing, For my case, user is unable to edit edit() or view this function, so I want to hide it by putting below code in JS because I am using function on this link.
I already enabled Session in PHP page like this <?php session_start(); ?>
And I try this putting this PHP in JS inside Datatables function. The dataTable function is working fine. Just the PHP is not working.
{ data : "project_id",
render: function(data) {
return "<span onclick='view()'></span> "+ // This is allow to user and admin level
"<?php
if ($_SESSION['user_privilege'] == 'Admin') { ?>
<span onclick='edit()'</span>
<?php } ?>"; // This is allow for admin level only
}
}
Check the following
<?php
if(isset($_SESSION["user_user_privilege"])){
echo "<script>
let button = '<span onclick='edit()'></span>';
</script>";
}else{
echo "<script>
let button = '';
</script>";
}
?>
Now check the button is empty or not.
{ data : "project_id",
render: function(data) {
return "<span onclick='view()'></span> "+ ((button!="") ? button : "");
}
}

Make a dialog box in my HTML page by some conditions

What I need to do.... In php-part of my login.php I check the user password and login this way:
<?php
// some code
session_start();
$query = "SELECT * FROM CRM.Users WHERE Login = '$l_username' AND Password = '$l_password'";
$result = mysql_query($query) or die ( "Error : ".mysql_error() );
while($row = mysql_fetch_assoc($result)){
...
if(mysql_num_rows($result) < 1){
// echo The password or login is wrong
</php>
In My HTML i have:
<div id="dialog" title="Basic dialog">
<p>The password or login is wrong</p>
</div>
And in my JS part I have:
function myfunction()
{
$( function() {
$( "#dialog" ).dialog();
} );
}
But when I bind MyFunction() with some test submit button (by onClick event) I see the DIV part in my page like common html text. But I dont want to see it while the condition wont true. So, My questions:
How I can realize the password/login check, throwing dialog box and when User click OK, i want to pull out user to index.php page
How I can hide the DIV for Dialog while condition is false
Here is the code for your problem:
<?php
if(mysql_num_rows($result) < 1) {
?>
<script>
$(function(){
myFunction();
});
</script>
<?php }?>
<script>
function myfunction()
{
$("#dialog").dialog({
resizable: false,
modal: true,
buttons: {
OK: function() {
$( this ).dialog( "close" );
window.location = 'http://localhost';
}
}
});
}
</script>
Your code is fine. It just needs some cleaning up:
<?php
if (!isset($_SESSION)) {
session_start();
}
$query = "SELECT *
FROM CRM.Users
WHERE Login = '".mysql_real_escape_string($l_username)."'
AND Password = '".mysql_real_escape_string($l_password)."'
LIMIT 1";
$resource = mysql_query($query) or die ("Error : ".mysql_error() );
// If there is one result, the login is successfull
if (mysql_num_rows($result) == 1) {
$record = mysql_fetch_assoc($resource);
$_SESSION['user'] = array(
'id' => $record['id'],
'username' => $record['Username'];
);
// Redirect
header("Location: secure.php");
exit;
}
?>
To check if a user is logged in:
if (!isset($_SESSION['user'])) {
header("Location: login.php");
exit;
}
Note: Others will probably complain about mysql_* functions not being secure. and they are right. These functions are deprecated. Instead I recommend using mysqli_*
Update
I forgot the part where the question was about hehe. Adding a dialog can be done very easily.
<script type="text/javascript">
if(!confirm("...")) return;
// redirect here
</script>

How to execute the code inside javascript confirm box

I have a JavaScript confirm box and i have some MySQL insert query code to be executed at some condition. This is how my code look like:
<?php
$id = $_POST['id'];
$name= $_POST['name'];
$query = mysql_query("select * from table where id='$id'");
$count = mysql_num_rows($query );
if($count!=0)
{
?>
<script type="text/javascript">
if (confirm("This seems to be Duplicate. Do you want to continue ?") == true)
{
//Execute/Insert into table as how it is given below
}
else
{
//Dont execute/insert into table but close the window
}
</script>
<?php
}
else
{
$queryinsert = mysql_query("INSERT INTO table(id,name) VALUES('$id','$name')");
}
?>
You can't execute MySQL or PHP command inside javascript, what you can do instead is to make a PHP function that you can call by Ajax. The best way is by using jQuery or by redirecting the page with your PHP function in URL.
<script type="text/javascript">
if (confirm("This seems to be Duplicate. Do you want to continue ?"))
{
$.ajax({
url: 'your_path_to_php_function.php',
type: 'POST', // Or any HTTP method you like
data: {data: 'any_external_data'}
})
.done(function( data ) {
// do_something()
});
}
else
{
window.location = 'your_url?yourspecialtag=true'
}
</script>
You're mixing serverside and clientside scrips. This won't work. You have to use AJAX, which are asynchronous server-client/client-server requests. I recommend jQuery, which is JavaScript which easily handles lot of things, including AJAX.
Run this if user confirms action
$.post("phpscript.php", {action: true})
Php file:
if ($_POST['action'] === TRUE) {
<your code here>
}

How to use ajax to scrape one page at a time, return the next page link and go again

Question:
I have a php scraping function and code that all works well, however it times out because its trying to load 60 different pages...
I was thinking of using AJAX to load one page at a time in a loop. Since i'm very new to AJAX im having some trouble.
This is what I have so far, I can get it to loop through the links if I provide them, however I want it to scrape page 1, return the next page link and then scrape the next page on a continuous loop until there are no more pages. As it stands it goes into infinite loop mode...
Any ideas guys?
Here is my code which i took from a youtube video which was using an array (i am only passing through a string)
<?php
ini_set('display_errors',1);
//error_reporting(E_ALL);
set_time_limit(0);
require_once 'scrape_intrepid.php';
//posted to this page
if(isset($_POST['id'])) {
//get the id
$id = $_POST['id'];
//this returns the next page link successfully, i just cant get it back into the function
$ids = scrapeSite($id);
echo $ids;
echo "<br>";
$data = $id . " - DONE";
echo json_encode($data);
exit();
} else {
$ids = 'http://www.intrepidtravel.com/search/trip?page=1';
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
function update() {
ids = <?=json_encode($ids);?>;
if(ids){
var id = ids;
$.post("index.php",{id:id}).done(function(msg){
console.log(ids,msg);
update();
});
} else {
console.log("done");
$("#log").html("Completed!");
}
}
$("#go").click(function() {
$("#go").html("Loading...");
update();
});
});
</script>
</head>
<body>
<button id="go">Go button</button>
<div id="log">Results</div>
</body>
Ended up solving this in another way: The function I am calling to function.php runs the script and returns the next URL to scrape. which is the msg value, so the refresh is called again once this is validated. Just processed 60 pages each taking 38 seconds each :S
<script>
$(document).ready(function() {
refresh('http://www.intrepidtravel.com/search/trip?');
function refresh(url) {
$.ajax({
type: "GET",
url: "function.php",
data: 'url=' + url,
success: function(msg){
$('#result').append('--->Completed! <br>Next Page: is ' + msg);
console.log(msg);
if ($.trim(msg) == 'lastpage'){
$('#result').append('--->Last page - DONE!');
}
else {
refresh(msg);
}
}
}); // Ajax Call
} //refresh
}); //document.ready
</script>
And the function.php file:
require_once 'scrape_intrepid.php';
if ($_GET['url']){
$url = $_GET['url'];
if ($url=="lastpage"){
echo $url;
} else {
$nextlink = scrapeSite($url);
echo($nextlink);
}
}

There is no alert when submitting a form using ajaxForm plugin

How can I have an alert that the form has been submitted successfully? I have already tried to look at the page of the plugin still come up empty handed.
This is the code I have tried so far maybe there is something wrong with my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms but the alert that suppose to appear after successfully submitted the form is missing for some reason.
This is the script that the form uses when submitting:
<?php
$title=$_REQUEST['articletitle'];
$articlemore=$_REQUEST['editor1'];
include "connection.php";
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$type=$_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO blog(articletitle, articleimage, articlemore) VALUES ('$title', '$data', '$articlemore')";
$results = mysqli_query($link, $query);
if(!$results)
{
echo "Saving Post Failed";
}
else
{
echo "You have a new Post!";
}
}//end if that checks if there is an image
else
{
echo "No image selected/uploaded";
}
// Close our MySQL Link
mysqli_close($link);
?>
Here is the Syntax
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
I hope this will help you
Change this:
$('#f1').ajaxForm({
to
$('#f1').ajaxForm(function(){

Categories

Resources