Posting html form data to php and accessing that through javascript - javascript

I'm trying to post some data to an html form, then that form sends the data to php, and finally javascript takes the data from that php.
This is my html form:
<form action="search.php" method='POST'>
<input id="movie_name" name="movie_name" type="text">
<input name="myBtn" type="submit" value="Submit Data">
</form>
This is my php file which is called search.php:
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo '<script>', 'hello();', 'var movie = '$movie_name';', '</script>';
}
?>
Finally my js script which is in the same file as the php one:
function hello(){
console.log('<?php echo $movie_name?;>');
}
What happens when I load this is that my html redirects ok and then for some in search.php nothing happens, the page goes white and the only thing the console says is "Resource interpreted as Script but transferred with MIME type text/html..."

What exactly you want is not clear. But i suggest you to use jQuery ajax like this:
<input id="movie_name" name="movie_name" type="text">
<input id="myBtn" name="myBtn" type="button" value="Submit Data">
$('#myBtn').click(function(e){
var movie_name = $('#movie_name').val();
$.ajax({
url: "search.php",
type: "POST",
data: {
'movie_name': movie_name
},
beforeSend : function() {
},
success : function(response) {
console.log(response);
},
error : function()
{
},
complete : function() {
}
});
});
in your search.php
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo $movie_name;
}
?>
This is better way from my point of view.

This should work:
<?php
if (isset($_POST['movie_name'])){
$movie_name = $_POST['movie_name'];
}
?>
<script type="text/javascript">
function hello(){
console.log('<?php echo $movie_name; ?>');
}
</script>
<?php
echo '<script> alert("'.$movie_name.'"); hello(); </script>';
?>

Related

Ajax and jQuery with PHP

I have this code which posts data using jQuery and ajax to itself.
<input type="button" id="butt" value="button11111111111111" >
<script>
$("#butt").on('click',function(e)
{
$.ajax(
{
type:'POST',
url:'test.php',
data:product_type:"cake"
});
});
</script>
<?php
if(isset($_POST['product_type']))
$abc=$_POST['product_type'];
if(isset($abc))
echo $abc;
?>
Now when I try to run this code.I do get the ok status inside the Network Console of Chrome but this code doesn't echo the output.
I simply want to display the result that has been passed by the ajax method.
I am new to ajax and jquery so i don't know much about how they work exactly but is it possible?
If yes, then how could i achieve that without actually refreshing the page?
Here is what I think you want, i.e. test.php is the source page AND the ajax page!
<?php
if(isset($_POST['product_type'])) {
Header("Content-type: text/plain; charset=utf-8");
$abc=$_POST['product_type'];
if(isset($abc)) {
echo $abc;
}
}
else {
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<input type="button" id="butt" value="button11111111111111" >
<script>
$("#butt").on('click',function(e) {
$.ajax({
type:'POST',
url:'test.php',
data: {
product_type:"cake"
},
success: function(data) {
alert('got ' + data);
}
});
});
</script>
</html>
<?php
}
?>

how to get json/array from ajax responseText in to javascript array

I am using codeigniter in my project.When I am trying to get array element from encoded array, something id going wrong.How can I get encoded json array in my javaScript?
index.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function sendMessage(){
var message=document.getElementById('chatInput').value;
var receverID=document.getElementById('id').value;
if(message==''){
alert("please enter message");
}
new Ajax.Request('index.php', {
method:'get',
evalJSON: true,
parameters: {
message: message,
id: receverID
},
onSuccess: function(transport){
var data= transport.responseText;
console.log(data);
},
onError: function() {
alert('Error');
},
onComplete: function() {
}
});
}
</script>
</head>
<body>
<textarea name="chatInput" id="chatInput" cols="60" rows="3"></textarea><br />
<input type="button" name="send_message" onclick="sendMessage()" Value="Send"/>
<input type="hidden" id="id" name="id" value="5">
</body>
</html>
index.php
<?php
header('Content-type: application/json');
$data['message'] = $_GET['message'];
$data['sender_id'] = $_SESSION['id'];
$data['user_id'] = $_GET['id'];
$this->model_users->setMessage($data);
echo json_encode($data);
?>
Based on your comment, it seems that you have a HTML in your response. It's a good practice to put exit after json_encode call when you expect JSON response.
Try to put this in your index.php and it should works:
echo json_encode($data);
exit; // terminate the current script

How to send data via ajax?

I'm trying to learn how does Ajax work and how I can send data by Ajax. I'm getting no error and nothing is being echoed.
index.html
<input id="name" type="text" /><input id="button" type="button" value="Load" />
<div id="feedback"></div>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
page.php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
}
?>
ajax.js
$('#button').click(function(){
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: 'name='+name,
success: function(data){
$('#feedback').html(data);
}
});
});
I appreciate any help
You are missing an echo in your page php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
echo $name;
}
?>
also in your javascript send an object like this
data : { name : name}
should work
data : { name : 'John'}
you can check the success method is invoked or not invoked.
Also you need to echo something from php.
echo $name

How to call output of a php page in an html page in a specific div?

This is my html code
<html>
<body>
<form name="form1" action="php1.php" method="post">
<input type="text" name="text1">
<input type="submit" name="submit1">
</form>
<div id="div1">
</div>
</body>
</html>
This is my php1.php code
<?php
if(isset($_POST['submit1']) && ($_POST['text1'])=="text"){
echo "hello";
}
?>
If I want to call the output of php1.php i.e., hello, in html div1 what to do ?
#Uzumaki, I've edited my html code like this, but its not working, here is my code.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
$("form#postit").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "hello.php",
type: 'POST',
data: formData,
async: false,
success: function (data)
{
// $("#div1").append(data); // or
$("#div1").html(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
</head>
<body>
<form name="form1" method="post" id="postit">
<input type="text" name="text1">
<input type="submit" name="submit1">
</form>
<div id="div1">
</div>
</body>
</html>
Since you didn't mention via jquery or ajax I am assuming you are going with a simpler old fashioned way So here is the code
SEND YOUR MESSAGE BACK TO HTML PAGE LIKE THIS
$msg = "hello"
header("Location: your_html_page.html?msg=".$msg);
IN HTML DO THIS
<div id="div1">
<?php
error_reporting(0);
echo $_GET['msg'];
?>
</div>
USING JQUERY :
Post the data to php
$.post("your_php_page.php",{data:data},function(returned_data_from_php){
$("#div1").append(returned_data_from_php); // or
$("#div1").html(returned_data_from_php);
});
Using Ajax
$("form#postit").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "your_php_page.php",
type: 'POST',
data: formData,
async: false,
success: function (returned_data_from_php)
{
$("#div1").append(returned_data_from_php); // or
$("#div1").html(returned_data_from_php);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
PHP
what ever you want to return from php it should be echo and there are many ways to do that
(Single string) echo "Success";
(Multiple Strings) echo $msg1.$msg2;
(Array data)
for example ...
$data = array();
$i = 0;
while($numbs = mysql_fetch_array($result))
{
$row_numb = $numbs['id'];
$data[$i] = $row_numb;
$i++;
}
echo json_encode($data);
// this will pass a json type object to the java script
When you get to javascript you want to access all the elements of the array one by one well that's easy too
JAVASCRIPT
parsed_it = JSON.parse(data); // data is the json type you got from your php
so parsed_it[0],parsed_it[1],parsed_it[2] and so on you can access all the data
hope it helps !!
Put the PHP into your HTML file where you want the result. Be sure your file is named something.php and that you have a PHP processor on the server.
<html>
<body>
<form name="form1" action="php1.php" method="post">
<input type="text" name="text1">
<input type="submit" name="submit1">
<div id="div1">
<?php
if(isset($_POST['submit1']) && ($_POST['text1'])=="text"){
echo "hello";
}
?>
</div>
</body>
</html>
You may use AJAX to dynamically load script output:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get
You may also consider using jQuery to simplify your code:
http://api.jquery.com/jquery.get/

Using AJAX to post form data to PHP page

I am simply trying to use the data submitted in a search form to query the database and bring back results similar to the search. My form looks like this:
<div id="searchform">
<form method="get">
<form id="submitsearch">
<input id="shop" name="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="submit" value="Go"/>
</form>
</form>
<div id="searchresults">
</div>
</div>
the Javascript I've got is:
$("#submitsearch").submit(function(event) {
event.preventDefault();
$("#searchresults").html('');
var values = $(this).serialize();
$.ajax({
url: "external-data/search.php",
type: "post",
data: values,
success: function (data) {
$("#searchresults").html(data);
}
});
});
return false;
I have also tried...
$("#submitbutton").click(function(){
var form_data = $("#submitsearch").serialize();
$.ajax({
url: "external-data/search.php",
type: 'POST',
data: form_data,
success: function (data) {
$("#searchresults").html(data);
}
});
return false;
});
And this seems to work slightly as it shows results, the first doesn't do anything. It's not sending the data to the PHP page but the PHP I've got is:
<?php
$str_shops = '';
$shop = $_POST['form_data'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE name LIKE '%$shop%'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shops;
mysqli_close($db_server);
?>
Any help would be greatly appreciated! Thanks in advance.
You have two form tags. This won't work. You want one form tag with two attributes
<form method="get">
<form id="submitsearch">
to
<form method="get" id="submitsearch">
you can do it without using html form.
first you call the php page and then display a data within html.
this is what I do?!
<div>
<input id="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="button" value="Go"/>
</div>
<div id="searchresults">
</div>
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function(){
try
{
$.post("root/example.php",
{
'shop':$("#shop").val().trim()
}, function(data){
data=data.trim();
$("#searchresults").html(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

Categories

Resources