I am attempting to send data from a form to another page(on the same server) and have that page load within a div on the main index page. When I submit the data it is being processed but the div is not updating to reflect a new page has been loaded in it.
form-page.php
<script>
$(document).ready(function() {//start document ready
$('#review-submit-button').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'pages/firstdeploy/deploy-sequence-finalize1.php',
data: $("#masteraccountsetup").serialize(),
success: function(response){
$("#primary-display").html(response);
}
});
});
});//end document ready
</script>
processing-form-page.php
<?php
$con=mysqli_connect("localhost","***","***","***");
if (!$con){
die("Database Connection Failed" . mysqli_error());
};
// escape variables for security
$companyname = mysqli_real_escape_string($con, $_POST['review-
companyname']);
$jobtitle = mysqli_real_escape_string($con, $_POST['review-jobtitle']);
$masteraccount = mysqli_real_escape_string($con, $_POST['review-username']);
$masteremail = mysqli_real_escape_string($con, $_POST['review-email']);
$masterpassword = mysqli_real_escape_string($con, $_POST['review-
masterpassword']);
$sql = "INSERT INTO accounts (username, password, company, position, email)
VALUES ('$masteraccount','$masterpassword',
'$companyname','$jobtitle','$masteremail')";
mysqli_query($con,$sql);
echo $companyname;
echo "<br>";
echo $masteraccount;
echo "<br>";
echo $jobtitle;
echo "<br>";
echo $masteremail;
echo "<br> test";
echo $masterpassword;
$con->close();
?>
Now the processing page works when I independantly go to it and it also works when submitted through the form page. The issue is, that it is not updating in to #primary-display from the index page. The form-page.php is loaded into the #primary-display div at the start of the form sequence.
edit: added index page
<div id="primary-holder" class="prima-hold">
<div id="primary-display">
<?php
// Start the Session
session_start();
$con=mysqli_connect();
if (!$con){
die("Database Connection Failed" . mysqli_error());
};
$query = "SELECT * FROM accounts";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
if($count > 0){
//Display if there is already a restaurant placed in the system
echo "
<script>
$(\"#primary-display\").load(\"pages/security/mainentrance.php\");
</script>
";
}else{
// Display if no restaurants have been placed in the system
echo "
<script>
$(\"#primary-display\").load(\"pages/firstdeploy/intro.php\");
</script>
";
};
?>
</div>
</div>
you can try:
$.ajax({
type: 'POST',
url: 'pages/firstdeploy/deploy-sequence-finalize1.php',
data: $("#masteraccountsetup").serialize(),
dataType: 'html',
success: function(response){
$("#primary-display").html(response);
}
If ajax dataType is set as text or html, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.
from here
Related
I have a list of divs with unique IDs (they are inserted from my database). When I click on one of them I want to display content from my database in another div. For example, I have a div with class pizza. The query should look like this: SELECT * FROM product WHERE name = 'pizza'. So depending on what div you click you get different content. The code below doesn't work and is incomplete. I was trying to do some research myself, but I couldn't find anything useful.
//head
<script>
$(function () {
$('.product').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
},
error: function () {
}
});
});
});
</script>
//HTML
<div class="product" id="pizza">pizza</div>
<div class="product" id="lasagna">lasagna</div>
<div class="product" id="sushi">sushi</div>
<div class="display_recipe"></div>
// PHP (recipe-container.php)
<?php
function display_recipe(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = "'pizza'"; //just a placeholder
$sql = "SELECT * FROM product WHERE name = $product";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$name = $row['name'];
$description = $row['description'];
$date = $row['date'];
echo $name;
echo "<br>";
echo $description;
echo "<br>";
echo $date;
echo "<br>";
}
mysqli_close($con);
}
display_recipe();
?>
Right now when I click the button nothing happens, even "pizza" placeholder doesn't work. Is there a simple way to do it?
JS file (AJAX code)
You can get the id attribute on click of the div with the class 'product' as coded below:
jQuery(function () {
jQuery('.product').on('click', function (e) {
var product = jQuery(this).attr('id');
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: {data:product},
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
}
});
});
});
PHP file: get the posted data in this file use it in a query to fetch the result and return the result to the AJAX success handler as a response.
To fetch the data posted from the ajax in this php file you can use $_POST['data'] as stated below:
$product = $_POST['data'];
Use that variable in your sql query to fetch the result and then change the structure of your response as stated below:
//saving the html response in a variable named "response"
$response = $name.'<br>';
$response .= $description.'<br>';
$response .= $date.'<br>';
//echo response will send the response variable back to the AJAX success handler.
echo $response;
I have this strange issue, happening to my PHP script, On page load the AJAX script runs and also after the second time the AJAX script runs it works and sends data to PHP, but i seem to not understand why the PHP script doesn't process the incoming POST request the second time it is sent in when i clean the input text box and type again, i get a blank response.My code for more expatiation.
index.php :
<input type="text" onkeyup="searchmedia(this)" placeholder="Search for seller with UNIQUE ID or Name.">
<div id="resut" style="margin-top:-24px!important;">
//where the ajax result is returned
</div>
<div style="margin-top:-24px!important;" id="normal">
//bla bla data here
</div>
<div id="hui" style="display:none;"><img src="../ajax5.gif">
</div>
<script>
function searchmedia(e) {
var tuq = $(e).val();
if (tuq == "") {
$('#resut').hide();
$('#normal').show();
$('#hui').hide();
} else {
$('#normal').hide();
$('#hui').show();
$.ajax({
type: 'POST',
url: 'sellersmessageajax.php',
data: {tuq: tuq},
timeout: 5000,
cache: false,
success: function (r) {
//console.log(r);
$('#resut').html(r);
$('#normal').hide();
$('#hui').hide();
},
error: function () {
alert("Could not search, reload the page and try again.");
$('#normal').show();
$('#hui').hide();
}
});
}
}
</script>
sellersmessageajax.php :
<?php include('../connect.php'); ?>
<?php
if (isset($_POST['tuq']))
{
$term = $_POST['tuq'];
$term = mysqli_real_escape_string($con,
$term); //WHEN I ALERT HERE THE SECOND TIME I SEE THE INPUT TEXT DATA THAT CAME IN BUT PLEASE CHECK AFTER THE **FOREACH**
$condition = '';
$query = explode(" ", $term);
foreach ($query as $text)
{
$condition .= "name LIKE '%" . mysqli_real_escape_string($con,
$text) . "%' OR reign_uniqeer LIKE '%" . mysqli_real_escape_string($con, $text) . "%' OR ";
}
//WHEN I ALERT HERE I GET NOTHING
$condition = substr($condition, 0, -4);
$zobo = "ORDER BY name";
$sql_query = "SELECT * FROM sellers_login WHERE " . $condition . $zobo;
$result = mysqli_query($con, $sql_query);
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$v_ida = $row['id'];
$v_namea = $row['name'];
$v_reign_uniqeera = $row['reign_uniqeer'];
?>
<div style="border-bottom:0.1px solid #eee;padding-bottom:20px;margin-top:20px;">
<a class="zuka" title="<?php echo $v_ida ?>" id="<?php echo $v_ida ?>"
style="color:#666;text-decoration:none;outline:none!important;cursor:pointer;">
<b style="color:blue;"><?php echo $v_namea ?></b>
<br/>
<div style="height:auto;max-height:30px;">
<b>UNIQUE ID :</b> <b style="color:red;"><?php echo $v_reign_uniqeera ?></b>
</div>
</a>
</div>
<?php
}
}
else
{
?>
<h1 class="zuka" style="text-align:center;margin-top:20%;"> No result found.</h1>
<?php
}
}
?>
Second time after clearing the data result set to hide. second time data is returning but it's hide
Add this line in ajax success block
$('#resut').show(); // Add this line
you are sending the var tuq wrongfully. Try this:
data : {"tuq": tuq}
I am trying to call a stored procedure in php-myadmin from wordpress website to check user login details.
I have a button that points to javascript function:
<input type="submit" value="Login" onclick="checkloging()">
The javascript file contains ajax:
function checkloging() {
$.ajax({
type: "POST",
url: 'checklogin_php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
The ajax code is to call a php file:
<?php
//Call the proc() procedure follow
$result= mysql_query("CALL checkpassword('username', 'password');") or die(mysql_error());
while($row = mysql_fetch_row($result))
{
for($i=0;$i<=6;$i++)
{
echo $row[$i]."<br>";
}
}
mysql_close($con);
?>
which invokes a stored procedure in phpmyadmin.
Please can any anyone help with this? I am not not sure if this is a good approach and I'm not getting it to work.
This might help you.
Note: Use and read more about mysqli
<?php
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db");
//call and run the store proc
$result = mysqli_query($connection,
"CALL checkpassword") or die("Query fail: " . mysqli_error());
//loop the result set
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
mysql_close($con);
?>
I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".
Ok so I have:
A PHP file that queries a database and displays the results of the query,
a HTML file that displays the results using AJAX and
another PHP file that I need to send the data from the first PHP file to.
How can I do this?
My first PHP file displays:
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div class='result'><a id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></a>";
}
So the AJAX brings this in and displays it in the HTML. Is there a way of sending the ID field when the link is clicked so that it can be used in another PHP file to display the data for that specific ID.
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: $("#hiddenid"),
success: function (data) {
$("#individualshop").load("external-data/shop.php");
}
});
So that the data from the #hiddendiv ($row ['ID']) will be sent to the new PHP file. This isn't working.
shop.php has the code:
//get shop ID
$shopid = $_POST['ID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE ID='$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='searchresult'><strong>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div>";
}
But I'm not sure how to retrieve the ID?
Basically I need to be able to click on each search result and have another PHP file bring in specific data associated with the ID of the search result. Any suggestions??
Thanks in advance!
I'm not 100% sure this is what you want but this is one way.
This is your first php file. I've added an onclick listener to it so when a user clicks a row it will fire a JavaScript passing the $row['id'] variable.
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div onclick='someFunction(" . $row['id'] . ")' class='result'><div id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></div>";
}
Then add this script to the header of the page.
<script>
function someFunction(d){
var response = httpGet("http://yourdomain.com/newphpfile.php?page_id=" +d);
document.getElementById('someResultArea').innerHTML = response;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
Then your new php file should do something like this.
newphpfile.php
<?php
session_start();
$page_id = strip_tags($_GET['page_id']);
$processResult = 'handle your result';
echo $processResult;
?>
I hope this helps you out.
Use this;
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: "ID=" + $("#hiddenid"),
success: function (data) {
$("#individualshop").html(data);
}
});
});
Note: Do not forget to return html in shop.php
You can fetch the clicked element id by using either javascript or jquery, and put it in the GET parameters on the php link
the ajax target would be ajax.php?id=test
Then get the value of id via $_GET['id']