I have installed XAMPP to run PHP files on my computer, here is my PHP file I am attempting to execute
<?php
if(isset($_GET['input']))
{
$string = $_GET['input'];
echo strrev($string);
}
?>
Here is my basic HTML file
<html land="en">
<head>
<meta carset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css";
</head>
<body>
<!-- Document Ready Event -->
<input id="text" type="text" /><input id="submit" type="button" value="Submit" />
<div id="feedback"></div>
<script src="../jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</body>
</html>
And here is my JS file
//Pass a value to a PHP file and taking the contents and showing the contents
$('#submit').click( function()
{
var text = $('#text').val();
$.get( 'C:/xampp/htdocs/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
});
When the button is clicked Chrome tells me the this.
Header is
Request URL:file:///C:/xampp/htdocs/amit/reverse.php?input=Hello
Query String Parametersview sourceview URL encoded
input:Hello
and the Response is
<?php
if(isset($_GET['input']))
{
$string = $_GET['input'];
echo strrev($string);
}
?>
Now I have put a different file on my XAMPP PHP side and it works fine, but this one just doesn't response, can anyone see what I am doing wrong at all?
You need to pass the files to your webserver -- make the GET request to a URI on your web server instead of making the request to a file on your computer.
So, change the line:
C:/xampp/htdocs/amit/reverse.php
to
http://localhost/amit/reverse.php
Alternatively, if all your files are in the same directory with a structure as follows:
-- htdocs
- amit
- <somefile>.html
- script.js
- style.css
- reverse.php
Then, you could simply use reverse.php instead of specifying the full path.
Full code as an example:
$('#submit').click( function()
{
var text = $('#text').val();
$.get( 'http://localhost/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
});
You need to get the file through a request to your XAMPP server. Try something like
$.get( 'http://localhost/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
Use relative path instead of local path on your-drive. Just type the filename (if filename is in root-directory). Try not to use absolute paths (like http://localhost/reverse.php) because then you would have to change it when uploading/changing it to another server and that is not a sustainable solution.
$.get( '/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
Secondly, I would recommend using other variable names. I think you're getting problems using text a variable because text() is function in jQuery.
Try:
var textOfElement = $('#text').val();
$.get( '/reverse.php', { 'input': textOfElement }, function( data )
{
$('#feedback').text( data );
});
An in some cases it's fine to be generic about naming, but input and text is far to genereic. Those names doesn't say a bit about the actual context.
Related
I would like to send an image to a php file using AJAX.
Here's my JS code:
$.ajax({
type: "POST",
url: "http://website.com/add-image.php",
data: "img=" + img
})
And That's my PHP
<?php
if ( !empty( $_POST["img"] ) )
{
move_uploaded_file( $_POST["img"], "image.png" );
}
?>
but it doen't work.
I also tried to replace move_uploaded_file by imagepng or imagejpg but still no result.
How can I save the image on my server ?
Thanks
If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you. Why re-invent the wheel?
http://hayageek.com/docs/jquery-upload-file.php
He breaks down the process into four simple steps, that basically look like this:
Look for //1 //2 //3:
<head>
// (1) Load the js files (note that it requires jQuery, which we also load)
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2) Create DIV
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3) initialize plugin
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename myfile specified in the jQuery code block.
On the Hayageek web page, study the upload.php example on the Server tab.
Note that you can also pass additional variables to the my_php_processor.php processor file by using dynamicFormData. See this other example:
$("#fileuploader").uploadFile({
url:"my_php_processor.php",
fileName:"myfile",
dynamicFormData: function(){
return {
//my_php_processor.php will receive POST vars below
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
};
},
onSuccess:function(files,data,xhr,pd){
//files: list of files
//data: response from server
//xhr : jquery xhr object
alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
}
});
my_php_processor.php:
<?php
$n = $_POST['newSubj'];
$b = $_POST['newBody'];
$uploadedFile = $_FILES["myfile"]["name"];
//etc.
echo 'This will display in the alert box';
jsFiddle Sample Code -
Click on Image Example
If your sending your data using a post,
The data property should be a json:
$.ajax({
type: "POST",
url: "http://website.com/add-image.php",
data: {img: img}
})
Instead of sending the image, the right approach would be to send image in base64 encoded format. On the server side you'll have to decode the base 64 encoded string and save as an image. Follow this link to get a better insight on how to send encoded image.
I have a php file that I load into another php file with jQuery. This works, but the moment I start using jQuery in the 'external file', I get ERROR 500.
The reason I used this approach is because this is handy to refresh the data after an AJAX function.
This I have:
test.php:
<script type="text/javascript" src="js/modernizr.custom.29473.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$(document).tooltip({
items: ".plupic , .ingr",
content: function() {
var element = $( this );
if ( element.is( ".plupic " ) ) {
var src = element.attr('src');
return "<img src='" + src + "' style='max-height: 300px; max-width: 300px;'>";
}
if ( element.is( ".ingr" ) ) {
var txt = element.text();
return txt;
}
}
});
$('#kasticket').load('cart.php');
});
</script>
</head>
<body>
<div class="container">
<div id="kasticket"></div><!-- Load data with jQuery-->
cart.php:
I just do a select from the database and write some data to a table with echo();
This works perfectly, but the moment I want to use jQuery, I goes all wrong...(I know this for sure because the jQUery works in a local html file and putting this line in comment makes my php working again)
echo("
<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>
");
I have no idea what I'm doing wrong.
If its any help: http://www.itreflex.be/TestAcc/test.php (with currently the jQuery line in comment).
And this is cart.php, exported to txt, it was to long to paste here.
hard to tell without the full source code but I have got a couple of ideas:
First Error 500 should be the HTTP code for internal server error, which basically means that the error lies on the server, then on the PHP side.
Could it be possible that you are mixing up PHP and jQuery on some of your other statements not posted here?
Second, you missed a single quote on your line
$('#kasticket').load(cart.php');
In your cart.php remove the brackets after echo ... For example
echo "<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>";
Try this above line in your cart.php and see if that works.
I have two sites, site A is just html and javascript, and site B has php. What I need is to get variables from site B in site A.
EX:
site A is like
<html>
<head>
<script>
//this script has to get the values from siteB
</script>
</head>
<body>
<div><!-- here i will do something with the data of site B --></div>
</body>
</html>
Site b is like:
<?php
var1= "something";
var2= "somethingElse";
?>
I was thinking to use JSON or Ajax but i do not understand exactly how.
$(document).ready(function() {
$.ajax({
type: "GET",
url: "filename.html",
dataType: "json",
success: function(data) {
// data will contain var1 and var2
},
error: function(data) {
alert("Problem - perhaps malformed JSON?");
}
});
});
and change your PHP file to be something like:
{
"var1" : "something",
"var2" : "somethingElse"
}
Confirmed to work.
Make sure that your file is a well-formed JSON, otherwise "success" won't be fire.
Note - I am implying usage of JQuery here. Your HTML file should include:
<script type="txt/javascript" src="jquery-1.8b1.js"></script>
File B
<?php
$array[var1] = 'Something';
$array[var2] = 'else';
echo json_encode( $array );
File A (jQuery)
$.getJSON( $( 'file.php', function( data ) {
$( 'div' ).html( data.var1 + ' ' + data.var2 );
}
Edited -- As mentioned, can't do this cross domain without doing some other measures.
Javascript cannot use ajax cross site, for security reasons. The only way to make this happen is to have but one php file on site A that can redirect.
<?php echo file_get_contents($_GET["url"]); ?>
And the javascript can call the url:
/redir.php?url=http://siteb.com/valuetoget.php
There is no way that I know of to do this with no php on the calling website.
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.
I have set up a test case:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script >
$(document).ready(function(){
var contents = $('html').html();
var filename = "test/000.html";
$.ajax({
type: "POST",
url: "/file.php",
data: "content="+contents+"&fn="+filename,
dataType: "html",
success: function(msg, ts, xh){
console.log(msg);
console.log(ts);
console.log(xh);
alert("success");
},
processData: false,
error: function(X, textStatus, error){
alert("Error saving... please try again now.")
}
});
});
</script>
</head>
<body>
<div id="rteContainer" class="dev">
<div id="textEditor">
<form>
<textarea name="balh" id="balh" rows="25" cols="103"></textarea>
<input type="button" id="updateContent" value="Update Changes">
<input type="button" id="closeEditor" value="Close Without Saving">
</form>
</div>
</div>
</body>
</html>
the file.php file is:
<?php
header("Content-type:text/html;charset:UTF-8");
$content = "<html>".stripslashes(urldecode($_POST["content"]))."</html>";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>
Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.
The html string, contents, has to be url-encoded before you POST it. Javascript provides the escape() function, just for this purpose.
Pass $('html').html() to escape() and assign it to contents, like so:
var contents = escape($('html').html());
Your script is dying of embarrassment at the massive security hole in it.
Never, ever, write into a file where the filename is a form parameter without validating the filename first. Even a novice hacker could use this script to overwrite any file on your system that the webserver has access to.
In your Ajax call, pass a { } style array of key value pairs in the data parameter, don't concatenate the variables with ampersands yourself:
data: { content: contents,
fn: filename }
Oh, and you're never actually writing the content into the dumpfile, so whatever file 'fn' points at will just get truncated.
Hope that helps...
I suspect that the ampersand in the javascript is causing a problem. Try replacing it with '&' and see if that fixes it.
Here is my code. You have to kindly look does it suffer from 'same origin policy' in this shape. The domain for HTML is (http://127.0.0.1/jqload.html) & php file (http://127.0.0.1/conn_sql.php). This is json format : [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}]
I actually want to append json data that I receive in HTYML with user input & I am suffering in that. If I use eval for parsing, it works fine to point its put here. But if I use JSON.parse to parse, the whole code stops working & this error message is issued '"IMPORTANT: Remove this line from json2.js before deployment". I put my code for some other question on stackoverflow forum & I was told that my code suffer from 'same origin policy' that causes the problems in appending JSON data. So can you kindly see does my code suffer from this policy? Though I have doubts it suffers from that policy as I learn that it restricts if files reside on different domains, here both files reside next to each other.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input>
<p><input type = "button" id = "send" name = "send" value = "send" onClick=
"ADDLISTITEM"></input>
<p><select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{
alert (json.length); // working
alert json.options[1]; // do not show any value, message just for testing
json.options[json.length+1] = 'newOption'; //not working; HELP HERE
jsonString = JSON.stringify(json);//working fine for current data
alert(jsonString);
//here I have to implement send this stringify(json) back to server,HELP
//HERE
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>
</body>
</html>
You're on the right track, but here: $.each(jsonData, function (i, j) { ... } you are actually looping through each character of the jsonData string, and not the json object. Just change jsonData to json inside the $.each(), and it should work fine (regardless of whether you're using eval or JSON.parse, but I recommend the latter).
Edited: Since you are using jQuery.getJSON(), you don't need to use eval or JSON.parse - jQuery does it for you. So inside your callback function, just set json = jsonData .
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(json, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>