I'm new with php. I'm trying to post some input with ajax but it doesn't work.
This is my HTML for input:
<div class="form-group"> <h3>Answer:</h3> <div class="input-group"> <textarea name="q1" id="q1" class="form-control" rows="4" ></textarea> </div> </div> <button type="button" id="button" class="btn btn-primary btn-lg">Submit</button>
And this is my jquery function to post data:
$(function(){ $('button').click(function(){ var q1= $('#q1').val(); $.ajax({ type: 'post', url: 'test.php', data: { q1: q1 }, success: function (response) { console.log( response); } }); }); });
My test.php is a simple code to display the input:
<?php $q1= $_POST['q1']; echo $q1; ?>
I don't know why in my test.php I get this error : Notice: Undefined index: q1 in C:\\xampp\\htdocs\\series\\file\\test.php on line 2
Can anyone tell me where is the issue?
First of all you are trying to post a json data to your php file so jQuery may not create correct payload for your request since you getting undefined index:q1
. Can you try the code below;
$(function () {
$('button').click(function () {
var q1 = $('#q1').val();
$.ajax({
type : 'post',
url : 'test.php',
data : "q1="+q1,
success : function (response) {
console.log(response);
}
});
});
});
Try this:
$('document').ready(function(){ $("form#data").submit(function(){ var formData = new FormData($(this)[0]); $.ajax({ url: 'url', type: 'POST', data: formData, async: false, success: function (data) { alert(data); }, cache: false, contentType: false, processData: false }); return false; }); }); }
<form id="data" method="post"> <div class="form-group"> <h3>Answer:</h3> <div class="input-group"> <textarea name="q1" id="q1" class="form-control" rows="4" ></textarea> </div> </div> <input type="submit" id="button" class="btn btn-primary btn-lg"> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.