I am trying to create a page whereby you can submit some text and then retrieve it on button press, I have managed to get it to submit to my server, however on retrieval I keep getting the error "unexpected end of JSON input" and have no idea what to do about it, my knowledge of PHP/JSON is very limited, any criticism / pointers are greatly appreciated.
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("DataSubmitted");
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var data = JSON.parse(this.responseText);
alert(data);
}
}
xxhttp.open("GET", "gethint2.php", true);
xxhttp.send();
}
PHP/HTML:
<php? session_start(); ?>
<html>
<script type="text/javascript" src="main.js"></script>
<head>
</head>
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
</html>
Sending Data:
<?
$_SESSION["input_data"] = $_POST;
echo $_POST["input"];
?>
Retrieving Data:
<?php
$_SESSION["input_data"] = json_encode($_POST);
?>
I am trying to pass a value to a ajax function. This was simple on a form and working as expected(changed the id to gal_id1 in the example below) but I am getting undefined error on the value passing for my anchor.
<html>
<head>
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "ajax_json_gallerySQL.php";
var gid = document.getElementById("gal_id").value;
var vars = "gal_id="+gid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Test Pictures. </h2>
THis is working
<input id="gal_id1" name="gal_id1" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();" > <br><br>
<div id="status"></div>
<?php
$myValue='13';
This is not working
echo "<td> <a id='gal_id' name='gal_id' href='#' onClick='ajax_post();' value='13' ><img src='images/Parents/Brook/Brook1.jpg' alt='Image' width='270' height='203'></a><br><br>";
?>
</body>
</html>
Anchors don't have values in the same way that inputs do, so .value won't work. What you can do instead is use document.getElementById("gal_id").getAttribute('value')
Having said that, you should probably be using data attributes, e.g.
<a data-value="13" id="gal_id">
and then
document.getElementById("gal_id").dataset.value
More information on data attributes
I know this has been mentioned many times in this thread but I still couldn't figure out how to solve my problem. I'm having difficulty on how to send and fetch my data from the comment.php to the insert.php
Here is my code for my comment.php:
(Notice the comments in javascript the method part [there's three of them], I've tried experimenting with them so that I could insert my data to the database but to no avail they didn't work. I'm still learning after all).Could someone help me. I'm still a beginner so I might find it difficult to understand an advance but i'll do my best.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Comment</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="bootstrap.min" />
<script type = "text/javascript" >
<!-- method 1-->
//$(document).ready( function() {
// $('#submit').click( function() {
//
// $('#getResponse').html('<img src="bootstrap/images /loading.gif">');
// $.post( 'insert.php', function(sendRequest) {
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"&web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
// $('#getResponse').html(sendRequest);
// });
// });
//});
<!-- -->
<!-- method 2-->
//function sendRequest() (
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
//)
<!-- -->
<!-- method 3-->
// function sendRequest()
//{
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,false);
// xmlhttp.send(null);
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
//}
<!-- -->
</script>
</head>
<body>
<form method = "post" action="">
<div id="main">
<div class="comment" style="display: block;">
<div class="avatar">
<img src="img/default_avatar.gif">
</div>
<div class="name">Avatar</div>
<div class="date" title="Added at 02:24 on 20 Feb 2015">20 Feb 2015</div>
<p>Avatar</p>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="Get" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name">
<label for="email">Your Email</label>
<input type="text" name="email" id="email">
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url">
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"> </textarea>
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<div id = "getResponse"></div>
</div>
</div>
</form>
</body>
</html>
Here is my code for the insert.php my php file where I perform the insertion of data to my database.
<?php
mysql_connect("localhost","root");
mysql_select_db("comment");
$name = $_GET['name'];
$email = $_GET['email'];
$web = $_GET['web'];
$comment = $_GET['comment'];
mysql_query("INSERT INTO demo (c_name,c_email,c_web,c_comment) VALUES ('$name','$email','$web','$comment')");
echo "Inserted Successfully";
?>
In your comment.php file , use Button,not submit.
And on click event of that button , call jQuery ajax
$('#button_id').click(function(){
//Get values of input fields from DOM structure
var params,name,email,url,body;
name=$("#name").val();
email=$("#email").val();
url=$("#url").val();
body=$("#body").val();
params = {'name':name,'email':email,'web':url,'comment':body};
$.ajax({
url:'insert.php',
data:params,
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
Update
I dont know whether you used button or submit. So I am specifying for you.
<input type="button" name="submit" id="button_id" value="Submit" >
you can use this to submit the record to insert.php action in the form should be action = "insert.php"
$('form#addCommentForm').on('submit', function(){
$("#response").show();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value ){
$('#response').html('<img src="images/loadingbar.gif"> loading...');
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$(".ajax")[0].reset();
$("#response").hide();
}
});
return false;
});
form the db connection script use this
<?php
$connect_error = 'sorry we\'re experiencing connection problems';
mysql_connect('localhost', 'root', '') or die($connect_error) ;
mysql_select_db('comment') or die($connect_error);
?>
you can also use the form serialize function, its good approach.
$('#addCommentForm').submit(function(form){
$.ajax({
url:'insert.php',
data: $(form).serialize(),
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "index2.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Your First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
The code above works and submits the data and gets the result, along with the result it renders the form again. Image --> http://oi47.tinypic.com/1bt02.jpg
How to fix it?
Thanks in advance.
Don't include the form in the response you send to the Ajax request.
Here's a very simple problem I came across today that's been very frustrating to me:
Say I'm uploading a video file through the HTML 'choose file' input, and I have a submit button that calls an onclick java script function for sending the video to a php file and returns data about the video back to the original page, (something simple like echo $_FILES[$myvideoupload]['name'] ) all through XMLhttpRequest().
Is this possible?
As it is right now, the video simply isn't being passed through my ajax function to the php file. Does document.getElementByID("stuff") work for video files? or is it more about how I should format var in send(var)? Any ideas or knowledge on the subject of passing files through XMLHttpRequest() would be awesome.
Here is my not-so-awesome code with the file attempts commented out in the js. Hope this helps.
<html>
<head>
<link href="jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script language="JavaScript" type="text/javascript">
function file_upload(){
var hr = new XMLHttpRequest();
var url = "vidcon.php";
if(document.getElementById('preset_mp4').checked) {
pr = document.getElementById("preset_mp4").value;
}else if(document.getElementById('preset_ogg').checked) {
pr = document.getElementById("preset_ogg").value;
}else if(document.getElementById('preset_mov').checked) {
pr = document.getElementById("preset_mov").value;
}else if(document.getElementById('preset_wmv').checked) {
pr = document.getElementById("preset_wmv").value;
}else if(document.getElementById('preset_3gp').checked) {
pr = document.getElementById("preset_3gp").value;
}
//var fd = new FormData();
//fd.append('uploadedfile', document.getElementByID("uploadedfile").files[0]);
var vars = "preset="+pr;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.response;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="hidden"/>
<form enctype="multipart/form-data" action="" method="POST">
Choose pload:<br> <input id="uploadedfile" name="uploadedfile" type="file" /><br />
</form>
Select Output Format for Conversion (changes will be made to conversion settings) <br>
<div class="field form-inline radio">
<input id="preset_mp4" name="preset" type="radio" value="mp4">mp4<br>
<input id="preset_ogg" name="preset" type="radio" value="ogg">ogg<br>
<input id="preset_mov" name="preset" type="radio" value="mov">mov<br>
<input id="preset_wmv" name="preset" type="radio" value="wmv">wmv<br>
<input id="preset_3gp" name="preset" type="radio" value="3gp">3gp<br>
</div>
<input type="submit" value="Upload File" onClick="javascript:file_upload();"/>
<div id="status"></div>
</body>
You need to use a FormData object to upload a file via ajax. Something like
var fd = new FormData();
fd.append('preset', pr);
fd.append('videofile', document.getElementByID("videofileinputid").files[0]);
hr.open("POST", url, true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.response;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(fd);
document.getElementById("status").innerHTML = "processing...";
Note that not all browsers support the FormData object but the are js libraries that simulate an ajax file upload.