Ajax Passing Data to PHP Script

Ajax passing data to php script

You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:

$.ajax({  
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});

or in its shorter form:

$.post('test.php', { album: this.title }, function() {
content.html(response);
});

and if you wanted to use a GET request:

$.ajax({  
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});

or in its shorter form:

$.get('test.php', { album: this.title }, function() {
content.html(response);
});

and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.

How do I pass data to a php file using jquery AJAX

Here is the AJAX that I suggest using

$(document).ready(function(){
$('#save').click(function() {
$.ajax({
url: '../php/preparesave.php',
type: 'POST',
data: { user : 'Tommy' },

success: function(output){
alert(output);
}
});
});
});

And below is the PHP (I tried it on my machine and it works)

$user = $_POST['user'];

if(!file_exists('../users/' . $user . '/Platoons/')){
if(mkdir('../users/' . $user . '/Platoons/', 0777, true)){
die('Success');
}else{
die("Folder `../users/{$user}/Platoons/` failed to be created");
}
}

The way you have it, it will only try to create "/Platoon" in a folder $user (Tommy in your example) but that folder doesn't exist and so the script is failing. You need to set the recursive parameter to true so it would first create the folder that doesn't exist and then everything else inside it and then them.

Allows the creation of nested directories specified in the pathname. (Straight from the docs)

How correctly pass data to php using ajax?

When sending data using a FormData object all information has to be in that object. Therefore you need to append() the value from .code to it, as you do with the file information. Try this:

$(".code_form").on("submit", function(e) {
var formData = new FormData();
formData.append('dota', $(".code").val());

if ($(".upload_img").val() != '') {
formData.append("my_file", $(".upload_img").prop('files')[0]);
}

$.ajax({
type: "POST",
url: "img_proc.php",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(data) {
$(".user-success-code").html(data);
}
})

e.preventDefault();
});

passing data to php script with Ajax and vanilla JavaScript

Edit: Since the OP asked, I have added a drop-in replacement for loadDoc() implemented using XMLHttpRequest. See below the main body of code.

XMLHttpRequest is an archaic way of doing things, and while it still has its place there are better methods now. See Fetch

It's also better to use addEventListener than in-line event handlers.

So, with that in mind I've rewritten your JavaScript as below.

Note: I've also closed all your unclosed <div>s and removed the unused libraries that you were loading.

Note also that just adding the required attribute to your <input> would achieve the same as the validation that you're doing.

<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
<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">
<title>demo</title>
<style>
</style>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="card">
<div class="card-body">
<form method="post" name="myForm" action="data.php">
<div class="form-group">
<label for="exampleInputName1">Full name</label>
<input type="text" class="form-control" name="name" id="exampleInputName1" aria-describedby="nameHelp" placeholder="Enter name">
</div>
<p class="text-center text-danger" id="loader">Load and display the value of name here with ajax</p>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
<script>
(function(){
"use strict";
function validateForm(e){
e.preventDefault();

// 'this' points to the form so no need to search for it
if (!this.name.value) {
alert("Name required");
} else {
loadDoc(this);
}
}
function loadDoc(myForm){
// Get the form data
let formData = new FormData(myForm);
fetch('data.php', {
method:"POST",
body: formData
})
.then(response =>{
response.text()
.then(txt => {
document.getElementById("loader").innerHTML = txt;

})
})
}
document.querySelector("form").addEventListener("submit", validateForm);
})();
</script>
</body>
</html>

Passing variables from javascript via ajax to php

It's just simple to pass the values to php file through AJAX call.
Change your AJAX call as shown in below

var message = $('#input-message').val();
var sender= $('#sender').val();
var receiver= $('#receiver').val();
$.ajax({
url: "scripts/load_messages.php",
method: "post",
//data: { "message":$('#input-message').val(),"sender":$('#sender').val(),"receiver":$('#receiver').val()},you can pass the values directly like this or else you can store it in variables and can pass
data: { "message":message,"sender":sender,"receiver":receiver},
success: function(data){
$('#chat-body').html(data);
},
error: function() {
alert('Not OKay');
}
});

and your load-messages.php could be like this`

$receiver = $_POST['receiver'];
echo $receiver;

Pass data to PHP file using Ajax

The cause of your problem is the fact you are using type: 'POST'. To quote the docs :

An associative array of variables passed to the current script via the
HTTP POST method when using application/x-www-form-urlencoded or
multipart/form-data as the HTTP Content-Type in the request.

POST is a more "old fashioned" method, typically you would POST a <form> where the content automatically is serialized, i.e urlencoded, but you try to POST data in a JSON format. What you should do is either consider whether you really need POST. If you change it to GET (or simply remove type: 'POST') and access the passed data by $_GET then it will work (as long as you correct data as well).

If not, change the content type to indicate incoming urlencoded data :

$.ajax({
type: 'POST',
url: 'insert.php',
contentType: "application/x-www-form-urlencoded",
data: {sifra: sifra, barkod: barkod, naziv: naziv, mjera: mjera, cijena: cijena, kolicina: kolicina, ukupno: ukupno},
success: function(response){
alert(response);
}
});

I am pretty sure your code will work now, i.e the $_POST works and any message is properly received as plain text you can alert.

Passing data to PHP from Jquery using ajax without refreshing

I'm not at my dev computer so I can't really test the php side of things but you do have two javascript errors, one of which might be causing the issue.

Not causing your issue but causing an error in the console.

1) Remove the passData() function from the onclick. It's not needed since you're watching for the form submission already with the .submit.

Might be causing your issue

2) When you're defining "title1" you're not getting its value which will cause an HTMLFormElement.toString error when submitting the form currently. Instead go ahead and get the value when defining title 1 via:

$('#title').val();

and then remove title1.val() out of the if statement where you check if its been populated and instead just put title1 == ""

Right now you're sending an HTML element via that ajax call which will cause jquery to fail. Put another way you currently are sending:

data: {title: (HTML ELEMENT)}

Let me know if that fixes it or not. If it doesn't I'll pull this up when I get to where I can run PHP.

EDIT: Also, as pointed out in one of the comments you'll need to change your PHP to be $_POST['title'] in order to match what you're sending. You can verify what is happening on the php side of things by echoing out some errors. It's been a really long time since I've done any php but I would usually do something like:

error_reporting(E_ALL & ~E_DEPRECATED);
ini_set('display_errors', 1);

At the top of my scripts while working on them in order to debug them. This will pass the error from php back to the Ajax response if there is one. That was back in PHP 5 days though.

EDIT2: This is how I got it to work

test.php

<?php
//getting values from JS
$title = $_POST['title'];

if(!$title == "") {
$res="Data received su ccessfully:";
echo json_encode($res);
} else {
$error="Not received,some problem occurred.";
echo json_encode($error);
}
?>

index.html just the ajax part:

$(document).ready(function() {
$('#form').submit(function(e) {
e.preventDefault();

//debug
var x = document.getElementById("msg");
var title1 = $('#title').val();

if (title1 == "") {
x.style.color = "red";
x.innerHTML = "Please fill out all of the blanks.";
} else {
$.ajax({
type: "POST",
url: "test.php",
data: {
title: title1
},
dataType: "JSON",
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
alert(xhr.responseText);
},
success: function(data) {
console.log(data);
}
});
return false;

}
});
});

Unfortunately I don't have the time right now to explain what was changed but I will get to that tomorrow! (Hopefully :)

Also, I did not put the success message in the html, I forgot, and instead am console.logging the response which you can see in the browser console. Sorry I wish I had more time tonight to respond.

How to pass data from HTML, to PHP file by Ajax?

You can't refer to $("#chosenOption") in display.php, because the page has been reloaded. You need to use $_POST['chosenOption'], since that was submitted by the form.

<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption: <?php echo $_POST['chosenOption']; ?>},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>

<div class="result"></div>


Related Topics



Leave a reply



Submit