How to use AJAX to display the data retrieved by html-don? - javascript

I have 3 files: index.html, parse.php, profile.html
index.html: It has a form, where I give the link of profile.html and with the html-dom parsing in parse.php, I should get all the data on the same page, i.e index.html.
I am new to AJAX and did not use it till now.
How should I go through on doing the operation?
index.html:
<form action="parse.php" method="post" id="myForm">
Name: <input type="text" name="uurl"><br>
<input type="submit">
</form>
parse.php:
require 'simple_html_dom.php';
$url = $_POST['uurl'];
$html = file_get_html($url);
foreach ($html->find("span[class=full-name]") as $key => $name){
echo $name."<br>";
}
script:
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>

index.html:
<form action="parse.php" id="myform" method="post">
Name: <input type="text" name="uurl" id="uurl"><br>
<input type="button" value="" >
</form>
<ul class="results"></ul>
Include jquery script tag, and add the following javascript code:
$(document).ready(function() {
$('#myform button').on('click', function() {
$.getJSON('/parse.php', { uurl: $('#uurl').val() }).done(function(a) {
var html = '';
if (a.results && a.results.length > 0) {
for (var i in a.results) {
html += '<li>' + a.results[i] + '</li>';
}
} else {
html += '<li class="error">No Results Found</li>';
}
$('ul.results').html(html);
});
});
});
In parse.php:
require 'simple_html_dom.php';
$url = $_POST['uurl'];
$results = array();
$html = file_get_html($url);
foreach ($html->find("span[class=full-name]") as $key => $name){
$results[] = $name;
}
echo json_encode(array('results' => $results));

So technically you aren't even using AJAX. Ajax is based on javascript and I don't see any javascript in your code.
Also, from what I understand, you don't need any PHP code to do what you're trying to.
Here is how you would do it. This would be the HTML.
<form action="parse.php" method="post">
Name: <input type="text" name="uurl" id="uurl"><br>
<input type="submit" id="submit-form">
</form>
<div id="container">
</div>
And then you would need this javascript:
var $url = $('#uurl');
var $button = $('#submit-form');
var $container = $('#container');
$button.on('submit', function(evt){
evt.preventDefault(); //to prevent the default form submission.
$.get($url.val(), function(response){
$container.html(response);
})
});
I have used jQuery for clarity, but it definitely not required.

Related

delete of instant search content with the delete of keyword

so i have search function with jquery to display instantly the content of what i search it is simple one here is the code:
function searchq() {
var searchTxt = $("input[name='search']") .val();
$.post("search.php", {searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
I use php for backend
<?php
$nonavbar = '';
include "init.php";
$output = '';
if (isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$stmt3 = $con->prepare("SELECT * FROM novel WHERE NovelName LIKE '%$searchq%'");
$stmt3->execute();
$rows = $stmt3->fetchAll();
$count = $stmt3->rowCount();
if ($count == 0) {
$output = "there is no search results!";
}else{
foreach ($rows as $row) {
$fname = $row['NovelName'];
$output .= "<div>
<ul>
<li>" . $fname . "</li>
</ul>
</div>";
}
}
}
echo ($output);
?>
and this is the html form for search
<form action="index.php" method="post">
<input type="text" name="search" class="form-control" autocomplete="off" placeholder="search novelname.." onkeydown="searchq()">
</form>
<div id="output" class="searchresult"></div>
everythong is work fine but I need to add function for delete the result when user delete the keywords for search bar honstly i didnt know much about javascript but the search work fine andi need to add this function plz help and thank
Instead of onkeydown use onblur event
<input type="text" name="search" class="form-control" autocomplete="off" placeholder="search novelname.." onblur="searchq()">
To clear the output use the method like below,and same funtion will work for onkeydown as well, but it is better to use blur event instead of onkeydown.
function searchq() {
var searchTxt = $("input[name='search']").val();
if(!searchTxt) { $("#output").html(""); return; }
$.post("search.php", {searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}

PHP stored procedure called and working, page reload doesn't show new data

I am calling a JS function using a form:
HTML form:
<form class="addBlock" method="post" name="addBlockForm">
<input type="image" id="addBlockBtn" name="addedBlock" src="images/addCassette.png" onclick="addBlock( <?php echo $rowSize + 1 ?>)">
<input type="hidden" name="specNum" value="<?= $_SESSION["specNum"] ?>">
</form>
Javascript function:
function addBlock(num) {
var form = document.forms['addBlockForm'];
var nb = document.createElement("input");
nb.type = "hidden";
nb.name = "NewBlockNum";
nb.value = ([num]);
form.appendChild(nb);
addBlock.submit();
}
Which submits the form, triggering the Php stored procedure and refreshes the page
PHP Stored procedure:
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['NewBlockNum'])) {
// run the stored procedure for adding a new block
$callSP_addBlock = "{ CALL AddBlockByID( ?, ?, ? ) }";
$accID = $row[12];
$spID = $row[13];
$nBlockNum = $rowSize + 1;
$ad_params = array(
array($accID,SQLSRV_PARAM_IN),
array($spID, SQLSRV_PARAM_IN),
array($nBlockNum, SQLSRV_PARAM_IN),
);
/* Execute the query. */
$stmt6 = sqlsrv_query( $conn, $callSP_addBlock, $ad_params);
header('Location: '.$_SERVER['PHP_SELF']);
if( $stmt6 === false ) {
echo "Error in executing statement 6.\n";
die( print_r( sqlsrv_errors(), true));
}
}
The order on the page is the Php, then the JS function definition, and then the html form.
Everything works, however the new added data does not display in the page.
The data display code (that lives after the JS function, but before the form) is this
PHP Data display code:
<?php
do {
if (isset($row[15])) {
$timeStamp = //date_format($row[15], 'Y-m-d h:i');
$printedLabel = 'Printed ';
$printedClass = 'printed';
} else {
$timeStamp = '';
$printedLabel = '';
$printedClass = '';
}
if (isset($row[14])) {
$numOfPieces = $row[14];
$piecesLabel = 'Pieces ';
} else {
$numOfPieces = '';
$piecesLabel = '';
}
echo '<div class="'.$printedClass.'cassetteDataRow">
'.$row[9].'<br>
<form action="#" class="printForm" method="post" name="printedCass"><br>
<input type="image" id="cassPrintBtn" name="cPrinted" src="images/cassetteIcon.png" onclick="cassPrint(1)"><br>
<input type="hidden" name="'.$row[0].'" value="'.$row[0].'"><br>
<input type="hidden" name="specNum" value="'.$specNum.'"><br>
<input type="hidden" name="BlockID" value="'.$row[10].'"><br>
</form><br/>
'.$numOfPieces.' '.$piecesLabel.'<br>
'.$printedLabel.' '.$timeStamp.'
<input type="image" id="cassInfoBtn" src="images/cassettePrintBtn.png" onclick="div_show('.$row[10].')">
</div> <br/>';
} while ($row = sqlsrv_fetch_array($stmt));
?>
I have tried moving the php for the stored procedure call below the form (didn't work),I tried form action to $_SERVER['PHP_SELF'] and location.reload(); (also didn't work).
Any advice is greatly appreciated.Thank you

PHP form stay on same page

Hi i am trying to update data in a database from a form on the same page as the php code without redirecting/reloading the page.
I tried this tutorial but that didn't work: http://www.formget.com/form-submit-without-page-refreshing-jquery-php/
Update code:
<?php
include "db.php";
session_start();
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
?>
Profilecomplete.js:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {
value: name
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
The form:
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate">
<label for="name">Value</label>
</div>
<button type="submit" id="submit" class="btn-flat">Update</button>
</form>
Use this, it's working already.
index.php
<form method="post">
<input type="text" id="name">
<input type="submit" id="submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var nameInput = $("#name").val();
var name = {
'name' : nameInput
}
if (nameInput == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {value: name}, function(data) {
alert(data);
//$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
profilecomplete.php
<?php
$_POST = array_shift($_POST); // array_shift is very important, it lets you use the posted data.
echo $_POST['name'];
?>
if you want a more simple way.
try to use $.ajax()
It looks like the issue, or at least, one of the issues, is on this line;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
You are opening and closing the single quotes twice, here
WHERE username='$_SESSION['user']'
Try using this instead;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='" . $_SESSION["user"] . "'");
How your click event can occur even if you are not preventing the default behavior of the form submit button. Make the submit input as a button or use event.preventDefault() to submit the form via ajax.
<?php
include "db.php";
session_start();
if(isset($_POST)) {
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='{$_SESSION['user']}'");
echo ($query) ? "Updated" : "Not Updated";
exit;
} else {
?>
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate" name="name">
<label for="name">Value</label>
</div>
<button type="button" id="submit" class="btn-flat">Update</button>
</form>
<?php } ?>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name === '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {name: name}, function(data) {
alert(data);
$('form')[0].reset(); // To reset form fields
});
}
});
});
</script>

Issued loading PHP data to HTML file using JavaScript

I am writing a Shoutbox. The HTML file has 2 buttons: refresh - refreshes all the messages and submit - submits message and refreshes page messages.
Everything works perfectly but one issue. When I click submit, the page doesn't refresh with latest message. But everything works fine afterwards.
HMTL file:
<head>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script src="script.js"></script>
</head>
<body>
<div id="wrap">
<div id="input">
<form>
<input type="text" name="name" id="name" placeholder="Enter a name">
<input type="text" name="message" id="message" placeholder="Enter a message">
<input type="button" id="refresh" value="Refresh">
<input type="button" id="submit" value="Submit">
</form>
</div>
<div id="messages">
<ul id="messageList"></ul>
</div>
</div>
</body>
</html>
JavaScript File
$(document).ready(function() {
$('#refresh').on('click', function(){
$("#messageList").load( "messages.php");
event.preventDefault();
});
});
$(document).ready(function() {
$('#submit').on('click', function(){
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
$.post( "newmessage.php", dataString );
event.preventDefault();
$("#messageList").load( "messages.php");
event.preventDefault();
});
});
messages.php:
<?php
//error_reporting(0);
include 'database.php';
//Create Select Query
$query = "SELECT * FROM shoutbox ORDER BY time DESC";
$shouts = mysqli_query($con, $query);
while($row = $shouts->fetch_object()) {
$time = $row->time;
$name = $row->name;
$message = $row->message;
echo "<li>".$time." - <b>".$name.": </b>".$message."</li>";
}
$con->close();
?>
newmessage.php:
<?php
//error_reporting(0);
include 'database.php';
if(isset($_POST['name']) && isset($_POST['message']))
{
$name = '"'.$_POST['name'].'"';
$message = '"'.$_POST['message'].'"';
$datum = new DateTime();
$timeStamp = $datum->format('Y-m-d H:i:s');
$insert_row = $con->query("INSERT INTO shoutbox(name, message) VALUES($name, $message)");
}
if($insert_row) {
} else {
die('Error : ('. $con->errno .') '. $con->error);
}
$con->close();
?>
From this answer:
I'd recommend strongly that you take the time to understand the nature of asynchronous calls within JavaScript
Please follow the link, there's more info there.
To your code to work:
$(document).ready(function() {
$('#submit').on('click', function(event){ // << event was missing
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
event.preventDefault();
$.post("newmessage.php", dataString, function(){
// this function is a callback, called on AJAX success
$("#messageList").load( "messages.php");
});
});
});
This should do the job. Make sure if you are using event.preventDefault(), you pass the event variable to the function. This can also test if the message was posted successfully
$('#submit').on('click', function(event){
event.preventDefault();
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
var posting=$.post( "newmessage.php", dataString );
posting.done(function(data){
$("#messageList").load( "messages.php");
});
posting.fail(function(){
alert("Something is not right with your message. Please Try Again")
})
});

Edit existing jQuery function to add upload file

I have some working code but want to add upload image field but with no success.
My current code is:
Form:
<form id="add_product_form" enctype="multipart/form-data">
<input id="uploadFile" type="file" name="image" class="img" /><br />
<input id="status" type="checkbox" checked /><br />
<input id="product" type="text" /><br />
<label for="button" id="response"></label>
<input type="button" id="button" value="Добави" /><br />
</form>
jQuery:
<script type="text/javascript">
$('document').ready(function(){
$('#button').click(function(){
var image = $('input[type=file]').val().split('\\').pop();
function chkb(bool){ if(bool) return 1; return 0; } var status=chkb($("#status").is(':checked'));
if($('#product').val()==""){ alert("enter name"); return false; } else { var product = $('#product').val(); }
jQuery.post("products_add_process.php", {
image: image,
status: status,
product: product
},
function(data, textStatus) {
$('#response').html(data);
if(data == 1){
$('#response').html("OK");
$('#response').css('color','green');
document.getElementById("add_product_form").reset();
} else {
$('#response').html("Not OK");
$('#response').css('color','red');
}
});
});
});
</script>
products_add_process.php:
<?php
$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];
$status = $_POST['status'];
$product = $_POST['product'];
if($image_name == '') {
echo "<script>alert('Select image')</script>";
exit();
} else {
$random_digit=rand(0000000000,9999999999);
$image=$random_digit.$image_name;
move_uploaded_file($image_tmp_name,"uploads/$image");
$query=mysql_query("INSERT INTO products(product, image, status) VALUES ('$product', '$image', '$status')");
if(mysql_affected_rows()>0){
$response = 1;
echo "1";
} else {
$response = 2;
echo "2";
}
}
?>
I put alert 'Select image' and then understand that $image_name is empty and maybe somewhere have to put some code to say that I want to send DATA TYPE. I try to add to form enctype="multipart/form-data" but won't work.
Where and what have to add in existing code to make sending data, without making very big changes because this code have in a lot of files and will be difficult to edit big part of codes.
Maybe have to add that form and jQuery are in php file which is called in other mother file and structure is something like this:
products.php /call products_add.php/
products_add.php /where is the form and jQuery/
products_add_process.php /called from products_add.php to upload data/
p.s. Sorry if I don't explain my problem well but I'm from soon at stackoverflow and still learning how to post my questions :)

Categories

Resources