I created a simple contact us form that would capture the data and send to the server end via JSON and display it on the PHP page. I'm a beginner to this whole JSON thing. Please tell me where I've gone wrong.
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr = {
firstName : document.getElementById('fName').value,
lastName : document.getElementById('lName').value,
email : document.getElementById('email').value,
comment : document.getElementById('comment').value,
rate : document.getElementById('select').value
};
$.ajax({
url: 'contact.php',
type: "post",
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: "json"
success: function(msg) {
alert("msg");
}
});
});
</script>
PHP
<?php
$example = $_POST['arr'];
echo $example;
?>
HTML
<body>
<h1> Contact Us </h1>
We value your feedback. Send in your questions, suggestions, ideas to help us improve our service.
<h2 align="Center"> Search us on Google Maps</h2>
<br>
<br>
<div id="map-canvas" > </div>
<form action="contact.php" name="form" method="post" >
<div id= "result">
<br>Name :<br>
<input type="text" name="fName" id="fName" required >
<input type="text" name="lName" id="lName" required >
<br> <br>
Email: <br>
<input type="email" name="email" id="email" required >
<br> <br>
Comment: <br>
<textarea name= "comment" rows="8" cols="50" autofocus></textarea>
<br> <br>
Rate our Website <select name="select" id="selected" autofocus>
<option value = "1" name= "rate"> 1 </option>
<option value = "2" name= "rate"> 2 </option>
<option value = "3" name= "rate"> 3 </option>
<option value = "4" name= "rate"> 4 </option>
<option value = "5" name= "rate"> 5 </option>
</select>
<br> <br>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
replace
data: ({name: 145}),
with
data: {arr: arr},
In your AJAX call, your data that you are sending over is just "name : 145", so the only thing in your post will be $_POST['name']. The arr value is never passed to you AJAX function, so it will not pass 'arr' over.
What you are looking for would be this if you want the PHP side to remain the same:
$(document).ready(function(){
var arr = {arr: {
firstName : document.getElementById('fName').value,
lastName : document.getElementById('lName').value,
email : document.getElementById('email').value,
comment : document.getElementById('comment').value,
rate : document.getElementById('select').value
}};
$.ajax({
url: 'contact.php',
type: "post",
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: "json"
success: function(msg) {
alert("msg");
}
});
});
When you use JSON, what gets sent through the post request looks like this:
For a JSON array that is formatted in this way:
var json = { 'name' : 'leneya', 'id' : '74'}
Your PHP $_POST array will look like:
$_POST['name'] => 'leneya'
$_POST['id'] => '74'
If I were you, I'd probably format my JSON as such:
$(document).ready(function(){
var arr = {
firstName : document.getElementById('fName').value,
lastName : document.getElementById('lName').value,
email : document.getElementById('email').value,
comment : document.getElementById('comment').value,
rate : document.getElementById('select').value
};
$.ajax({
url: 'contact.php',
type: "post",
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: "json"
success: function(msg) {
alert("msg");
}
});
});
Notice how I pass the arr variable into data, because that is how you send JSON through the AJAX request.
Then on the PHP side, you can now use $_POST['firstName'] to get just the first name, $_POST['email'] to get the email, and so on.
Edit
Since your are running $.ajax on $(document).ready(), jQuery is running the ajax function as soon as the page loads. What I'm assuming you want is to submit the form once the user clicks the "Submit" button. To do this, you need to adjust your javascript:
$(document).ready(function(){
//this line binds the ajax functionality to the click of the submit button
$('input[type="submit"]').on('click',function(e){
//this prevents the form from submitting itself to php.
e.preventDefault();
var arr = {
firstName : document.getElementById('fName').value,
lastName : document.getElementById('lName').value,
email : document.getElementById('email').value,
comment : document.getElementById('comment').value,
rate : document.getElementById('select').value
};
$.ajax({
url: 'contact.php',
type: "post",
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: "json"
success: function(msg) {
alert("msg");
}
});
});
});
On the PHP side, you will now be able to access your keys according to the JSON array.
$_POST['firstName'],
$_POST['lastName'],
$_POST['email'] ...
Again, the keys in your post array should match up with the keys in your JSON array. If they don't, then your AJAX is still not working. In addition, you will be able to tell if the AJAX is working, because you should get an "alert" from javascript that displays whatever message you have echoed from PHP.
Related
Hello i try to display a price form an AJAX call, i putted an input just to check if you get the price and it's work but i can't display the price result on a span.
{{$product->price}} have default value but it's change depending the size, i would like to display the result also in the space and hide the input.
someone knows how to do that ?
Here my html :
<input type="text" placeholder="{{$product->price}}"value="{{$product->price}}">
<div id="price">
<span class="text-muted text-normal" id="price"> {{$product->price}}€</span>
</div>
<input type="hidden" name="price" id="price" value="{{$product->price}}" />
Here my javascript :
<script>
$('#size').change(function () {
$.ajax({
type: 'GET',
url : '../{{$product->id}}/ballons-entrainement/size-price',
dataType: "json",
data : {
size : document.getElementById('size').value
},
success:function(data){
console.log(data);
$('input').attr('value', data.price);
}
});
});
</script>
You try with .html() like
<script>
$('#size').change(function () {
$.ajax({
type: 'GET',
url : '../{{$product->id}}/ballons-entrainement/size-price',
dataType: "json",
data : {
size : document.getElementById('size').value
},
success:function(data){
$('span#price').html( data.price );
}
});
});
</script>
I am making two AJAX calls in the form. The first is to change the second select based on the first select which calling a PHP page to process the data. The second is to prevent the default post and post the data in another PHP page.
Both Functions are working if I delete the other one. I also have another problem which is the redirect to a new page (using CleanURL). Where should I redirect in the posting page, or once return to the form page?
$('#brand').change(function() {
var brandID2 = $(this).val();
$.ajax({
url: "Calling the models after selecting the brand",
method: "POST",
data: {
brandID: brandID2
},
dataType: "text",
success: function(data) {
$('#model').html(data);
}
});
});
$("#testform").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "Calling the post page",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
//window.location.href = "<?php echo $_SESSION['toRedirectToAfterFilters']; ?>";
}
});
}));
<form name="testform" action="" method="POST">
<select name="brand" id="brand">
<option value=''>Select a Brand</option>
//function to load all the brands
</select>
<select name="model" id="model">
<option value="">Please Select Brand First</option>
</select>
<button type="submit" name="submit" class="">FILTER</button>
</form>
You are missing the id on testform
<form id="testform">...
I would remove the CleanURL dependency and try out each AJAX request one at a time. Then you will immediately see the point of failure. If not, throw a debugger; inside each event handler and step through.
Personally, I would redirect from the server after a successful database write, to simplify the logic and not have to store the success callback URL inside the $_SESSION array.
So I have a target. It's to have a live area where you type in a username and every time you let a key go onkeyup() in the input area, I want it to send that data to a php file where that file will return what you just typed in and display it out where I want it. This isn't going as I like though :P. Please help, and thanks in advance.
JavaScript/jQuery/Ajax Code
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "GET",
url: "php/return.php",
data: user,
cache: false,
success: function(data){
$("#username-display").text(data);
}
});
}
HTML Code
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP Code
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $username;
?>
Please let me know if you need more info to help me solve this...
hey you can use following code
HTML CODE
<script type="text/javascript">
function changeUsername() {
// var user = $("#user").val();
$.ajax({
type: "GET",
url: "s.php",
data: {'user':$("#user").val()},
success: function(data){
$("#username-display").text(data);
}
});
}
</script>
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP CODE
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $_GET["user"];
?>
You need to correct your AJAX code also change type from GET to POST in php code so, final code will be like -
function changeUsername() {
var user = $("#user").val();
$.ajax({
url: "data.php",
data: {'user': user},
type : 'post',
success: function (data) {
$("#username-display").text(data);
}
});
}
PHP CODE :-
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo json_encode($username);
Change Get to Post.
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "POST",
url: "php/return.php",
data: {'user': user},
cache: false,
success: function(data){
alert(data);
$("#username-display").text(data);
}
});
}
Php code first try to get response.
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo $username; exit;
Try:
echo( json_encode( $username ) );
exit( 1 );
I plan to POST my text content to http://language.cs.usm.my/synthesis/read.php form's textarea which is third party web page, below is the form that i get from the URL.
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100">Malaysia ialah sebuah negara raja berperlembagaan persekutuan di Asia Tenggara yang terdiri daripada 13 negeri dan tiga wilayah persekutuan. Ia menduduki bumi berkeluasan 329,847 kilometer persegi.</textarea>
<input type="submit" value="OK" name="submit" />
</form>
The method i use to post data as below:
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:"Nama saya ialah Ali"
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
How can i replace the content in the existing textarea with my data?
Thanks
you have to add ng-model on the input or textarea
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100" ng-model="yourtextarea"></textarea>
<input type="submit" value="OK" name="submit" />
</form>
and in the controller get him with $scope.yourVarName
$scope.yourtextarea ;
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:$scope.yourtextarea
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
You need to use ng-model
<textarea name="malayText" rows="4" cols="100" ng-model="malayText">
and then you can readily access it in your controller
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test: $scope.malayText
}
I used ajax method to solve this problem with auto submit the form when i perform the POST action. Below is my code and solution:
$.ajax({
type: 'POST',
url: 'your url',
data: {'submit': 'submit', 'malayText' : "data that wish to POST"}, // you can use as much as data you want to send,
dataType: 'JSON' // so you can use the json_encode php function
});
I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.