PHP POST data array is empty - php

I am using HTML, PHP and AJAX to create a search field.
Here is my HTML Code:
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
This is my AJAX Code:
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert("Success");
}
});
});
In PHP I tried the following:
$obj = $_POST['myData'];
echo $obj;
print_r($_POST);
All I am getting is:
Notice: Undefined index: myData in C:\xampp\htdocs\workspace\MakeMyApp\WebContent\search.php on line 9
Array ( )
I have also tried with:
file_get_contents('php //input')
but there also I am getting empty array. I don't know what exactly the problem is. Am I missing anything?

Sorry, I can't comment as I don't have enough 'reputation'.
I have tried to replicate your issue and it seems to work ok for me.
Here is the HTML page ...
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
});
});
</script>
</head>
<body>
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
</body>
</html>
And this is the receiving PHP page
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
In the ajax request, you can see I'm using alert to output the response in an alert but, and if all goes well it should output the content outputted by the receiving PHP page.
Also, it may not help much, but his is how I would have done the ajax request; it's slightly less code and you don't have to define each form field individually (if you have more than one field)
$(document).ready(function(){
$('#search_form').submit(function() {
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data: formData,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
return false;
});
});

Related

How to pass the array value to PHP using AJAX?

I am trying to submit data to the database using AJAX. I have one array and I have to pass the value of the array to PHP using AJAX to display all the related records.
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
AJAX
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
//alert(response);
}
});
});
});
</script>
PHP
$sql='SELECT Name, Email FROM request WHERE Id IN (' .( is_array( $_POST['compare_id'] ) ? implode( ',', $_POST['compare_id']) : $_POST['compare_id'] ).')';
$records = array();
$query=$conn->query($sql);
if ($query->num_rows > 0) {
while($row=$query->fetch_assoc()){
$records[]=$row;
}
}
echo json_encode($records);exit();
HTML
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
JS
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
}
});
});
});
</script>
PHP
var_dump($_POST['compare_id']);
// it is already an array of ids. You can do whatever you want with it.
change your script as below. Your output is in array so you cant add it in div directly
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'action.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html();
for(data in response) //loop over your data
{
$('#response').append(response[data].Email); //add email
}
//alert(response);
}
});
});
});
</script>
There are errors in your code. A good way to debug this is to print_r your POST value in your php script.
First $_POST["All"] does not exist. It is all. (php)
Second, you send a GET request not a POST one. (jQuery)
Third, format your date into json. A good way to do this is to create a variable right after compare_id.push, it's more readable, as so :
var json_data = {"my_array" : [1,2, "bonjour", 4]};
Your problem is mostly related to "how to debug". I think you should print what's happening along the way to figure out what's happening.

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

Posting data to sql database without reloading page

the problem is that i am unable to insert data in my database without reloading
i have tested it without the note_sql.js and my note_sql.php works fine but there seems to be a problem in my js file if some body could point me in the right direction it would be wonderful
Index.php
<form id="noteform" action="note_sql.php" method="POST">
<input type="text" name="note"></input>
<input id="sub" type="submit" value="Save Note" />
</form>
<span id="result_note"><span>
<script type ="text/javascript" src="jquery/note_sql.js"></script>
note_sql.js
$("#sub").click(function(){
var data = $("#noteform: input").serializeArray();
$.post($("#noteform").attr("action"),data,function(info){$("result_note").html(info); });
clearInput();
});
$("#noteform").submit(function(){
return false;
});
function clearInput(){
$("#noteform :input").each(function(){
$(this).val('');
});
}
Use Jquery Ajax the working code is given below :
please add ID to Note Form Element :
<pre>
<script>
$(document).ready(function () {
$("#sub").click(function () {
var name = $("#note").val();
var message = $("#message").val();
$.ajax({
type: "post",
url: "note_sql.php",
data: "name=" + name,
success: function (data) {
alert(data);
}
});
});
});
</script>
</pre>

Send input value to php using ajax with result printed to div

I'm trying to send an input value to a php script and have the returned value posted to a div, using ajax, but I can't seem to get this right. Any help/suggestions would be appreciated. Thanks!!
This is what I have by now, but console says: "Failed to load resource: the server responded with a status of 404 (Not Found)".
test1.php:
<script>
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$(document).ready(function(){$("#content").load("test2.php");});
}
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit">
</form>
<div id="content"></div>
test2.php:
<?php
$string=$_POST['id1'];
require_once('connect.php');
$inf = "SELECT * FROM `comments` WHERE date='$string'";
$info = mysql_query($inf);
while($info2 = mysql_fetch_object($info)) {echo $info2->username.$info2->date;}
?>
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
<div id="content"></div>
When you submit the ajax request, you're already submitting your content to test2.php, so you don't need to load it again. In the success function, you can append the result to the div from the callback.
$(document).on('click','#submit',function(e) {
e.preventDefault();
$.post('test2.php',{url: $('#id1').val()},function(data){
$("#content").html(data);
}
});
});
404 (Not Found) Error is for page not found. Please make sure that file test2.php is exist in same folder. Check url.
Also you can copy the URL from console and paste it in the browser URL to check the url correct or incorrect.
jQuery
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
HTML
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
You could try this:
<script>
$('#submitBtn').on('click',function(){
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$("#content").html(data);
}
});
return false;
});
</script>
<form name="input">
<input type="text" id="id1">
<input id="submitBtn" type="submit">
</form>
<div id="content"></div>

jQuery making a post request and retrieving result

So I have a test input and a submit button. I want to send the data via jQuery and retrieve the result from the post request and then display the value that the post request returns, without refreshing the page.
Here is my html:
<div id="middle">
<form id="searchForm" action="/">
<input placeholder="E.g. http://www.google.co.nz" id="url" type="text" name="forward_to"/>
<input id="button" type="submit" name="shorten" value="Go"/>
</form>
<div id="result"></div>
</div>
Here is my php
if($query) {
print("<div id='content'>http://www.website.co.nz/u/$short</div>");
} else {
print("<div id='content'>Error</div>");
}
Is there anyway to do this?
$(document).ready(function(){
$('#button').click(function(e){
e.preventDefault();
$.ajax({
type: 'post',
url: '/',
data: { query: $('#url').val() },
success: function(data) {
$("#result").html(data);
},
error: function() {
$("#result").html("Some error occurred.");
}
});
});
});

Categories