Ajax and rewrite engine - javascript

I have a problem with ajax and rewrite engin. I made a site, where I use this load more script:
http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html
Everything works fine on users profile page (I am getting posts from users feedback), when the url looks like this: example.com/user.php?u=ExampleUser
but I have this in .htaccess:
RewriteRule ^u/(.*) user.php?u=$1 [L]
So if I type something like example.com/u/ExampleUser I get the username like:
$username = $_GET['u'];
But in this way when I click on the load more it doesn't load more posts from the user, it just starts to lead the site itself to the div box (like it is an iframe...).
Please help me, it is necessary.
Here is my script, which should load more info from MySQL database($id is userid from DB):
$(function() {
// More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: 'lastmsg='+ID+'&user='+<? echo $id; ?>,
cache: false,
success: function(html) {
$("#container").append(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});

Not knowing the entire context of your code, it looks like when the ajax call is made, the final url is something along the lines of domain.tld/u/ajax_more.php.
I get around this issue by maintaining a list of constants in the javascript object.
For example, I have a paths.php file that contains this:
<?php
header("Content-Type: text/javascript");
echo "
myNamespace.paths = {
RELATIVE_FOLDER: '<?=RELATIVE_FOLDER?>',
// add more as required...
}
";
?>
This is included in the page just like a regular script (with script tags), and from that point forward, myNamespace.paths will contain your constants, as returned by the server.
In my case, if the URL was "http://www.example.org/path/to/my/dev/env", I would have RELATIVE_FOLDER set to /path/to/my/dev/env/ on the server-side, which would then be included into the paths object.
Later, in your ajax calls:
$.ajax({
type: "POST",
url: myNamespace.paths.RELATIVE_FOLDER + "ajax_more.php",
// ... everything else
});
I notice you have no problem with directly injecting PHP into your scripts. This is not necessarily a bad thing, but it does make it harder for you to minify your js. This is the reason why I went with a separate file to store the constants, instead of directly injecting it into the javascript itself with <?= ... ?> tags.

Related

AJAX returning current page when trying to execute separate PHP query

Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});

How to write php include inside div with jquery

I need to write <?php include $this->_ script('admin/test.phtml'); ?> Using jquery within a <div> so that it works.
I have already researched and in all the responses recommend using load("file.php"), but it does not work in my case, because it is a framework and because of the routes this does not work.
I tried this and it did not work, it does include inside the script instead of doing in div:
<script>
$('.btn-group').on('click', '#btn-edit', function(e) {
e.preventDefault();
var id = $(this).attr('data-id');
$('#myModal').modal({
backdrop: 'static'
});
<?php $_GET['id'] = id;?>
var php = "<?php include $this->_script('admin/teste.phtml') ?>";
$('.modal-body').html(php);
});
</script>
I tried this code and it also did not work:
<script>
$('.btn-group').on('click', '#btn-edit', function(e) {
e.preventDefault();
var id = $(this).attr('data-id');
$('#myModal').modal({
backdrop: 'static'
});
<?php $_GET['id'] = id;?>
var php = "include $this->_script('admin/teste.phtml')";
$('.modal-body').html('<?php' + php + '?>');
});
</script>
The only way to get something like this to work is using jQuery to request the page back to the server to get the server processing PHP again.
However, as you've found, loading just the file doesn't work because the file likely included dependencies that are not present.
The way I would solve this problem (I happen to be using WordPress which might change your specific application of my answer) is this:
jQuery:
jQuery('.btn-group').on('click', '#btn-edit', function(e) {
jQuery.ajax({
type: "POST",
url: "/", //Or whatever the page you want to use to load this.
data: {"custom_php_action": "my_special_action"},
tryCount : 0,
retryLimit : 3,
success: function(res){
jQuery(".modal-body").html(res); //Div for my response
},
error: function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
jQuery.ajax(this);
return;
}
return;
}
}
});
});
PHP (This is where whatever you are using to build your page will change):
function my_custom_controller_function() {
if ( isset($_POST['custom_php_action']) && $_POST['custom_php_action'] == 'my_special_action' ) { //Tests for our AJAX conditions
//My Code Here -- Make sure whatever response is echoed and not simply returned.
//If the function returns a value, then echo it here.
//Example
echo 'My Response';
//Example
//Example 2
$data = my_function();
echo $data;
//Example 2
exit(); //Stop the rest of the page from loading.
}
}
add_action( 'wp', 'my_custom_controller_function' ); //Control when AJAX kicks in -- we don't want it firing too soon -- or too late.
This uses a WordPress action hook that fires after WordPress and plugins are loaded, but before any theme files have been processed (if I understand my hook order correctly). Depending on your framework will depend on how you include the code you are wanting to use.
This is how I have solved dynamic loading of information. Hopefully you can piece together a solution from this example that will work for you since I don't know the class/object combination you are using to locate the document you're trying to load/include and I don't know what the details of the platform you're building upon.

Php function call from Javascript function using ajax

Hello everyone I am new to php.
I have been trying out this thing when a user enter a product name need to validate that the product is valid or not.
For that purpose I have used onchange event when the text is entered.The onchange function will call the javascript function.From javascript function I am calling the php which is in the same file.So when I am entering the product name somehow the php function is not working.
Here is my code :
<?php
include 'conf.php';//it contains the php database configuration
session_start();
$quantityRequired=0;
$productName_error="";
if(is_ajax()){
if(isset($_POST["productName"])){
$productName=$_POST["productName"];
$row=mysqli_query($conn,"SELECT * from OrderDetails where ProductName='".$productName."'");
if($row)
{
$result=mysqli_fetch_assoc($row);
$quantityRequired=$result["Quantity"];
}
else
{
$productName_error="The product name is not valid or product does not exist";
echo $productName_error;
}
}
}
function is_ajax() {
$flag=(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
return $flag;
}
?>
<html>
<head>
<title>Order Page </title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="userName">Username</label><br>
Product Name<input type="text" name="productName" id="productName" onchange="validateProduct()"><?php echo $productName_error?><br>
Quantity Required<input type="text" name="quantityRequired" id="quantityRequired"><br>
Availability<input type="text" name="availability">
<p id="demo"></p>
</form>
<script>
function validateProduct()
{
$.ajax({
type: "POST"
});
}
</script>
</body>
</html>
so the code is when the user enters the product name.The function validate product is called.From validate product it will call the php which is in the same file. is_ajax() function is used to check whether it is the ajax request or not.
A PHP library for Ajax
Jaxon is an open source PHP library for easily creating Ajax web applications. It allows into a web page to make direct Ajax calls to PHP classes that will in turn update its content, without reloading the entire page.
Jaxon implements a complete set of PHP functions to define the contents and properties of the web page. Several plugins exist to extend its functionalities and provide integration with various PHP frameworks and CMS.
How does Jaxon work
Define and register your PHP classes with Jaxon.
$jaxon->register(Jaxon::CALLABLE_OBJECT, new MyClass);
Call your classes using the javascript code generated by Jaxon.
<input type="button" onclick="JaxonMyClass.myMethod()" />
check link https://www.jaxon-php.org/docs.html
There may be other problems I haven't spotted, but the first thing that jumps out to me is that your server-side code runs conditionally:
if(isset($_POST["productName"]))
And that condition was never satisfied because you didn't send any values in the AJAX request:
$.ajax({
type: "POST"
});
Send the value(s) you're looking for:
$.ajax({
type: "POST",
data: { productName: $('#productName').val() }
});
You may also need to specify a couple other options if they don't default correctly. Explicit code is generally better than implicit in many cases:
$.ajax({
url: 'yourUrl.php',
type: "POST",
dataType: 'html',
data: { productName: $('#productName').val() }
});
In general you'll probably want to check the documentation for $.ajax() and see what you can and should tell it. You'll also want to take a look at your browser's debugging tools to see more specifically why and how it fails when testing these things.
Speaking of things you should do, you should read this and this. Your code is wide open to SQL injection attacks at the moment, which basically means that you are executing as code anything your users send you.
var data1 = "Something";
$.ajax({
url: "script.php",
type: "POST",
data: { data1: data1 }
}).done(function(resp) {
console.log( resp )
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus + " - Please try again.")
})
Here you have a script that will send the data1 variable across to the php script. The resp in the done portion is the return you send back from the php script.
If you want to send more data just add it { data1: data1, data2: data2 } and so on.
Just adjust to suit your needs.

How to convert javascript variable into php variable?

Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
<?php
include "accounts/config.php";
$phpvar='"+str+"';
mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')");
//echo $phpvar;
?>;
})
});
As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({
"savesample.php",
{myPostVar: str}
}).done(function() {
alert("sample saved.");
});
Of course you need a serverside script to handle this request:
<?php
$yourVar = $_POST["myPostVar"];
// TODO use mysqli::escape_string or similar!!
mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script>
<![CDATA[
var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
CORS
SQL injection
Authenticated AJAX calls
You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.
Look up Jquery post for more information.
The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.
On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!
So for instance (using JQuery)
$.ajax({
url:"someurl",
type:"POST or GET",
data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
datatype:"JSON", //This is the return type of the information you want if any
success: successfulHandlerfunction()
error: errorHandlerfunction()
});
That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/
I hope this helps!
JS
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
$.ajax({
type: "POST",
url: "save.php",
data: {items: str},
success: function(responce) {
alert(responce);
}
});
});
Create save.php file
<?php
include "accounts/config.php";
$items = $_POST['items']; // Validation HERE!!!
foreach ($items as $item) {
// Insert to DB
}
echo 'Saved';
?>
Separate languages = separate files. (if you can...)
In PHP always check user input.
Use PDO.
This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:
Client(browser):
$.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
alert("Variable was successfully sent.");
}});
Server(Apache)
config.php
<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

Use PHP for Cross Site Loading of HTML Content [duplicate]

This question already has answers here:
Loading cross-domain endpoint with AJAX
(9 answers)
Closed 8 years ago.
Maybe a stupid question, but I'm wrecked from this issue.
The issue: cross domain loading of webpage via javascript and having access to variables and elements within
Theoretical solution:
Send an ajax request to a local php file with the requested URL as a parameter
Get the PHP file to load the page
Display the loaded page and have access to the elements in a box specified
Before I endeavor, is something like this possible or worth the work involved? I am familar with PHP Simple HTML DOM Parser.
Thanks in advance, have spent quite some time on this issue already.
Update
First, the javascript:
function loadTheUrl(x){ // x = the url, e.g. http://example.com
$.ajax({ url: 'loader.php', // explained below
data: {url: x},
type: 'get',
success: function(output) {
$('.loading-space').html(output);
}
});
}
This calls a local PHP file called loader.php
loader.php
<?php
echo file_get_contents($_GET['url']);
And that's it. This works, but it actually gives me some issues with CSS that I am trying to figure out. The CSS is overriding my site too.. I'd like to keep the CSS, but limit it to within that div.
Update
A semi-working example. Only works in Chrome due to data:text/html.
HTML
<div value='http://example.com' onClick='javascript:loadURL(this)'>Click Here</div>
JavaScript
function loadURL(x){
var xURL = $(x).attr('value');
$.ajax({ url: 'load.php',
data: {url: xURL},
type: 'get',
success: function(output) {
$('.page-loaded').attr("data", "data:text/html,"+output); // .page-loaded is an HTML object element
}
});
}
load.php
<?php
error_reporting(0);
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents($_GET['url']));
echo $doc->saveHTML();
Just curious as to why the downvotes are coming in. I would have thought this issue would have been more widespread? Thanks
Update
PHP way doesn't allow to access elements. CORS seems the only way to go. Just need to limit CSS to within the box.
Is this what you are looking to do?
<script>
$(function(){
$.get("youFile.php", function(data){
$("#container").html(data);
});
}):
</script>
You could use DOMDocument, find all the script and link tags, remove them, and spit out the HTML:
<?php
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents($_GET['url']));
$internal_css = $doc->getElementsByTagName('style');
foreach ($internal_css as $css) {
$css->nodeValue = "#container_id " . implode(" #container_id ", explode("}", $css->nodeValue));
}
echo $doc->saveHTML();

Categories