<!doctype html>
<html>
<head>
<title>jQuery Tagit Demo Page (HTML)</title>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
var availableTags = [];
$('#demo2').tagit({tagSource:availableTags});
$('#demo2GetTags').click(function () {
showTags($('#demo2').tagit('tags'))
});
/*
$('li[data-value]').each(function(){
alert($(this).data("value"));
});*/
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
function showTags(tags) {
console.log(tags);
var string = "";
for (var i in tags){
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
}
});
</script>
</head>
<body>
<div id="wrap">
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
<div class="box">
<div class="note">
You can manually specify tags in your markup by adding <em>list items</em> to the unordered list!
</div>
<ul id="demo2" data-name="demo2">
<li data-value="here">here</li>
<li data-value="are">are</li>
<li data-value="some...">some</li>
<!-- notice that this tag is setting a different value :) -->
<li data-value="initial">initial</li>
<li data-value="tags">tags</li>
</ul>
<div class="buttons">
<button id="demo2GetTags" value="Get Tags">Get Tags</button>
<button id="demo2ResetTags" value="Reset Tags">Reset Tags</button>
<button id="view-tags">View Tags on the console </button>
</div>
</div>
</div>
<script>
</script>
</body>
</html>
This code will just transfer the list of items in the dostuff.php but when I try to print_r it on PHP nothing won't come out. why is that?
I am doing an ajax request on this line
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
and the code in PHP
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
This is just a shot in the dark, given the limited information, but it would appear that you're expecting something to happen with the data sent back from the server.. but you literally do nothing with it. On success, you have it display an alert... and nothing else.
Try changing your success entry to the following:
success: function(data) {
$("#wrap").html(data);
}
This will fill the div with the data from the POST request. The reason it shows up as nothing as it is..., you aren't loading the currently executing page with the data needed for the print_r to actually echo anything.
Edit: How to insert values into database;
Database interaction now-a-days is done with either custom wrappers, or the php Data Object, also referred to as PDO, as opposed to the deprecated mysql_* functions.
First, you prepare your database object, similar to how a connection is done in the aforementioned deprecated functions:
$dbh = new PDO("mysql:host=hostname;dbname=database", $username, $password);
Then, you can begin interaction, preparing a query statement..
$stmt = $dbh->prepare("UPDATE table_name SET column1 = :column1 WHERE id = :id");
Binding a parameter in said statement..
$stmt->bindParam(':column1', $column1);
$stmt->bindParam(':id', $id);
$id = $_POST['id'];
And finally executing the query:
try {
$stmt->execute();
}
catch (Exception $e) {
echo $e;
}
PDO auto-escapes any strings bound in the prior statements, making it save from SQL-injection attacks, and it speeds up the process of multiple executions. Take the following example:
foreach ($_POST as $id) {
$stmt->execute();
}
Since the id parameter is already bound to $id, all you have to do is change $id and execute the query.
Where where you expecting the PHP result of print_r to "come out"?
Try changing your AJAX call to this (only the value of success is different):
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: function(data, textStatus, jqXHR){
alert(data);
}
});
With this, the output of your PHP template, which you would normally see if you posted to it the old fashioned way (ie. with a form and a full page reload), will display in an alert.
Hope that helps.
Try to add encodeURI for the jQuery part,
$.ajax({
url: "demo3.php",
type: "POST",
data: { items: encodeURIComponent (list.join("::")) },
success: function(response) {
console.log(response);
}
});
And urldecode for the PHP part:
$lis = $_POST['items'];
$liarray = explode("::", urldecode($lis));
print_r($liarray);
3 things:
Set your AJAX's success to show the echos/prints given in your PHP script
success: function(result)
{
$("#somecontainer").html(result);
}
That way ANYTHING that gets printed in a PHP script otherwise, will be put in i.e.
<div id="somecontainer">
Result of PHPcode here
</div>
Second, instead of
var string = "";
for (var i in tags)
{
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
use push(). This adds the value at the next unoccupied index in the array:
var string = "";
for (var i in tags)
{
list.push(tags[i].value);
}
That way you don't have to pop the last element off.
Third point: put your PHP code in a separate file (and your JavaScript/jQuery as well). Have like:
/root/index.html
/root/script/dostuff.php
/root/script/myscript.js
then let your AJAX call to url: "/script/dostuff.php"
Related
I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.
I have a PHP script which Edit and Delete cars on my website. Now I want to make Edit and Delete buttons inside a dropdown, and I did but its adding dropdown just to the first car from the row, since the ID is the same for every dropdown. Now I know how to get the unique ID from every car from PHP but how can I achieve it in JavaScript. I will show you my code.
PHP:
$id = $row["id"];
<div class='dropdown'>
<button onclick='myFunction()' class='dropbtn'>Settings</button>
<div id='myDropdown".$id."'class='dropdown-content'>
".($featured!=1 ? "<a title='Make ".$title." Featured'href='forms/addfeatured.php?id=".$id."'>Make Featured</a>" : "<a title='Remove ".$title."' href='forms/removefeatured.php?id=".$id."'>Remove Featured</a>")."
<a title='Delete ".$title."' href='forms/deletecars.php?id=".$id."'>Delete</a>
</div>
JavaScript:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
So how can I have different ID in javascript so I can open dropdowns for each entry?
Only use , No need to technically learn AJAX or JSON !
You Just need to use the simple functions which has been prepared for use and has been put in the libraries. And set a few parameters that they need.
The important thing is that, You should know PHP runs on the server machine, not your browser or your PC.
So the PHP variables too.. They are not in your machine to easily put them in a JS variable.
At his point we need to communicate with the server to send them(using AJAX function) in a proper format(using JSON function) for us to use.
So, Your question :
How to add ID from PHP script to JavaScript code?
has the easiest solution just with these functions:
(At your browser page):
$.ajax({ .. some parameters .. });
$(document).ready(function() {
$.ajax({
type: 'post', //Transfer Protocol
url: 'serving.php', //Address of Server Page
dataType: 'json', //Data Structure
data: {action: 'demo'},
success: function(output) {
$variables = output;
}
});
});
and
(At your PHP page on the server)
json_encode(.. some data ..);
$variables = array("Chevy", "BMW", "Ford");
echo json_encode($variables ); // Encoded variable array
Unfortunately your codes and description are not clear for me to help directly in your project.
But I attach a simple practical Example :(in Jquery)
// carSelection.html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs
/jquery/2.1.1/jquery.min.js"> //jquery CDN
</script>
</head>
<body>
<div style="margin:2em">
<form id="myForm">
<select id="selectNumber">
<option>Choose a car</option>
</select>
</form>
</div>
<script>
var $cars = '';
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'carServs.php',
dataType: 'json',
data: {action: 'demo'},
success: function(output) {
$cars = output;
var option = '';
for (var i=0;i<$cars.length;i++){
option += '<option value="'+ $cars[i] +
'">' +
$cars[i] + '</option>';
}
$('#selectNumber').append(option);
}
});
});
</script>
</body>
</html>
And
// carServs.php page
<?php
// ...
$cars = array("Chevy", "BMW", "Ford");
echo json_encode($cars);
//...
?>
just remeber to attach the jquery CDN at your code, In the head section or just before ending the body tag </body>
And if you insist to have it in JavaScript, It's possible just with a few changes in syntax.
I have a drpcategory dropdown in a form. I will just paste the dropdown code below;
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
Then I AJAX post every time I make a selection in the above drpcategory dropdown as below;
<script>
$(function(){
$('#drpcategory').on('change',function()
{
$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
});
});
</script>
This seems to be currently working as I'm getting outputs like below in Chrome Browser > Inspect > Network tab every time I make a selection in drpcategory. Here is the screenshot;
The question is how can I capture this AJAX post data using PHP within the same page and echo it within the same page? So far I have tried;
<?php
if(isset($_POST['drpcategory']))
{
echo 'POST Received';
}
?>
I'm looking for a solution using only PHP, JQuery and AJAX combined.
This question was later updated and answered here:
AJAX POST & PHP POST In Same Page
First of all, this line -> type: $(this).attr('post') should be type: $(this).attr('method'),. So this will give the value ** type:post** and
As far as i understand, you are asking to send ajax whenever you select options from drpcategory. Why are you submitting the entire form for this. If i where you, i should have done this problem by following way
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
On you php side, you can get your data like,
echo $_POST['drpcategory'];
I recommend you read the documentation for the ajax function, I tried to replicate it and I had to fix this:
$.ajax({
// If you don't set the url
// the request will be a GET to the same page
url: 'YOU_URL',
method: 'POST', // I replaced type by method
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
http://api.jquery.com/jquery.ajax/
OUTPUT:
First change to $value
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category2 = file($category, FILE_IGNORE_NEW_LINES);
foreach($category2 as $value)
{
echo "<option value='".$value."'>".$value."</option>";
}
?>
</select>
then add url
<script>
$(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:'folder/filename.php',
type: 'post',
data: '{ID:" . $Row[0] . "}',
success: function(result) {
console.log(result);
}
});
});
$('#drpcategory').on('change',function()
{
$("#form").submit();
});
});
try request
if(isset($_REQUEST['ID']))
The result will/should send back to the same page
Please try this code:
$.post('URL', $("#FORM_ID").serialize(), function (data)
{
alert('df);
}
I think you have an eroror syntax mistake in ajax jQuery resquest because ajax post 'http://example.com/?page=post&drpcategory=Vehicles' does not return this type url in browser Network Tab.
<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.
Here ajax request example
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
`
It sounds like you're trying to troubleshoot several things at once. Before I can get to the immediate question, we need to set up some ground work so that you understand what needs to happen.
First, the confusion about the URL:
You are routing everything through index.php. Therefore, index.php needs to follow a structure something like this:
<?php
// cleanse any incoming post and get variables
// if all your POST requests are being routed to this page, you will need to have a hidden variable
// that identifies which page is submitting the post.
// For this example, assume a variable called calling_page.
// As per your naming, I'll assume it to be 'post'.
// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
// set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
header('Content-Type: application/json');
print json_encode(array('message' => 'Your submission was received'));
// if this is from an ajax call, simply die.
// If from a regular form submission, do a redirect to /index.php?page=some_page
die;
}
// if you got here, there was no POST submission. show the view, however you're routing it from the GET variable.
?>
<html>
(snip)
<body>
<form id="form1" method="post">
<input type="hidden" name="calling_page" value="page" />
... rest of form ...
<button id="submit-button">Submit</button>
</form>
}
Now, confusion about JQuery and AJAX:
According to https://api.jquery.com/jquery.post/ you must provide an URL.
All properties except for url are optional
Your JQuery AJAX will send a post request to your index.php page. When your page executes as shown above, it will simply print {message: "Your submission was received"} and then die. The JQuery will be waiting for that response and then do whatever you tell it to do with it (in this example, print it to the console).
Update after discussion
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<!-- HTML to receive AJAX values -->
<div>
<label>Item</label>
<select class="" id="drpitem" name="drpitem"></select>
</div>
<script>
$(function(){
$('#drpcategory').on('change',function() {
$.ajax({
url: '/receive.php',
method: 'post',
data: $(this).serialize(),
success: function(result) {
workWithResponse(result);
}
});
});
});
function workWithResponse(result) {
// jquery automatically converts the json into an object.
// iterate through results and append to the target element
$("#drpitem option").remove();
$.each(result, function(key, value) {
$('#drpitem')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
</script>
receive.php:
<?php
// there can be no output before this tag.
if(isset($_POST['drpcategory']))
{
// get your items from drpcategory. I will assume:
$items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');
// send this as json. you could send it as html, but this is more flexible.
header('Content-Type: application/json');
// convert array to json
$out = json_encode($items);
// simply print the output and die.
die($out);
}
Once you have everything working, you can take the code from receive.php, stick it in the top of index.php, and repoint the ajax call to index.php. Be sure that there is no output possible before this code snippet.
I'm getting text value from an onclick event. I have saved the data in (var id) in using jQuery. In the variable data will check the database and if it is matching it will display all the records.
My html code:
<div class="col-lg-3 col-md-6 test" data-idtest="Diabetes">
<a href="" class="box_cat_home">
<i class="icon-info-4"></i>
<img src="assets/img/icon_cat_3.svg" width="60" height="60" alt="">
<h3>Diabetes</h3>
<ul class="clearfix">
<li><strong>124</strong>Doctors</li>
<!-- <li><strong>60</strong>Clinics</li> -->
</ul>
</a>
</div>
My jquery code:
<script type="text/javascript">
$(document).ready(function() {
$('.test').click(function (){
var id = $(this).data('idtest') ;
//alert(id);
$.ajax({
url : "getting.php",
type: 'POST',
data : {id:id },
}).done(function(response) {
});
})
});
</script>
How can I achieve this?
Here my php code:
<?php
echo "ejejejej";
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'mysql';
$dbName = 'fre';
$id =$id;
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$men ="select * from tbl_users where doctor_speciality = $id";
$men_result=$db->query($men);
$projects=array();
while($row=mysqli_fetch_assoc($men_result)){
$projects[] = $row;
}
?>
please how can i achive this?
You should use $.ajax in jquery library
check Ajax for reference.
Basic example:
$.ajax({
url : "your_server_url",
type: 'POST',
data : {id:id },
}).done(function(response) {
//when request is success , done function is call so you should write anything or leave it empty
});
replace your_server_url with your server url that call php script which contain mysql query for save id
You need to use ajax.
You send the ID to a controller (in case you are using laravel or any other MVC frameworks)
or just post it to a PHP file. You select all the needed values from using php and return it as a JSON. ex:
And then you loop through it in jQuery and display it as needed.
$.post( "/php/getRecordsById.php", { id: yourSelectedId }, function( data ) {
//Do Something with recieved data here
}, "JSON");
Returning JSON data from php:
echo json_encode($yourSelectedData);
I have a problem concerning my code which should change content in a div onclick "More News articles" as the change will happen only once. I see in Chrome Developer mode that it fires every click a request. What goes wrong?
Output.php
<?php
require_once('../pe13f/SSI.php');
require_once ('../PE13/smf_2_api.php');
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function MakeRequest(id)
{
$.ajax({
url : 'display.php',
data:{"id":id},
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
}
});
}
</script>
<div id="stream" class="bg4 roundedcrop shadow">
<div class="ph25 pv20">
<h1>News</h1>
<input id="streamcnt" name="streamcnt" type="hidden" value="" />
</div>
<div id="streamadd"></div>
<div id="streaminnern">
<?php
$num_recent = 5;
echo $num_recent;
?>
</div>
<div onclick="MakeRequest(<?php echo $num_recent; ?>);" id="streammore">More News articles</div>
</div>
backend php display.php
<?php
$num_recent = $_GET['id']+5;
echo $num_recent;
?>
Greetings Emil
Check the source that is produced by output.php. You'll find there onclick="MakeRequest(5);". Basically - on every click you call MakeRequest(5) which always fires call display.php?id=5 (you probably see that in your dev console).
Try something like this:
<script>
var lastId = 0; // var that stores last fetched ID
function MakeRequest(id)
{
if(!lastId) // if there is no last ID use the one from initial onclick
lastId = id;
$.ajax({
url : 'display.php',
data:{"id":lastId}, // note that we are using the lastId var
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
lastId = data; // save fetched ID in our global var
}
});
}
</script>
The request is always the same. Suppose $num_recent is initially set to 5.
Then as per your code MakeRequest(5) will be executed. And your ajax call updates a div with class streaminnern. So the new id has no impact on the next ajax call. For the ajax request to be sent updated value you may set
$.ajax({
url : 'display.php',
data:{"id":$('#streaminnern').html()},
.................
});