I have a php file that returns a result that is JSON encoded. Im using:
$.GET("thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});
"thephpfile.php" is in the same folder as the javascript page. Currently, I get a blank page. But when I add full path it works like this:
$.GET("http://locahost/thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});
How do I fix this issue?
Please use following code for the solutions.
<?php
define("ROOT_WWW","http://".$_SERVER['HTTP_HOST'] ."/yourprojectname/");
?>
<script type="text/javascript">
var ajax_folder="<?= ROOT_WWW ?>";
</script>
$.GET(ajax_folder+"thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});
$.GET("/thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});
Related
I am trying to post a form through AJAX jQuery. The PHP script to which it points returns a JSON encoded array. But, at the receiving end on the main page JSON.parse() is not working.
Please suggest if I am missing on some file types which need to be included
Here is my code.
< script type = "text/javascript" >
$(document).ready(function() {
$("#send").submit(function() {
//$("#submit_form").html('');
$("#modal-text2").html("<img src=" + "img/loader1.gif "
+ "/></br</br><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>");
$("#myModal2").modal('show');
$.post($("#send").attr("action"), $("#send").serialize(), function(data) {
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
});
//Important. Stop the normal POST
return false;
});
});
< /script>
The JSON encoded array which is being sent back by the PHP script is:
{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}
don't know if its the cause of hte problem or if its just a typo in here, but you have a typo in the following line:
<img src="+"img/loader1.gif "+"/></br</br>
you aren't closing the first linebreak, and the slash should come after the br - also not sure why you have so many quuotes in that html block - it should be :
$("#modal-text2").html("<img src='img/loader1.gif'/><br/><br/><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>")
You should console.log(data) to check if the data value has any problem.
use try/catch to catch message if error happened in JSON.parse.
try {
var decode = JSON.parse(data);
}catch(e){
console.log(e) ;
}
Make sure your php responses the json in the right way. Or there may have some invisible character and make the problem.
<?php
$data = ... ;
header('Content-type:application/json;charset=utf-8');
echo json_encode($data) ;
?>
I thought there is a sytax error in your script just check it out in the last line of script the closing tag of < /script> has space, remove it and try -
</script>
i execute the parsing snippet of your code it is working fine.
var data = '{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}';
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
I'm trying to pass a javascript variable to php on the same page. I tried some code but nothing worked.
The current code looks like this:
function init(e){
$('#DeleteDaily').click(function() {
d = document.getElementById("DailyRequestsList");
selected = d.selectedIndex;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "index.php?i=" + selected, true);
xhttp.send();
});
}
$(document).ready(init);
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}
?>
});
});
If I try to use Index as an argument for a python script it should delete an entry in a textfile and an element from a select object should be deleted on the website which doesn't happen. The python script itself works fine.
But I don't know why the variable isn't passed to php.
You can't just "mix" javascript and PHP like you're doing.
If that is inside a web page, the PHP code will be rendered (in your case, it will return nothing), and the page will just interpret an empty javascript function.
You need that PHP to be on the server, or turn it into javascript...
you can done it by
PHP Code
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}else{
$Index='';
}
?>
Javascript code
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
var index = '<?php echo $Index;?>';
if(index == ''){
//put your code
}else{
//put your code
}
});
});
.php
<?php
$timeArray = [355,400,609,1000];
$differentTimeArray = [1,45,622, 923];
?>
<script type="text/javascript">
var i=0;
var eventArray = [];
function generateArray(arrayName){
eventVideoArray = <?php echo json_encode(arrayName); ?>;
var vid = document.getElementById('my_video');
vid.currentTime = eventVideoArray[i];
}
</script>
<button onClick="javascript:generateArray(timeArray)"><button>
Currently I can get the function to generate the desired output by making generateArray have no arguments and replaing arrayName with $timeArray.
i.e. Working Code
<script type="text/javascript">
var i=0;
var eventArray = [];
function generateArray(){
eventVideoArray = <?php echo json_encode($timeArray); ?>;
var vid = document.getElementById('my_video');
vid.currentTime = eventVideoArray[i];
}
</script>
I want to use generate function to call on many different Time arrays, so getting JS to call directly from the php array would make coding much easier. Any help would be much appreciated.
Thanks!
[SOLVED]
Hi there,
Not sure about the comments regarding php not being able to run, I had a working example on my IIS just not quite flexible enough.
I solved the issue by rewriting the button in html. Now I can add new time arrays to video using the same function.
Thanks for the help.
<?php
$timeArray = array();
$timeArray[] = 345.1;
$timeArray[] = 789.1;
$timeArray[] = 1002.1;
$timeArray[] = 1200.12;
$differentArray = array();
$differentArray[] = 1500;
$differentArray[] = 1700;
?>
<script type="text/javascript">
var i = 0;
var eventVideoArray = [];
function generateArray(arrayName){
eventVideoArray = arrayName;
var vid = document.getElementById('my_video');
vid.currentTime = eventVideoArray[i];
}
</script>
<button id="goToTime" onClick="javascript:generateArray(<?php echo json_encode($timeArray); ?>)">timeArray</button>
<button id="goToTime" onClick="javascript:generateArray(<?php echo json_encode($$differentArray); ?>)">differentTimeArray</button>
PHP runs on the server and JS runs on the client. You want the client to call the server for the values for the array you will need an Ajax call or print the values directly to the JS (as already done on your code).
Depending on the project making an Ajax call would be a bit too much to be done.
A webserver will not parse PHP in a .html file...
Either, generate your Javascript variable in your PHP file and declare it global..
Or, change your .html file extension to .php so that the PHP in it gets parsed by the webserver.
I'm trying to use jQuery to read all text files in a folder and display their contents, but then, filter which should ones should be displayed based on the name of the folder.
Here's the JavaScript:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt": "",
"01600610/9874565214_789545623.txt": ""
};
$.each( obj, function(SavedText) {
$.get(SavedText, function(data){
$('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ data +'</div>')
}, 'text');
});
On this:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt":"",
"01600610/9874565214_789545623.txt":""
};
Q1: How do I get all text files inside a folder instead of specifying the file I want?
Q2: How can I filter? For example, how can I only get files ending or starting with 789545.
When these files are on your local filesystem, you can use the HTML5 Filesystem API.
If the files are located on a server, there is no way listing them from plain (client-side) javascript (maybe except a brute-force method, which shouldn't be considered of course). Then you have to write a server script (in PHP/Node/Perl/Phython/...) which will respond to a ajax request with a file list.
If you are using a server script, you should do the filtering on the server (so the answer depends on the language).
Otherwise you should use Regular Expressions:
var search = new RegExp("789545");
for(var file in obj) {
if(search.test(file))
alert(file+": "+obj[file]);
}
This would search for files with a name containing the pattern 789545
Please create index.php file and add this content to it. Create there a folder called "files" and add your files there
<?php
function contains($haystack, $needle){
if (strpos($haystack,$needle) !== false) {
return true;
}
return false;
}
if(isset($_POST['get_files'])){
$folder = "";
$filter = "";
if(isset($_POST['folder'])){
$folder = $_POST['folder'];
}
if(isset($_POST['filter'])){
$filter = $_POST['filter'];
}
$files = array();
foreach(glob($folder.'/*.*') as $filename){
if($filter != ""){
if(contains($filename, $filter)){
$files[] = $filename;
}
}else{
$files[] = $filename;
}
}
print_r($files);
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getData(){
jQuery.post('index.php',{
get_files:true,
folder:"files",
filter:""
},function(data){
jQuery('#container').html(data);
});
}
</script>
</head>
<body>
<input type="button" value="Get data" onclick="getData();" />
<div id="container"></div>
</body>
</html>
You can specify different folder, and filename filter in jQuery post request call
U can use regular expressions to filter the filenames. And for getting all files in a folder, U want to run a server side script. I use perl or php, to do this kinda stuff. U can use ajax to post the request and make the server script to return the file contents.
http://perlmeme.org/faqs/file_io/directory_listing.html
This link is just an example to do what u need in perl. And u could possibly do the same with other languages too
as you know we can get post field by server side language like php,for example in php
$var1 = $_POST['field1']now I wanna know is it possible to get it by JavaScript to?(or any Client Side Language like VBScript)
for example I have page which has got form
<form method = "post" action="test.php">
in test.php I wanna get field by JavaScript,not by php.
Is it possible and how can I do it if it's possible?
You cannot read $_POST data using JavaScript.
When you submit data through the GET method, the generated query string can be read through the location.search object. Another method to "post" data from page 1 to page 2 is by using hashes.
The location object (JavaScript)
location.href = http://example.com/test.php?formElem=value&another=true#hash
location.search = ?formElem=value&another=true
location.hash = #hash
Example (based on the URL at the previous paragraph)
<script>
var $_GET = (function(){
var query_string = location.search.substr(1); //Exclude the first character: `?`
var data = query_string.split(/&+/); //
var $_GET = {};
for(var i=0; i<data.length; i++){
var qs = data.match(/^([^=]+)(?:=(.*))?$/);
$_GET[qs[1]] = qs[2];
}
return $_GET;
})()
alert($_GET["formElem"]); //Alerts "value"
</script>
An alternative method to transmit data from a form to a JavaScript HTML page is by using hashes:
<form action="index.html#someHash" method="get">
<input type="submit" name="someName" value="someValue" />
</form>
After submission, the following page will be requested: index.html?someName=someValue#someHashThe hash is available through the location.hash property.
in your test.php file, echo your post fields as a JSON object.
echo '<script> var data = '. json_encode($_POST).' </script>' ;
It can be accessed as a dictionary in javascript then.
Output in test.php
<script>
var data = { 'field1' : 'value1' , 'field2' : 'value2' } ;
alert(data['field1']);
</script>