index.html
<script>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
<input type="text" size="3" name="id"><br />
<button onclick="check();">Pay</button>
<div id="result"></div>
ajax.php
<?php
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "<script language=JavaScript src='https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc'></script>";
I try to form javascript in php file and embed it into div with id="result".
I've used get, load, ajax, createElement methods but the script doesn't execute.
try this..
$('#result').load('ajax.php');
In your php file ajax.php include the header.
header('Content-Type: text/javascript');
And in index.html add type=”text/javascript” to the script tag.
<script type=”text/javascript”>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
You must load script as real script element. DOM conversion of "<script>/*...*/</script>" may fail in this case. This is done via standart DOM document.createElement function.
var script = document.createElement("script");
script.src = path;
Other way is to download the script via AJAX and then eval it.
Try using getScript:
$.ajax({
url: url,
dataType: "script",
success: success
});
try this:-
"<script language=JavaScript src='https://*****/index.php?id="'.$id.'"&invoice="'.$invoice.'"&sum="'.$sum.'".......etc'></script>";
Why wouldn't you load directly the script URL using AJAX?
ajax.php only should return path to the script:
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc";
Besides that all HTML element attributes should be enclosed with quotes or apostrohpes.
Then you should load this url in javascript and generate script element here:
function loadScript(url,appendTo) {
var script = document.createElement("script")
script.type = "text/javascript";
script.src = url;
if(typeof appendTo.appendChild == "function") //Chceking if we can append script to given element
appendTo.appendChild(script);
else
document.body.appendChild(script) //This will not work in old IE, where document.body is not defined.
}
You call this function with script url and optional target element (where will be put in) as parameters.
Like this:
$.get("ajax.php",{param1:"value"},function(scriptUrl) {loadScript(scriptUrl, document.getElementById("result");})
Related
currently, I am trying to set the URL of my website base on what the user click. The website is coding in html and php and this is the code I am trying to use to set the Url. However it seems that windows.location doesn't recognize php code. is there any other way to do this?
<script>
$(document).ready(function(){
$("#HELP").click(function(){
window.location='hotels.php?Category=<?php $cat ?>&Pic=<?php $img ?>';
});
});
</script>
You forgot to echo the variables to the output:
window.location='hotels.php?Category=<?php echo $cat ?>&Pic=<?php echo $img ?>';
Variables by themselves don't emit anything to the page. They simply represent a value.
Try this:
<script>
$(document).ready(function(){
$("#HELP").click(function(){
var url = 'hotels.php?Category=<?=$cat?>&Pic=<?=$img?>';
window.location= url;
});
});
</script>
What change:
Echo php veriables in url
But its not a good practice to use php code in client side you can create global veriables in java script.
Or if your requirement is like that than you can also use a hidden value for url in html and than get value in your jQuery code as like that:
<input type="hidden" id="url" value="<?=hotels.php?Category=<?=$cat?>&Pic=<?=$img?>" name="url">
<script>
$(document).ready(function(){ $("#HELP").click(function(){
var url = $('#url').val();
window.location= url;
});
});
</script>
I'm newbie at Jquery. I stacked to passing php $_GET['myvalue'] to my jquery file.
I struggled very much but I cannot find solution.
I have different one php file and one jquery file. I call my php file like
myphpfile.php?myvalue=testvalue
Then I want to receive myvalue's value to my jquery file. I tried document.getElementById but It doesnt work.
For any helping Thanks.
If you want to access the $_GET['myvalue'] value in your Javascript you can echo it out straight into it.
<script type="text/javascript">
// Your code
// The var you want to assign it to
var value = '<?php echo $_GET['myvalue'];?>'
</script>
Try this in your jQuery File:
First create a function to parse the parameters in the URL:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
Then you call the function:
var myUrlParameters = getUrlVars();
Then you can access them with:
var myParameter = myUrlParameters['myParameter'];
You need to read more about jQuery and Javascript...
You might want to add the variable you want in an HTML element, for example:
PHP
<?php
$myValue = $_GET["myvalue"];
echo '<input type="hidden" name="_method" value="'.$myValue.'" id="myElement" />';
?>
At jQuery:
$(document).ready(function(){
alert($('#myElement'));
});
If you want to access the $_GET['myvalue'] value in your script but using only Javascript.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
My problem with the javascript file run through the AJAX call is
for example :
index.php
$(function(){
$(".btn-ajax").click(function(){
$.getJSON('ajax.php',function(data){
jsInc(data['js'][0]['src']);
$("#response").html(data['html']);
});
});
function jsInc($src){
var head = document.getElementsByTagName("head")[0];
var script=document.createElement("script");
script.type='text/javascript';
script.src = $src;
head.appendChild(script);
}
ajax.php
$arr['js'][] = array('src'=>'js.js');
$arr['html'] = '<input type="button" class="btn" value="show message"/>';
echo json_encode($arr);
js.js
$(function(){
$(".btn").on('click',function(){
alert("test !");
});
});
but when execute ajax request and append input button to the index.php file this button click event not worked!
please help me
Thanks
You want to get script via AJAX right? You can use $.getScript:
$.getScript("script.js");
Load a JavaScript file from the server using a GET HTTP request, then execute it.
I think what's happeneing is your first loading the JS which binds the click listener and then loading the Button. SO the listener doesnt get bound
Try reversing the order like:
$("#response").html(data['html']);
jsInc(data['js'][0]['src']);
Try rebinding the click function after the Ajax call (success):
$.ajax({...
success: function(data) {
$(".btn").click(clickFunction);
}
});
$(".btn").on('click', clickFunction);
function clickFunction() {
alert("test !");
}
You need to change your function in js.js to be a delegate function.
$(function(){
$('body').on('click','.btn',function(){
alert("test !");
});
});
When you do it this way. The .btn element doesn't even need to be present before the script is run. It attaches the event to the body tag prior to checking if the .btn element exists.
How can I add redirect URL link to JS function (example form action to : session.php) in below code.
I've tried with another way code, but it still can't function.
$(document).ready(function() {
$("#submit_butt").click(function() {
var conf = {
frequency: 5000,
spread: 5,
duration: 600
};
/* do your AJAX call and processing here...
....
....
*/
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Invalid username or password!</p>');
// clear the fields to discourage brute forcing :)
$("#password").val("");
document.forms['login_form'].elements['username'].focus();
});
});
You can try this
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
https://developer.mozilla.org/en-US/docs/DOM/window.location
Ref: How to redirect to another webpage in JavaScript/jQuery?
you can use this..
window.location.href = "http://www.google.com";
you can try
<script>
function name(){
window.location ='abc.php';
}
</script>
you can by breaking into php code inside your javascript
$(document).ready(function()
{
<?php
someFunction();
?>
});
but only if your javascript is in a php file so it can be processed by php. So if your linking to a .js file that needs to be changed to .php
I have a list list of checkbox with name of files that came froma DB. Then I have button for delete the files. I have the following code for the button:
<input type='button' id='submit_btn' onclick='eraseFile()' value='DELETE FILES' />
and the eraseFile function
...
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
<?php
echo "HElllo World";
?>
}
</script>
It gives an error "missing ; before statement" and "eraseFile is not defined"
Is it possible to write php inside javascript right??
Is it possible to write php inside javascript right??
Unless the PHP code is generating valid JavaScript, then no.
The reason eraseFile is being called undefined is that your echo statement is causing a syntax error since it is printing the string literal Hellllo World at the end of the JavaScript function which violates JavaScript syntax rules.
Yes, it is possible.
PHP is parsed on the server, so you will literally be printing "HElllo World" inside your javascript function, which would probably cause an error.
You might be looking do do the following:
<?php echo 'document.write("Hello World!");'; ?>
Your PHP output gets appended to your JS function making your javaascript look like this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World //syntax error here
}
</script>
You can do this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
alert("<?php echo "HElllo World"; ?>");
}
</script>
This will give a pop-up saying 'Hello World'
To pass a value from your Javascript function to your PHP script, you can do this:
var yourJsVar = {assign value here};
url = "yourPHPScript.php?value=" + yourJsVar;
if (window.XMLHttpRequest)
{ // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = someFunction;
//someFunction will get called when the PHP script is done executing
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject)
{ // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = someFunction;
req.open("GET", url, true);
req.send();
}
}
In your PHP script:
$yourPhpVar = $_GET['value'];
I mentioned someFunction above that gets called after the PHP script completes execution. This is how it should look. (Note that this is on your Javascript)
function someFunction()
{
if(req.readyState == 4 && req.status == 200)
{
//this will only execute after your AJAX call has completed.
//any output sent by your PHP script can be accessed here like this:
alert(req.responseText);
}
}
Try to echo a meaningful javascript code, "Hello World" it's not a valid JS statement.
Try something like
<?php
echo "alert('HElllo World');";
?>
Where is your eraseFile function defined?
if it is not defined until after the place it is called, you will get that error.
Side note:
You can have php echo inside of the javascript, except what you have there will not do much...
Yes, you can use PHP code in you script files, but your code generate invalid script code here.
<?php
echo "HElllo World"; // becomes: HElllo World (text!) in JS
?>
It is possible to write PHP in Javascript, but it is not the best pratice. The way we normaly do this is through AJAX read the documentation : http://api.jquery.com/category/ajax/
Yes, it is possible to include PHP inside JavaScript, since the PHP will be executed on the server before the page contents are sent to the client. However, in your case, what is sent is the following:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World
}
</script>
This doesn't validate as JavaScript, since the "Helllo World" is not a valid JavaScript command. This is why the function isn't being defined properly. You need to replace the "Helllo World" string with an actual JavaScript command.