Why does this simple JavaScript+Ajax+php code not working? - javascript

I'm new to ajax, I am trying to send the html page data to php without reloading the current page. When I click on submit button it just blink "processing..."
html file
<!DOCTYPE html>
<head>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "simple.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);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
First Name: <input id="first_name" name="first_name" type="text"> <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>`
Php file
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
Edit 1
I added alert message in onreadystatechange. It showing three alert messages 2,3,4 respectively.
alert(hr.readyState);

There are multiple things i can see:
</script> a closing of the script which doesn't have any opening tag in the head.
The variable vars doesn't create a query string as it is missing a ?.
So, the complete changes would be:
<head>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "simple.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "?firstname="+fn+"&lastname="+ln;
//----------^---put this at start.
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.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
Or you can send it as:
hr.send({ firstname:fn, lastname:ln });

Related

Trying to send a string to php file using ajax

So i am trying to send a string into a php file using ajax but the http.send is not working, maybe something is wrong with the code? (i am just a beginner)
mainlink= 'a link';
id= 'an id';
$(document).click(function(){
var http = new XMLHttpRequest();
var link = mainlink+id;
http.open("POST", 'test.php', true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onload = function(){
if(this.status == 200) {
console.log (link);
}
}
http.send("link="+link);
});
test.php:
<?php
if (isset($_POST['link'])){
echo $_POST['link'];
} else{echo "error";}
?>
i tried both GET and POST.
This works. Are you sourcing in jQuery? Paste this tag inside the head tag of your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
It also seems probable that you want to console log this.responseText instead of link so you actually log what the server is responding rather than what you sent. Here is the exact code I used to get this working:
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var mainlink = 'a link';
var id = 'an id';
$(document).click(function(){
var http = new XMLHttpRequest();
var link = mainlink + id;
http.open("POST", 'test.php', true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onload = function(){
if (this.status == 200){
console.log(this.responseText);
}
}
http.send("link=" + link);
});
</script>
</head>
</html>
PHP:
<?php
if(isset($_POST['link'])){
echo $_POST['link'];
}
else{
echo "error";
}
?>
You can see it working live here. Is your pathname correct for test.php?

Send data from JavaScript with AJAX and JSON to the server and retrieve data from the server

I am new to AJAX and JSON. I found some code from this link and modified it:
send json object from javascript to php
What I want is this:
I have some data (variables, arrays, ect.) in JavaScript which are dynamic (the user can change this values at runtime). Now I want to send this data to the server and save it in a PHP file. I also want to retrieve the updated data from the server. In short explained I want to save from client to server and load from server to client.
I become an error in Load() on line "alert(jsondata.num);": Cannot read property 'num' of nullat XMLHttpRequest.xhr.onreadystatechange
PHP:
<?php
header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;
?>
JavaScript:
function Save() {
var jsondata;
var num = {"num":Math.floor(Math.random()*100)};
var data = JSON.stringify(num);
var xhr = new XMLHttpRequest();
xhr.open("POST", "demo.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
console.log(jsondata);
alert(jsondata.num);
}
}
}
function Load() {
var jsondata;
var xhr = new XMLHttpRequest();
xhr.open("GET", "demo.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
alert(jsondata.num);
}
}
}
I have created this for you for clarity. It allows user to send email and name and return json data to clients. With this you now have basics..
<!doctype html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
// submit button click
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
alert(name);
if(name != ''){
$.ajax({
url: 'demo.php',
type: 'post',
data: {name:name,email:email},
dataType: 'JSON',
success: function(response){
alert(response.name);
// selecting values from response Object
var name = response.name;
var email = response.email;
var dt = "<div>";
dt += "<b>Email:</b>"+email+"<br>";
dt += "<b>name:</b>"+name+"<br>";
}
});
}
});
});
</script>
</head>
<body>
<div class="container">
<div class="content">
<h1>Enter Details</h1>
<div>
<input type="text" id="name" name="name" placeholder="Name">
</div>
<div>
<input type="email" id="email" name="email" placeholder="email">
</div>
<div>
<input type="button" value="Submit" id="submit">
</div>
</div>
<div id="Result">
</div>
</div>
</body>
</html>
demo.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
// insert into database
//response
$return_arr = array('name'=>$name,'email'=>$email);
echo json_encode($return_arr);

image upload using javascript?

This is my HTML and javascript.
I'm trying to upload an image using javascript.
I did find some examples using jquery, but was hoping if this function below can be modified to do the same.
The image upload script is a PHP script, which works when the form is posted normally, but when using this function below, it doesn't send the image to the PHP script. $_FILES is empty.
How can I modify this function to send the image as well?
<html><head>
<script type="text/javascript">
function jax( ){
pd = document.getElementById("pd").innerHTML;
i = document.getElementById("i").value;
url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i;
q="act=uploadPic&title=" + pd + "&i=" + i;
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false;
}
}
}
ajaxRequest.onreadystatechange= function(){
if(ajaxRequest.readyState == 4){
r =ajaxRequest.responseText;
alert(r);
}
}
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(q);
}//func
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> Title: <input type="text" name="pd" id="pd" value=" Title here " />
<p> Image: <input type="file" name="i" id="i" />
<p> <button onclick=" jax( ) "> Upload </button>
</form>
</body>
</html>
The PHP script to verify if image is send:
ajax.php
<?php print_r($_FILES); ?>
this is my function,but can't working lower than ie8:
function jax(){
url= "ajax.php?act=uploadPic";
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('post',url,true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
xhr.addEventListener('progress',function(e){
if (e.lengthComputable) {
console.log(e.loaded+'/'+e.total);
}
},false);
xhr.send(formData);
}

How can I print PHP POST data using AJAX? (no jQuery)

So basically I've got this HTML.
<form method="post" id="myform" onsubmit="getData()">
<fieldset>
<legend>Form</legend>
<label>Color: <input type='text' id="color" name='color'></label>
<label><input type="submit"></label>
</fieldset>
</form>
<div id="showoutput">
</div>
This PHP:
<?php
$color = $_POST['color'];
if($color != "")
{
$color = htmlentities($color, ENT_QUOTES);
print "<p>The color is $color</p>";
}
else
{
print "<p>Fill out form!</p>";
}
?>
And this JS:
window.onload = getData;
var req = new XMLHttpRequest();
function getData()
{
var poststr = "color=" + encodeURI( document.getElementById("color").value );
req.open("POST", "lab11-1.php", true);
req.onreadystatechange = useResponse;
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(poststr);
}
function useResponse()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById('showoutput').innerHTML = req.responseText;
}
}
}
I'm trying to be able to input a color in the form, hit submit, and use AJAX to print the PHP to the "showoutput" div in my HTML. I've tried everything I can think of and haven't been able to figure it out.
I think this is not correct.
Ajax don't need form submit function,
I did do like this, I think you want it.
<form method="post" id="myform">
<fieldset>
<legend>Form</legend>
<label>Color: <input type='text' id="color" name='color'></label>
<label><input type="button" onclick="getData()" value="submit"></label>
</fieldset>
</form>
<div id="showoutput">
</div>
<script>
window.onload = getData;
var req = new XMLHttpRequest();
function getData()
{
var poststr = "color=" + encodeURI( document.getElementById("color").value );
req.open("POST", "test.php", true);
req.onreadystatechange = useResponse;
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(poststr);
}
function useResponse()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById('showoutput').innerHTML = req.responseText;
}
}
}
</script>

Ajax Post to PHP and Get Return Data

I am developing a slider to set my budget and would like to achieve the value which I set in slider1.php. However, when I tried using the code below, I encountered an error
"Notice: Undefined index: slideStatus in C:\xampp\htdocs\1204763e\slider1\slider1.php on line 4
Thank you , says the PHP file"
In slide.php, I inserted this set of code:
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(val){
var hr = new XMLHttpRequest();
var url = "slider1.php";
var ss = document.getElementById('sliderStatus').innerHTML = val;
var vars = "sliderStatus="+ss;
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.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>
<input type="range" name="slide" min="0" max="100" value="50" step="2" onChange="ajax_post(this.value)" />
<br /><br />
<span id="sliderStatus">50</span>
<br/><br/>
<div id="status"></div>
</body>
</html>
In slider1.php, I inserted this set of code:
<?php
echo 'Thank you '. $_GET['slideStatus'] . ', says the PHP file';
?>
You seem to try to access "slideStatus" but you are posting "sliderStatus".

Categories