linking php to jquery - php

I am trying to build my first jquery web application, but I've hit a roadblock and can't seem to figure this out.
I have a PHP page and an HTML page.
The HTML page has a form with a triple drop down list.
The PHP page connects to the database but I am not sure how to pass the query result from the php page to populate the drop down list on the html/javascript page.
Here is my code thus far.
HTML:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#selector").submit(function() {
$.ajax({
type: "GET",
url: "DBConnect.php",
success: function(msg){
alert(msg);
}
});
var select_car_make = $('#select_car_make').attr('value');
var select_car_model = $('#select_car_model').attr('value');
var select_car_year = $('#select_car_year').attr('value');
alert("submitted");
}); //end submit
});
</script>
<h1 style="alignment-adjust:center">Car information:</h1>
<hr />
<div id="results">
<form action="get.php" id="selector" method="get" name="sizer">
<table width="451" height="70" border="0">
<th width="145" height="66" scope="row"><label for="select_car_make"></label>
<div align="center">
<select name="select_car_make" id="select_car_make" onchange="">
</select>
</div></th>
<td width="144"><label for="select_car_model"></label>
<div align="center">
<select name="select_car_model" id="select_car_model">
</select>
</div></td>
<td width="140"><label for="select_car_year"></label>
<div align="center">
<select name="select_car_year" id="select_car_year">
</select>
</div></td>
</tr>
</table>
<input name="completed" type="submit" value="submit" />
</form>
Here is the PHP Page:
<?php
$DBConnect = mysqli_connect("localhost", "root", "password", "testing")
or die("<p>Unable to select the database.</p>" . "<p> Error code " . mysqli_errno($DBConnect) . ": " . mysqli_error($DBConnect)) . "<p>";
echo "<p>Successfully opened the database.</p>";
$SQLString1 = " SELECT car_make FROM cars";
$QueryResult = mysqli_query($DBConnect, $SQLString1)

Hey Justin if this is your first time dipping your toes, I would keep it ultra-simple. Put the select box inside something with an ID, such as a span or div. Then get your AJAX response to just rewrite the contents, this is an easy and clear way to start with AJAX, for example:
$.ajax({
type: "POST",
url: "/call.php",
data: "var=" + myData,
success: function(response){
$("#someId").html(response);
}
});
On your remote page just echo the whole select box:
echo "<select name='cars'>";
echo "<option value='".$value."'>".$name."</option>";
etc...
Again this isn't the best way, but its certainly not the worst.

You should be able to JSON encode your result from PHP into a variable which Javascript or the Jquery can read. I did it like this with an image string I received from PHP reading a directory of images:
var imageFiles = '<?=$images_js?>';
imageFiles = $.parseJSON(imageFiles);
var images = [];
for(i = 0; i<imageFiles.length; i++){
var image = document.createElement('img');
image.src = imageFiles[i];
images.push(image);
}
var count = imageFiles.length;
var i = 0;
the is the variable which came from my php result. The $.parseJSON(imageFiles); does the interpretation for the variable.
I hope this helps, or puts you along the right path.

If you want the car make selection page to be populated by your database, you should give it a .php extension as well. I think you should reconsider if AJAX is the best option.
But I would put the database connection code inside a "conn.php" file to be included on your selection page then populate it with PHP.

Related

Php echo button onclick get id

I hava a dynamic list, loading from database in my php page.This list also have a delete button. When i click this button i need to get id of this button and delete from database that line with php code.
$dbh = new PDO("sqlite:database.sdb");
$sql ="SELECT * FROM clip";
foreach ($dbh->query($sql) as $row)
{
print 'Id: '. $row['id'] .'<br />';
echo '<input type="submit" id="'.$row['id'].'" value="delete" name="del">';
}
also this is my final code for button click;
$dbh->exec("delete clip where id='in here should be button id'");
How can i connect with this two code. Thanks already.
Given the level of your question I am assuming you are unfamiliar with jQuery and AJAX, but you should research both.
For a simple solution not using these you could do as follows:
Change the output to be <input type="button" id="'.$row['id'].'" value="Delete" onclick="do_delete(this.id)">;
Then you need a php script on the server side to handle the delete function, e.g. yourhandler.php
<?
//connect to DB here
if ($_POST['id']) {
$sql = "delete from clip where id=:delete_id";
$stmt = $dbh->prepare($sql);
$stmt->execute([':delete_id'=>$_POST['id']]);
}
?>
Then on the client side you need a form which submits when the button is clicked. Here is an example form code:
<form action="yourhandler.php" method="post" id="myform">
<!--Your PHP script which creates buttons-->
<input type="hidden" value="" name="id" id="delete_id">
</form>
<script>
function do_delete(which) {
var x = document.getElementById('delete_id');
x.value=which;
document.getElementById('myform').submit();
}
</script>
You can use this working jquery template for your task. It binds to all inputs that has a name="del".
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('input[name="del"]').on('click', function() {
alert('button id is '+$(this).attr('id'));
var button_id = $(this).attr('id');
$.ajax({
method: 'post',
url: "delete.php",
data: {'did':button_id},
dataType: "html",
success: function(result) {
alert(result);
}
});
});
});
</script>
In your PHP delete file, you can retrieve the delete id via $_POST['did'].

I don't know how to get id of records while deleting record using jquery

<script type="text/javascript" src="../js/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$("#submit").click(function (){
var name =$("#name").val();
var mobile =$("#mobile").val();
var email =$("#email").val();
$.get('new.php',{name : name, mobile: mobile, email: email},function (data){
$("#res").html(data);
});
$("#name").val("");
$("#mobile").val("");
$("#email").val("");
$("#res").hide(10000);
});//submit.click end here!!!!!!!
$("#view").click(function(){
var view='view';
$.post('new.php',{view: view},function(data){
$("#viewdata").html(data);
});
$("#viewdata").toggle("slow");
});//to display data in table!!!!!!!
$("#add").click(function(){
$("#addnew").toggle("slow");
});//toggel button for record table!!!!!
$("body").on('click','',function(){
var iddata =this.id.split('-');
var id = iddata[1];
alert(id);
});
</script>
if(isset($_POST['view']))
{
$query="select * from userdetail";
$res=mysql_query($query);
echo "<table border=1>
<tr><th>name</th><th>Mobile</th><th>Email</th><th>Delete</th><th>Update</th></tr>";
while($row=mysql_fetch_array($res))
{
echo "<tr><td>".$row[1]."</td><td>".$row[3]."</td><td>".$row[4]."</td>";
echo "<td><div class='del' id='id-".$row[0]."';>Delete</div></td>";
echo "<td><a href='#'>Update</a></td>";
}
echo"</table>";
}
<body>
<div id="addnew" style="width:500px; float:left;">
<div style="width:200px; float:left;">
<form name="frm" id="frm">
<input type="text" id="name"></br>
<input type="text" id="mobile"></br>
<input type="text" id="email"></br>
<input type="button" id="submit" value="submit"/></br>
</form>
</div>
<div id="res" style="width:300px; float:left;">
</div>
</div>
<button id="add">Add New</button>
<button id="view">View</button>
<div id="viewdata">
<table border=1>
<tr>
<th>name</th><th>Mobile</th><th>Email</th><th>Delete</th><th>Update</th>
</tr>
</div>
</body>
I'm new in jquery and trying to learn crud function with jquery and php. I'm working on a code where I can add data through jquery as well as I can retrieve it from database, now I have placed a delete field to delete record from that table but I'm stuck here because I don't know how to get id from that table so I can use it to delete that record from table. I have tried .on and delegate in jquery to get that id but still not getting the result what I want, so please help me to solve this error.
So your html output is going to be something like this for your delete cell
<td>
<div class='del' id='id-1'>Delete</div>
</td>
Within JQuery you can do this:
$('.del').on('click',function() {alert(this.id)});
Result: id-1
Check it out here http://jsfiddle.net/54nptrkd/
By placing id inside while loop, I can fetch it using bellow code
in html page.
I can use
$<'#viewdata'>.on('click','.del',function(){
alert(this.id);
})
It will popup the result like id-31 or id-1 (whatever is selected).
Now you can use that id to delete the record.
.del is a class where id is stored in php file
e.g
< class='del' id=$row['id']>delete
"ok i'm trying and can you refer me some stuff or link to learn delete and update using jquery and php"
Your SQL statement will be something along the lines of
Delete from *TABLE* where id = ?
You most likely will have a Delete.php file that you can run your sql queries the same as you did in your New.php. Delete.php will either listen to a $_POST or $_GET variable
Your JQuery will have an ajax call like this if you are using $_POST in your php
$.ajax('Delete.php?id='+id,{
success: function() {
alert('it worked!')
}
});
or like this if you are using $_GET in your php
$.ajax('Delete.php', {
id: id,
success: function() {
alert('it worked!')
}
});
id will be defined in your JS like I mentioned before
$('.del').on('click',function() {
alert(this.id)
var id = this.id;
//$.ajax call goes here
});

Autosave from php to mysql without page change or submit button

Basically I have a list of data that is shown via a foreach statement from a table in my database. I want a dropdown list next to each that has some values in them that need to be saved to a field in my table, however I want to autosave the value in the dropdown list to the field as soon as the value in it is changed. Can anyone point me to a tutorial or something that might help?
I am using php and mysql to create the system, but will happily use JavaScript if required
I have had a look at this: dynamic Drive Autosavehttp://www.dynamicdrive.com/dynamicindex16/autosaveform.htm which is similar to what i want, however i need it to actually store that data in my database not temporary storage.
Any Guidance appreciated,
Ian
BIG EDIT
So, thankyou for the replys but I have no clue about ajax call.....I found this:How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?.
can i get it to work?
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id</td>
<td>
<select name="status" id="status">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
and on the page saveStatus.php:
<?php
if (isset($_POST['statusType'])) {
$con=mysql_connect("localhost","username","mypass","rocketdb3");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jobs", $con);
$st=$_POST['statusType'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
$resource = mysql_query($query)
or die (mysql_error());
}
?>
Where is the $id in saveStatus.php ?
You need to pass the statusType and job_id via AJAX to update correctly in the saveStatus.php.
For example:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).id;
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal, job_id: job_id },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id; ?></td>
<td>
<select name="status" id="<?php echo $job->job_id; ?>">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
*Note: .live() is deprecated, use .on() instead.
And saveStatus.php
$st = (int)$_POST['statusType'];
$id = (int)$_POST['job_id'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
You will need to use JavaScript (+ jQuery for easier working) to achieve this.
Catch the 'change' of the value using JavaScript and fire an AJAX call to a PHP script that saves the value to the MySQL db.
Use jQuery! On the drop-down onchange event do a ajax call and update the record in DB. Here is a link to jQuery Ajax method.

Post result from a query via php in same page with Ajax

I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.

Ajax to read from form

I'm writing a store system for my game,
it worked quite well until I found out that it only takes the amount of first entered Item.
function pbuy(buyitem) {
var amountc = "amount-"+buyitem,
var amount = $("#"+amountc+"").val();
$.ajax({
type: "POST",
url: "store2.php",
data: "buyitem="+ buyitem+"&amount="+amount,
success: function(resp){
document.getElementById('ajaxDiv').innerHTML = resp;
},
error: function(e){
alert('Error: ' + e);
}
});
}
I'm trying to give it it the Id of the form like so:
function pbuy(buyitem) { var amountc = "amount-"+buyitem, var amount = $("#"+amountc+"").val();
But nothing happens.
The code the creation of the forms is:
<tr>
<td class='items' width='80%' align='center' valign='top'>
<?PHP echo $itemstore->itemname;?>
</td>
<td width="20%">
Price:<?PHP echo $itemstore->newprice;?>
<form method="post">
<input type='text' id='amount-<?PHP echo $row;?>)' />
<input name="itembid" type="button" onclick="pbuy(<?PHP echo $row;?>)" value="Buy" />
</form>
</td>
</tr>
If I hardcode the amount in the ajax function it all runs fine like it should.
You're getting a javascript error before the AJAX-request is being sent since you are defining your amountc and amount variables separated by a comma. Either do
var amountc = "amount-"+buyitem;
var amount = $("#"+amountc+"").val();
semicolon separated, or keep the comma and skip the second var
var amountc = "amount-"+buyitem,
amount = $("#"+amountc+"").val();
Did you checked the response of the AJAX request?

Categories