Get the Echo from PHP into a Div with Ajax - javascript

I have a simple Database on a Server (for Testing).
This PHP File is on the Server and works when I open the URL. (http://**.com/search.php?id=abc) Echo gives back "30"
<?php
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$idV = $_GET['id'];
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{ $posV = $row['position']; };
echo $posV;
?>
The HTML is just for Testing
<input type="text" id="txt1">
<button type="button" class="btn btn-info" id= "bt1">Info Button</button>
<div id= "div1"> </div>
I want that when i enter a Code in the Textfield and press the Button, the Echo from the PHP is Displayed in the Div.
I know i should use Ajax GET, but i tried so many things and nothing worked.
Could you help me pls?
Edit: Last try: https://jsfiddle.net/qz0yn5fx/
<input type="text" id="txt1">
<button type="button" class="btn btn-info" id="bt1">Info Button</button>
<div id="div1">Here </div>
<script>
$(document).ready(function() {
$("#bt1").click(function() {
$.ajax({
//create an ajax request to load_page.php
type: "GET",
url: "http://**.com/search.php?id=a10 ",
dataType: "html", //expect html to be returned
success: function(response){
$("#div1").html(response);
alert(response);
}
});
});
});
</script>
Better dont look at the next Fiddle i just copied all first Tries:
https://jsfiddle.net/jqv1ecpj/

You could just use a simple POST request instead of a GET request.
<form id="search" name="search" method="post">
<input type="text" id="txt1" name="search_input">
<button type="submit" class="btn btn-info" id="bt1">Info Button</button>
</form>
<div id="div1">Here </div>
$(document).ready(function(){
$("#search").on("submit", function(e){
e.preventDefault();
$.post("/search.php", $("#search").serialize(), function(d){
$("#div1").empty().append(d);
});
});
});
And then in your PHP, (don't forget to use try{}catch{}):
try {
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty');
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->bindParam(1, $idV);
$statement->execute();
foreach($statement -> fetchAll() as $row){
echo $row['position'];
}
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
I think this should work (haven't tested it). Let me know if it doesn't work and I'll test and correct it.

Related

Trying to change the content of a page without reloading after passing a value to a variable on submit

Retrieving data from an API using Php. This my code:
<?php
if(isset($_POST['search']))
{
$login = 'something';
$password = 'something';
$query = urlencode( $_POST[ "search"]);
$url = 'something' . $query;;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
$result = curl_exec($ch);
curl_close($ch);
$output = json_decode($result, true);
foreach ($output['response']['customers']['customer'] as $r)
{
$inner = $r['lifetime_points'];
};
}
else
{
echo ("No search query has received");
}
?>
Html code:
<div id="get_text" >
<div><em>CHECK YOUR POINTS</em></div>
<div ><em>Enter mobile number</em></div>
<form action='' method='POST' id='search-form'>
<div>
<input type='search' name='search' id="sub1" />
</div>
<div>
<button type="submit" id="sub" >Submit</button>
</div>
</form>
</div>
<div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>
So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#show_text").hide();
$("#sub").on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'aristocracy-test.php',
method: 'POST',
data : $("#get_text").serialize(), //pass your form elements as key-value pairs
success: function (response) {
$("#show_text").show();
$("#get_text").hide();
}
});
});
});
</script>
The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.
I think you forgot to set the response to the div after showing the div .
Please add $("#show_text").html(response); after showing the div.
If you want to show the result in textbox . Use
$('input[name="textboxname"]').val( response ) ;
then your code will be like.
success: function (response) {
$("#show_text").show();
$('input[name="textboxname"]').val(response) ;
$("#get_text").hide();
}
Just add $("#show_text").html(response); in your ajax success method.
Or perhaps you should try this $('input[name=points]').val(response);
You are not getting in your div with id show_text because you did not insert the new data in it :
You need to call $("#show_text").html(response); in order to set new data something like:
success: function (response) {
$("#show_text").show();
$("#show_text").html(response);
$("#get_text").hide();
}
});
Also it will remove anything in that div so :
<div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>
becomes :
<div id="show_text" >
//HERE WILL BE YOUR NEW DATA WHICH CAME FROM AJAX
</div>
UPDATE
You are not sending proper data in your ajax params:
data : $("#get_text").serialize(),
This wont do.
change it to :
data:{
search : $('#sub1').val()
}
Please Check your Data posted to server ,Data Returned from server in Browser console .

Submit PHP Prepared statement with ajax

First i am just learning about PHP prepared statements and sql injection. And my first question is, is this php code good enough to stop sql injection. And my second question how do i submit this php statement with Ajax. Thanks in advance
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['submit_req']))
{
$req_title = $_POST['req_title'];
$req_min = $_POST['req_min'];
$req_entry = $_POST['req_entry'];
$req_payment = $_POST['req_payment'];
$post_req = $_POST['post_req'];
$stmt = $db->prepare('INSERT INTO users_request (req_title, min_order, poi, pay_method, req_brief) VALUES (:req_title, :min_order, :poi, :pay_method, :req_brief)');
$stmt->bindValue(':req_title', $req_title, SQLITE3_TEXT);
$stmt->bindValue(':min_order', $req_min, SQLITE3_TEXT);
$stmt->bindValue(':poi', $req_entry, SQLITE3_TEXT);
$stmt->bindValue(':pay_method', $req_payment, SQLITE3_TEXT);
$stmt->bindValue(':req_brief', $post_req, SQLITE3_TEXT);
$result = $stmt->execute();
if ($result)
{
echo "<p>Request post successful</p>";
}
}
Ajax code i have tried but didn't work
$('#post_form').submit(function () {
$.ajax({
url: "req_exec.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
$('.success').html(data);
}
});
The form
<div class="success"></div>
<div class="post_req">
<form action="req_exec.php" method="post" enctype="multipart/form-data" id="post_form">
<input type="text" name="req_title" id="req_title" placeholder="Request title. (Example: Dried Cashew Nuts)">
<input type="text" name="req_min" id="req_min" placeholder="Minimum Order. (Example: 2 Tons, 7800 units, 40 container, 1 Barrel)">
<div class="form_division">
<input type="text" name="req_entry" id="req_entry" placeholder="Point of Entry">
<input type="text" name="req_payment" id="req_payment" placeholder="Payment Method">
</div>
<textarea name="post_req" id="post_req" placeholder="Briefly describe your request" rows="6"></textarea><br>
<input type="submit" name="submit_req" id="submit_req" value="Post Request">
</form>
</div>
Thanks in advance.

Dynamic form and send to mysql via jquery and ajax

I have already asked some questions about this, I was helped, but kind of the way they said it only works if the form is normal, with inputs with name "something here" my form only has an input "text" name "table" to put The table number the rest of the form comes via mysql ajax. My question is how can I pass this form to the database since it is dynamic? My code below.
My form
<div class="well">
<!-- left -->
<div id="theproducts" class="col-sm-5">
</div>
<!-- left -->
<form method="post" action="relatorio.php" id="formRel">
<span>Mesa</span>
<input type="text" id="numero_mesa" name="numero_mesa">
<input type="text" id="theinputsum">
<!-- right -->
<div id="thetotal" class="col-sm-7">
<h1 id="total"></h1>
<button type="submit" class="btn btn-lg btn-success btn-block"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Finalizar Pedido</button>
</form>
</div>
<!-- right -->
</div>
And the javascript code.
<script>
$('#formRel').submit(function(event){
event.preventDefault();
var formDados = new FormData($(this)[0]);
$.ajax({
method: "POST",
url: "relatorio.php",
data: $("#formRel").serialize(),
dataType : "html"
})
};
</script>
The insert query is like this.
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
//Criar a conexao
$link = new mysqli ("localhost", "root", "", "restaurant");
if($link->connect_errno){
echo"Nossas falhas local experiência ..";
exit();
}
//echo "<pre>"; print_r($_POST); exit;
$mesa = $_POST['numero_mesa'];
$pedido = $_POST['products'];
$preco = $_POST['products'];
$sql = "INSERT INTO spedido ('pedido','preco','numero_mesa') VALUES ('$mesa','$pedido','$preco')";
$link->query($sql);
?>
enter image description here
<script>
$(document).on('submit', '#formRel', function(event) {
event.preventDefault();
var numero_mesa = $('#numero_mesa').val();
$.ajax({
type: "POST",
url: "relatorio.php?",
data: "numero_mesa="+ numero_mesa+
"&products="+ products,
success: function (data) {
alert(data) // this will send you a message that might help you see whats going on in your php file
});
})
};
</script>

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

Ajax call successful, but can't get radio values from $_POST

My site is fully asynchronus, most of the html gets created and destroyed on button presses and every one of them prevents navigation.
At this part I produce a form with a "rate 1 to 10" array of radioboxes, post it using jQuery.ajax() and send it to process where it's either echoed back (for now) or echo "nothing was selected.".
This is the form,
<?php
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">';
for ($i = 0; $i <= 10; $i++) {
echo '
<span class="lead form-options">' .'</span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio'. $i .'" value="'. $i .'">'. $i.'
</label>';
}
echo '
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
?>
This is the javascript:
$('body').on('click', '.surveyForm', function(){
console.log("Clicked on .surveyForm-btn");
var data = $('#surveyForm').serialize();
console.log( data );
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log("Ajax call to processSurvey success");
$("#surveyForm").clearForm();
console.log(result);
console.log( data );
}
});
return false;
});
And this is the process php:
<?php
if (isset($_POST['sabor'])) // if ANY of the options was checked
echo $_POST['sabor']; // echo the choice
else
echo "nothing was selected.";
print_r($_POST);
?>
This is the console after clicking submit WITH a selected radiobox:
Clicked on #surveyForm
[EMPTY LINE]
Ajax call to processSurvey success
nothing was selected.
[EMPTY LINE]
This means the submit is successful, but the form data is empty. I've been trying to find the problem since yesterday, I'm pretty sure I'm passing the data wrong but can't find anything in google that I haven't tried.
EDIT: Added most sugestions, problem persists. Maybe the html structure is wrong? The form and the submit don't seem to be connected.
EDIT 2: I found something very strange, on the final code there seems to be an extra closing tag, like this
<form id="surveyForm" action="processSurvey.php" method="post"></form>
<h3>Alimentos</h3>
<h4>Sabor</h4>
I have no idea where is that coming from, but is defenitely the problem.
there are a lot of notes here
1- you will get confused with form id='surveyForm' and button class='surveyForm' so its better to change it a little bit to button class='surveyForm_btn'
2- I think you should serialize the form not the button
var data = $('#surveyForm').serialize(); // not .surveyForm
3- IDs must be unique
4- $("#surveyForm").clearForm(); // not .surveyForm
finally check all comments
and Its better to use
$('body').on('submit', '#surveyForm', function(){});
Edited answer:
1- please check everything after each step
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
in js
$('body').on('submit', '#surveyForm', function(){
var data = $(this).serialize();
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log(result);
}
});
return false;
});
in php
<?php
echo 'Connected successfully';
?>
this code will output Connected successfully in console .. if this work add your for loop and make a check again
Try to write your htm like that :
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<?php
for ($i = 0; $i <= 10; $i++) {
?>
<span class="lead form-options"></span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio<?=$i ?>" value="<?= $i ?>" /><?= $i?>
</label>
<?php
} ?>
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>

Categories

Resources