AJAX send value from js to php - php

been tring to send var form js to php and do some manipulation but I keep receving this error. Is it even possible to send the value through to php?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<?php
echo $_POST['name'];
?>
<button id='button'>hi</button>
</body>
<script src="index.js"></script>
</html>
$("#button").click(function(){
$.post("index.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
});
});

I created one index.php file here this should work for you.
<?php
if ($_POST) {
echo json_encode(['data' => $_POST['name'], 'success' => true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<div id='test'></div>
<button id='button'>hi</button>
</body>
<script>
let data = {
name: "Donald Duck",
city: "Duckburg"
};
$("#button").click(function(){
$.ajax({
type: "POST",
url: 'index.php',
data: data,
dataType: 'json'
}).done(function(response) {
if (response.success) {
$('#hey').html('success');
$('#test').html(response.data);
}
});
});
</script>
</html>

This does not work because when you first load the page $_POST['name'] is undefined. Your javascript code does not trigger a submit (= reload to send the data). $_POST['name'] is never set because it will not be updated on the fly. To make this work make a separate php file which only handles the POST data from your javascript and returning a value.
/* call post.php and add console.log to track data */
$("#button").click(function(){
$.post("post.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
console.log(data);
});
});
<?php
// post.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
}
This is of course very basic. In order to communicate effectively you should look into formating the data e.g. into JSON.

Related

Jquery Ajax success data from PHP echo not working

I'm trying to get the data value on success from the php. However when I alert(data) in the success, it returns the page html.
HTML:
<input type="text" class="form-control" name="project_name" id="projectName" required>
Jquery AJAX:
$('#projectName').on('blur', function(){
var projectName = $(this).val();
$.ajax({
url: 'page.php',
type: 'POST',
dataType: 'text',
data: {
'projectChecked': 1,
'project_name': projectName,
},
success: function(data){
if (data == 'taken') {
$('#projectName').addClass('border-red');
}
}
});
});
PHP:
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
Alert Message:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="shortcut icon" href="/favicon.png"/>
<title>Page Title</title>
<meta name="description" content="Meta Description">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlTw8HfCJo=" crossorigin="anonymous"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-157194354-1"></script>
You should use exit in php code to get return data use following code
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
can you check the html code when you do alert(data); and post here?
alternatively, you might want to check the developer tools of browser and validate network tab to monitor parameters and response of ajax request.
It is possible that you are getting http 400/500 response and you are actually seeing default error page (which is of course not a JSON response) in the data variable (this depends on the way server is configured)

Undefined index: files when uploading using ajax and php

I'm trying to create a page that uploads an image. When I hit the upload.php I get this error
Undefined index: files in E:\My-Laptop\Wamp\www\image-upload\upload.php on line 3
and if I do print_r($_FILES)I get an empty array.
I'm not sure where I went wrong.
Here is my code.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container" >
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple>
<!-- Drag and Drop container-->
<div class="upload-area" id="drop-zone">
<h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
</div>
</form>
</div>
<script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html>
my main.js
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
dropZone.ondrop = function(e){
e.preventDefault();
var transfer = e.dataTransfer.files;
uploadImage(transfer);
}
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function uploadImage(files){
var dataString = 'files='+files;
$.ajax({
type: 'POST',
url: 'upload.php',
data: dataString,
success: function(response){
console.log(response);
}
});
}
my upload.php
<?php
print_r($_FILES['files']);
Hope it's help:
function uploadImage(files){
var data = new FormData();
$.each( files, function( key, value ){
data.append( key, value );
});
$.ajax({
type: 'POST',
url: 'upload.php',
data: data,
success: function(response){
console.log(response);
}
});
}

jquery - post() method gets `not found` error

I want to send an email address to my submit.php as post and receive a response with jquery.
submit.php and index.html are in website root and script.js is in 'js' folder.
my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="email" type="email" placeholder=" Email"><br>
<button id="submit-btn">send</button>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script src="js/script.js"></script>
</body>
</html>
my script.js:
$(document).ready(()=>{
$("#submit-btn").click(()=>{
$.post("../submit.php", { user_email: $("#email").val()})
.done((data)=>{
alert(data);
})
.fail((xhr, status, error)=>{
alert(error);
});
});
});
my submit.php:
<?php
$email = (isset($_POST['user_email']) ? $_POST['user_email'] : "nothing");
echo $email;
I expect the output to be my email address, but the actual output is not found.
I think my request has failed
Since you say that both files are in the same folder, there is no need for the ../ in front of your request.
$.post("../submit.php", { user_email: $("#email").val()})
$.post("submit.php", { user_email: $("#email").val()})

How can I consume and autocomplete a field from url that contents json information

I'm trying to autocomplete a field from url that contents json information, I find a lot of examples that I dont know where is my error.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://camino-rest-service.cloudhub.io/caminoAPI/GetCamino",
data: { query: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.ubicaciones
};
});
response(transformed);
},
error: function () {
response([]);
}
});
});
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
JSON example
[
{
"ubicaciones": "San Gabriel, Provincia de Carchi"
},
{
"ubicaciones": "El Ángel, Provincia de Carchi"
},
{
"ubicaciones": "Ambuquí, Provincia de Imbabura"
}
]
some could says who is my error? I try everthing that I know
$( function() {
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "http://camino-rest-service.cloudhub.io/caminoAPI/GetCamino",
dataType: "json",
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el
};
});
response(transformed);
},
error: function () {
response([]);
}
});
}
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
you have syntax error in code and link you provide is nor respond to POST or GET method (i fix only syntax issue)

Problems with jQuery/AJAX interaction

I've been studyiing jQuery lately and today I was working with AJAX. What I want to do, right now, is simply send a date from a date picker to a PHP page which sends back that date.
I'll later improve the PHP page to do what I need to do.
Here's the code of the HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
$(document).ready(function() {
$("#foo").submit(function(){
var serializedData = $(this).serialize();
$.post('demo.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
$("#result").text() = response;
});
});
});
</script>
<title></title>
</head>
<body>
<form id='foo'>
<input type='date' id='dataI' name='dataI'>
<input type='submit' value='send'>
<p id='result'></p>
</form>
</body>
</html>
And here's the simple php page I made:
<?php
echo $_POST["dataS"];
?>
But when I try to send data nothing happens. What am I doing wrong? I tried using a solution I saw here on stack overflow but it doesn't work.
I am attaching code sample;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function validate(){
var serializedData = $('#foo').serialize();
$.post('ajax.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
$("#result").html(response);
});
return false;
}
</script>
<title></title>
</head>
<body>
<form id='foo' action="#" onsubmit="return validate()">
<input type='date' id='dataI' name='dataI'>
<input type='submit' value='send'>
<p id='result'></p>
</form>
</body>
</html>
Ajax code file;
echo $_POST["dataI"];
Try adding return false; after
$.post('demo.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
$("#result").text() = response;
});
statement.
$(document).ready(function() {
$("#foo").submit(function(){
var serializedData = $(this).serialize();
$.post('demo.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
$("#result").text() = response;
});
return false;
});
});

Categories