Creating jQuery Validation rules using PHP - javascript

I am using the jQuery Validation plugin. Per, http://jqueryvalidation.org/remote-method, a callback is used to send extra data (i.e. username).
var myObj={
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
}
}
}
}
}
};
$( "#myform" ).validate(myObj);
Works perfect! But now, I don't wish to hardcode the myObj object, but use PHP to create it. Note that my example script below is extra simple and doesn't address the validation plugin.
One way to do so is to directly create the JavaScript as I did so for myObj1. However, I have been told that one should never dynamically create JavaScript using PHP due to security and troubleshooting issues. Instead, I should just pass JSON from the server to the client.
So, I tried to do so for myObj2, however, evidently JSON cannot contain JavaScript, and it doesn't parses.
What is the best way to dynamically create jQuery Validation rules using PHP?
<?php
$myID='myID';
if(isset($_GET['task'])) {
header('Content-Type: application/json');
exit("{'data':{'getValue':function() {return $( '#{$myID}' ).val();}}}");
}
else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
<script>
console.log(window,location);
<?php echo("var myObj1={'data':{'getValue':function() {return $( '#{$myID}' ).val();}}}");?>
$(function() {
alert(myObj1.data.getValue());
$.get(location.href+'?task=getJSON',function (myObj2){
alert(myObj2.data.getValue());
},'json');
});
</script>
</head>
<body>
<input id="myID" type="text" value="Hello" />
</body>
</html>
<?php
}
?>

"What is the best way to dynamically create jQuery Validation rules using PHP?"
There is no "best" way. Since the PHP constructs the page (incl the JavaScript) on the server and the jQuery Validation plugin only runs in the browser, I don't understand your issue. How could using JavaScript's ajax to retrieve the parameters be more secure than just using a PHP echo to put those parameters into the page in the first place, before it's sent to the browser?
No matter how you construct your page, the JavaScript code will/should look exactly the same when it gets to the browser.
<script>
$(function() {
$( "#myform" ).validate( <?php echo .... ;?> );
});
</script>

Related

How to convert JavaScript variable into PHP through ajax

its the code for posting a javascript variable into php...
but its not working..sugesstion...
i want to take value of id from javascript and post into a php.
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("form").submit(function() {
var id = $("input[type=submit]").attr('id');
alert(id);
$.ajax({
type: 'post',
url:('abcde.php')
data: {id1: id},success: function(response){}
alert(id1);
});
});
});
</script>
</head>
<form action="abcde.php" method="POST">
<!-- other form fields -->
<input type="submit" id="a" name="idVal" value="a">
</form>
</body>
</html>
<?php
if(isset($_POST['id']) ){
$id=$_POST['id'];
echo $id;
}
?>
ohh boy, 1st: it's
data: {'id': id}
secondly, your code is really wrong on this part, you are not doing anything in success, and you just randomly put an alert() in, with a variable that doesn't even exist.
So instead of success: function(response){}, it should be success: function(response){alert(response);} and forget about the alert(id1);
Other errors I saw from looking at it quickly: you are submitting your form from AJAX and HTML as well. You should block the default behavior with a function at the beginning of .submit(funcition() {...}. There already is a function for that, but I can't remember.
Lastly, you are sending the form data to the same page you are submitting from. You will get an answer from AJAX with the same page you are looking at. You should extract the php code to a different file and make abcde.php a simple abcde.html file.
One last thing: instead of alerts, you should use Console.log and watch the browser's console for debugging. You will see a bunch of errors, which makes debugging a lot easier.
You should, instead of blindly coding, be more mindful about what is responsible for what. You should be thinking more about the side-effects of you are introducing to your code. This will come with experience, we've all been there. Make sure one 'thing' is only responsible for ONE task.

Get a javascript derived dom-tree element

My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents.
I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead.
There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes).
<!doctype html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function ok {
alert "OK";
}
function get_html (my_html){
alert "OK";
var l = document.getElementById('my_link').value;
alert l;
alert my_html;
var url = my_html;
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
var f = fs.open("testi_kalenteri.html", "w");
f.write(data);
f.close();
alert "data saved";
}
});
}
</script>
</head>
<body>
<p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p>
<p id ='ok' onclick='ok()'>show ok</p>
</body>
</html>
Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe.
And that iframe points to that location :
http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget
Which is in fact the real source of the calendar...
EDIT following your comment on this answer
Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192
If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side).
From this asumption, I inspected the source code (again).
In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for
calls to server (everything but calls to resources : images, stylesheets...).
I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192&currentMonthFirstDate=&duration=7.
I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such).
I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js.
It contains the code that generates asynchronously the calendar.
tl;dr
The calendar is indeed generated asynchronously.
You can't get the full html with a curl or file_get_content in PHP and
you can't access it with ajax code (due to Same-origin policy).
By the way, you should contact the site to see if you can access their api via PHP with their consent.
Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery):
<div id="calender"></div>
<script>
$("#calendar").click(function(){
alert('calendar was clicked');
});
</script>
If I understand you correctly. I think you need appropriate php respond with some correct code inside php file:
// json_handler.php
<?php
if (is_ajax()) {
$return = $_POST;
$return["ok"]="ok";
$return["json"] = json_encode($return);
echo json_encode($return);
}
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
and this is script wich is inside html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<a id="click">click</a>
<script>
$("document").ready(function(){
$("#click").click(function(){
var data = {
"request": "request"
};
data=$.param(data);
// alert(data);
$.ajax({
type: "POST",
dataType: "json",
url: "json_handler.php",
data: data,
success: function(data) {
// here you will see echo respond from your php json_handler.php
// also you can add here more javascript (jquery code) to change your page after respond
alert();
}
});
return false;
});
});
</script>
<body>
<html>
http://www.w3schools.com/jquery/jquery_ajax_intro.asp

Setting PHP variable in <noscript>

Something like the below does not work:
<?php $nojs = false; ?>
<noscript>
<?php $nojs = true; ?>
</noscript>
As the PHP is executed regardless if JS is enabled or not. But is there a way to get a similar effect? I'm trying to set a flag if JS is disabled and then display parts of the page accordingly.
PHP is executed before javascript, so you cannot do this. You can do something such as executing a basic ajax request and storing hasjs in a session variable once the ajax page is successfully queried. You wouldn't know if it's just the fact that the ajax request wasn't successful due to something else, or if they have Javascript disabled.
Lets give this a shot anyway:
The jquery script in your head tags
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$.get( "hasjs.php", { hasjs: "1"} );
});
</script>
The PHP file (hasjs.php)
<?php
if(isset($_GET['hasjs']))
{
session_start();
$_SESSION['hasjs'] = 1;
}
?>
Then you can access the session variable to determine if they have JS based off the ajax query. Nothing stopping the user from visiting that page though if they don't have JS installed.

Trouble combining jQuery and .php in Wordpress

I am trying to make a simple translation site here:http://traductordeinglesaespanol.co/. I created a simple php code that uses get to an external translation api which works fine. Here's the code:
<?php
if(!empty($_GET['text'])){
$trans_url ='http://api.mymemory.translated.net/get?q='.urlencode($_GET['text']).'&langpair=en|es' ;
$trans_json = file_get_contents($trans_url);
$trans_array = json_decode($trans_json, true);
echo $trans_array['responseData']['translatedText'];
}
?>
Here is the simple html form:
<form id="form" method="get" action="tran.php">Enter Text to be Translated below:
<input name="text" type="text" id="test" />
<button id="but">Translate</button></form>
<div class="results"></div>
The translation works ok now but I what I would like to do is to grab the tran.php result using jQuery and show it in the "result" class below the form. I am trying to do this by the following:
I loaded by editing the functions.php file so it loads jQuery and a .js script named tran.js. When I inspect element I see both jQuery and the script being loaded. In the script I put this basic code:
jQuery(document).ready(function(){
$('#go').click(function() {
$.ajax({
type: 'GET',
url: 'tran.php',
success: function(data) {
$('.result').html(data);
}
});
});
});
and change action to to handle the form from this page. (tran.php is in the root directory.) But it isn't working at all. I suspect there is/are some crucial mistakes in the coding but being a complete beginer I cannot find where the mistakes are so any advice/correction would be greatly appreciated!
I somehow managed it to work! There was a small typo:
data : 'text=' + to_be_translated;
I replaced the ";" in the end with a comma and now I am getting the result like this: Let's say I input the text name to translate (nobre in spanish!), I get this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>estes</title> </head> nombre
So I have to get rid of these headers somehow! Anyway I want to thank you again very much for your help! Gracias!
You should use ajax this way :
var to_be_translated = "Hello";
$.ajax({
type: 'GET',
url: 'tran.php',
data : 'text=' + to_be_translated,
success: function(data) {
$('.result').html(data);
}
});
Here I added the "data" label, it says the JS variable to_be_translated will be seen as $_GET['text'] in PHP.

can i separate JavaScript If condition?

in PHP we can put HTML between codes like this:
<?php
if (condition) {
?>
<p>True</p>
<?php
} else {
?>
<p>True</p>
<?php
}
?>
can we do this in javascript ? like this ?
<script language='JavaScript'>
if (condition) {
</script>
<p>True</p>
<script language='JavaScript'>
} else {
</script>
<p>True</p>
<script language='JavaScript'>
}
</script>
There's something like this that has the effect you posted (maybe not your intention though, it's hard to say), but I wouldn't do it.
<script type="text/javascript"> //language == deprecated!
if (condition) {
document.write('<p>True<\/p>');
} else {
document.write('<p>True<\/p>'); //maybe False here?
}
</script>
But again this is just a demonstration of the effect, try to avoid document.write (it' a blocking operation) whenever possible.
Update: Edited based on comments below to make this example you shouldn't use! valid, but you shouldn't be copy/pasting it in the first place...
No. Browsers will output things in order that it sees them, without considering any conditions of other media on the page.
This works in PHP because the PHP interpreter interprets your code before sending the output to the client browser window. In other words, the actual HTML document being sent to the client is parsed and computed before being sent to the requesting browser. With Javascript mostly being a client-side scripting language this method is not possible, since you already have your HTML document generated from a server-side language such as PHP. You can manipulate the document in other ways using Javascript, with technologies such as Ajax and the DOM.
not that i know of, but for php do this instead
<?php if (condition): ?>
<p>True</p>
<?php else: ?>
<p>False</p>
<?php endif; ?>
=)

Categories