i am new in ajax. i want to display the text entered inside the input to another div element.here is the image given below:
here is my code :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<script >
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async:true,
data: values ,
success: function (response) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
</script>
</body>
</html>
here is php code:
<?php
$bar = $_POST['bar']
?>
please help me to fix the problem & also minimize the code if possible.thanks
Client-side
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form>
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Go">
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<!-- For testing purposes comes here the JSON object (stringified) -->
<div id="jsonstring" style="font-family:monospace;">Json object</div>
<script type="text/javascript">
var values = $("form").serialize();
$("form").on("submit", function( event ) {
event.preventDefault();
var values = $( this ).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async: true,
data: values,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(json) {
$('#result').html((json.content) ? (json.content) : '???');
$('#result').prop('title', json.title);
$('#jsonstring').html('Json object: '+JSON.stringify(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
</body>
</html>
Server-side
<?php
$bar = (isset($_POST['bar'])) ? $_POST['bar'] : '';
$result = array(
'title' => 'This is the result from an AJAX call',
'content' => 'This is the result: <span style="color:red;">' . $bar . '</span>',
);
echo json_encode($result);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form name="form">
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" id="submit" value="click" >
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<script >
/* Get from elements values */
$("#submit").on("click", function(){
var values = $(this).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async:true,
data: values ,
success: function (response) {
$('#result').html((response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
</body>
</html>
Related
Well I've been having this issue now where my ajax form doesn't show my response value which I enter in the text field. I can't seem to understand why it doesn't show my post value at all.
reset.php
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.1.1.js"
integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
crossorigin="anonymous"></script>
<script>
function submitdata()
{
var email=document.getElementById( "emailfield" );
var datastring='email='+ emailfield;
{
$.ajax({
url: "work2.php",
type:'POST',
data:datastring
cache:false
success: function (html){
$('#msg').html();
}
});
});
</script>
</head>
<body>
<form method="POST">
E-mail: <input type="text" id="emailfield"><br>
<input value="submit" type="submit" onclick="return submitdata()">
</form>
<p id="msg"><p/>
</body>
</html>
work2.php
<?php
$email=$_POST['email'];
echo "response $email";
?>
There are few things you are missing here:
1) You are NOT getting the value from user.
Use:
var emailfield = document.getElementById( "emailfield" ).value;
OR simply
$("#emailfield").val();
2) You are not preventing the default submit process.
Use:
e.preventDefault();
I went ahead and wrote this for you. Just copy all the file and you'll see it working. Hope it helps!
<?php
$data = array();
if(isset($_POST['email'])){
$data = $_POST['email'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
E-mail: <input type="text" id="emailfield"><br>
<input value="submit" type="submit">
</form>
<p id="msg"><p/>
<script type = "text/javascript">
$("form").on("submit", function(e){
e.preventDefault();
var emailfield = $("#emailfield").val();
var email ='email='+ emailfield;
$.ajax({
url: "testing.php",
method: "POST",
dataType: "json",
data: {email: email},
success: function (result) {
alert("result: " + result);
console.log(result);
$("#msg").html(result);
}
});
});
</script>
</body>
</html>
You didn't take value, it's element object, change here
var emailfield = document.getElementById( "emailfield" ).value;
Also put html with value
$('#msg').html(html);
Try it like this.
<html>
<head>
<body>
E-mail: <input type="text" id="emailfield"><br>
<button type="button">Submit</button>
<p id="msg"><p/>
<script
src="https://code.jquery.com/jquery-3.1.1.js"
integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$("#emailfield").on("click",function(){
var value = $("#emailfield").val();
$.ajax({
method: "POST",
url: "work2.php",
data: { email: value }
})
.done(function( data ) {
$('#msg').html(data);
});
});
});
</script>
</body>
</html>
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;
});
});
I am using jquery auto complete to get current data from database in php. But, I am not getting result.
Here is the code sample:
<label class="col-md-4">Referrer</label>
<div class="col-md-6">
<input type="text" name="referrer" id='referrer' placeholder="Type keyword..." autocomplete="off" value="" class="form-control" />
</div>
<script>
var path = $( "#referrer" ).data('path');
$("#referrer").autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/ir_populate_referrer",
dataType: "json",
type: "POST",
data: {
keyword: request.term,
path: path
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label
}
}));
}
})
}
});
</script>
As in my search.php file:
<?php
echo json_encode(array('label'=> $link, 'value' => $keyword));
?>
html
<html>
<head>
<title>test jquery autocomplete</title>
<script type="text/javascript" src="jquery/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery-ui-1.8.2.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#zipsearch").autocomplete({
source: function(req,res) {
$.ajax({
url: "json.php",
dataType: "json",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.label,
value: item.value
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
}
});
});
</script>
<link rel="stylesheet" href="jquery/css/smoothness/jquery-ui-1.8.2.custom.css" />
<style type="text/css">
</style>
</head>
<body>
<form onsubmit="return false;">
Ejemplo<br/>
Enter a Zipcode:
<input id="zipsearch" type="text" />
</form>
</body>
</html>
PHP
<?php
$response = array();
$response[0]=array('label'=>'test','value'=>'test');
$response[1]=array('label'=>'test2','value'=>'test2');
echo json_encode($response);
?>
I've seen some similar questions, but I haven't seen any that specifically speaks to this. I've created a very simple sample, and I feel that it should work, but it doesn't. The point is to see something simple, so that other, similar things are clear.
I feel that this is very 'basic', and it's hard to be much simpler; so, people should be able to get behind it, knowing that it's the ultimate noobie stepping stone:
The HTML and JS:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
$("submit").click(function(){
var req = $.ajax({
type: 'POST',
url: 'form.php',
data: {
message: $('#message').val(),
author: $('#author').val()
},
timeout: 20000,
beforeSend: function(msg) {
$("#sent").html(msg);
}
});
req.fail(function(xhr, ajaxOptions, thrownError) {
alert("AJAX Failed");
});
req.done(function(res) {
$("#received").html(res);
});
});
});
</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form>
Your message: <input type="text" name="message" value="Hi!" /><br />
Your name: <input type="text" name="author" value="Michael" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>
And the PHP:
<?php
echo "The file is located at ".$_POST["message"].".<br>";
echo "The file is named ".$_POST["author"].".";
You can use serialize instead of assigning id to the input fields:
<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
$("#submit").click(function(){
var req = $.ajax({
type: 'POST',
url: 'form.php',
data: $('#frm').serialize(),
timeout: 20000,
beforeSend: function(msg) {
$("#sent").html(msg);
},
success: function(data){
alert('Success!Data was received by php.Message from the php script:'+data.res);
}
});
req.fail(function(xhr, ajaxOptions, thrownError) {
alert("AJAX Failed");
});
req.done(function(res) {
$("#received").html(res);
});
});});
</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form id="frm">
Your message: <input type="text" name="message" value="Hi!" /><br />
Your name: <input type="text" name="author" value="Michael" /><br />
<input type="submit" id="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>
PHP SCRIPT:
<?php
if(isset($_POST['message']) && isset($_POST['author']))
{
$arr_to_pass_as_json = array('res'=>'This is your message:'.$_POST['message'].' and your author '.$_POST['author']);
echo json_encode($arr_to_pass_as_json)
}
else
echo json_encode(array('res'=>'Message and Author is required'));
We use json in displaying result from php to javascript. hope this will help.
Check the difference with this:
$(document).ready(function(){
$("submit").click(function(){
var req = $.ajax({
type: 'POST',
url: 'form.php',
data: {
message: $('#message').val(),
author: $('#author').val()
},
timeout: 20000,
beforeSend: function(msg) {
$("#sent").html(data);
}
})
.fail(function(xhr, ajaxOptions, thrownError) {
alert("AJAX Failed");
})
.done(function(res) {
$("#received").html(res);
});
});
});
Check if this works (According to http://api.jquery.com/jQuery.ajax/#jqXHR it should)
since your using
message: $('#message').val(),
author: $('#author').val()
You will need to specify your id's in you input tgs.
<form>
Your message: <input type="text" name="message" value="Hi!" id="message" /><br />
Your name: <input type="text" name="author" value="Michael" id="author" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
Your asking to find and html id selectyor, and get the value from it, 'name' is NOT the same as an ID.
Alternatively you could put and id on your html form and use .sezialize(), but simply adding an id is simpler at this step.
http://api.jquery.com/serialize/
I'm trying to do some really basic AJAX using PHP & jQuery, but for some reason when I enter text into the input field and click the button I'm always getting null data back. What am I doing wrong?
WebService.php:
<?php
$return['ReturnString'] = $_POST['SearchString'];
for ($i = 1; $i < 100; $i++)
{
$return['ReturnString'] = $return['ReturnString'] . $_POST['SearchString'];
}
return json_encode($return);
?>
HTML:
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
</script>
<script type="text/javascript" src="Scripts/script.js"></script>
</head>
<body>
<form>
<div>
<input type="text" id="txtJavaPHP" />
<input type="button" id="btnJavaPHP" value="Go" />
<br />
<br />
<span id="spanJavaPHP"></span>
</div>
</form>
</body>
</html>
Script.js:
$(document).ready(SetupButtonClicks);
function SetupButtonClicks() {$('#btnJavaPHP').click(DoPHP);}
function DoPHP() {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'WebService.php',
dataType: 'json',
data: {
SearchString: $('#txtJavaPHP').val()
},
success: function (data) {
if (data == null)
$('#spanJavaPHP').text("Data is null");
else
$('#spanJavaPHP').text(data.ReturnString);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#spanJavaPHP').text('There was an error: ' + errorThrown);
}
});
return false;
}
I think the problem lies here, but I have not used AJAX for a while, so I was not able to fully go through the AJAX Code:
echo $return['ReturnString'];
return json_encode($return);
You should be echoing the json_encode($return);
echo json_encode($return);
This should hopefully fix it. Although I do not know why you are looping that data 100 times...but yea.