I am having some trouble with my jquery. I am not sure if it is connecting to doc.php but I am not getting anything inserted into my database.
I have an insert command in doc.php which I know is working.
I'm trying to create a way to update prices in a database, from doc.php, that searches out items one at a time.
The doc.php is searching by var, then updating in the same page.
The foreach loop function then, takes the var one by one, sends them to the doc.php page that then searches by var and updates into the database.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die (mysql_error());
$sql = "SELECT var FROM table";
$query = mysql_query($sql) or die (mysql_error());
while ($result = mysql_fetch_array($query)) {
$variable = array($result['var']);
foreach ($variable as $variable1) {
?>
<script src="jquery-1.7.2.min.js" type="text/javascript">
$(function() {
var valueToSend = '<?php echo $variable1; ?>';
$.ajax({
url: "doc.php",
dataType: "json",
type: "POST",
data: { Variable: valueToSend },
success: function (m) {
alert(m);
},
error: function (e) {
alert("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
}
}
?>
First of all, what do you want to do with this code? If you want to read & write to db using php, ajax call is unnecessary. If you want to practice ajax & php you need to read some howto because your code is somewhere strange ;). This is nice collection of tutorials for jQuery and some for PHP read some and practice.
Related
This question already has answers here:
Form submit with AJAX passing form data to PHP without page refresh [duplicate]
(10 answers)
Closed 7 years ago.
I'm working with a mysql database and a webpage that i'm trying to make comunicate with it.
Here's my situation:
i have the listmat.php file that echoes all the records in the table Material and it works.
Now i manage to show the output of the listmat.php file inside a specific div witouth refreshing the hole page with the following code:
<script>
$(document).ready(function(){
$("#matbutton").click(function(){
$("#matins").load('listmat.php');
});
});
</script>
Where matbutton is the id of the submit button in the form and matins is the id of the div where i show the output of listmat.php
Here's my form:
<form id="formmatins" method="post" action="listmat.php">
<p>Name:<input type="text" Name="Mat" id="Material"></p>
<center><input type="submit" value="Insert/Remove" id="matbutton"></center>`
</form>
What i'd like to do is to use the matbutton to also insert the value of the textbox in the table that listmat.php echoes all his records. So that everytime i click a record is inserted and in the div is shown the new table
The problem is that if i insert the button in the form with the method post , by clicking it redirects to the output changing page but if i put it out the echoes work but i cannot pass obviously the value of the textbox to the listmat.php file to be the argument of the insert because the button is not interested by the method post.
I looked around and looks like the solution is using some articulated structure in jquery/ajax but i really don't know how to fix. Any help would be really appreciated
UPDATE
<script>
$(function () {
$('#formmatins').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function () {
$("#matins").load('listmat.php');
alert('form was submitted');
}
});
});
});
</script>
And again it switch page
UPDATE
<?php
$user = "**";
$pass = "**";
$db = "**";
$host = "localhost";
$con = mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$m = $_POST['Mat']; //the text box in the form
$ins = $con->query("INSERT INTO mattemp (Material) VALUES ('$m')");
$query = $con->query("SELECT Material FROM mattemp");
while ($row = $query->fetch_assoc()) {
echo $row['Material']."<br>";
}
?>
It print the table updated everytime but still in a new page...what am i doing wrong?
SOLVED BY MYSELF
Thanks to all have tried to help me. The solution that gave me -1 on the post was not correct and here the solution of my code , in case someone would encounter the same problem
`<script>
$(function () {
$('#matbutton').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function (data) {
$("#matins").load('listmat.php');}
});
});
});
</script>`
You'll need $.ajax
For exemple :
$.ajax({
url: "your_url.php",
type: "POST",
data: $('#formmatins').serialize(),
success: function(response){
// Do something, or not...
}
})
This ajax code gets called, I tested it, but the database does not get updated.
I think the code is small enough not to need any further explanation. When something from the class pdb gets clicked, it saves its source to the database.
$(function(){
$('.pdb').on('click',function(){
var sou = $(this).attr('src');
var iddo = $(this).attr('id');
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
$.ajax({
data: data,
type: "post",
url: "database.php",
success: function(data){
alert("Prova: " + data);
}
});
});
});
database.php
<?php
mysql_connect("localhost","pierostesting","");
mysql_select_db("my_pierostesting");
$id=$_POST['id'];
$value =$_POST['value'];
$turno=$_POST['turno'];
if(true){
$sql="UPDATE board SET $id=$value, turno=$turno WHERE partita=0";
$result=mysql_query($sql);
if($result){
echo "Nailed it";
}
}else{
}
?>
remove
var data = 'id='+iddo+'&value='+sou+'&turno='+bia;
and debug ajax calls use either console or firebug extension
replace:
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
with
data = { 'id':iddo,'value':sou,'turno':(bia)?true:false}
Needed to change the PHPto this:
$sql="UPDATE board SET $id='$value', turno=$turno WHERE partita=0";
Simply change $value with '$value', bloody ''. Thank you all guys.
I'm building a webshop for a project at university. I have a search bar in header, navigation bar on the left. In both cases I send data with Ajax (from search bar a keyword, from navs a category and subcategory). Ajax response is a PHP script that prints products based on category and subcategory or keyword. At the end of it it prints pagination links and select element for number of products per page. If I submit a keyword or click on a nav, it prints out results fine, but if I then change the page or a number on select element (another Ajax request) , the results default because category/subcategory or keyword are not being sent anymore. This is the code for search bar request:
$("#searchButton").click(function(){
$("#searchBar").blur();
var keyword=$("#searchBar").val();
$.ajax({
type:"GET",
url:"print.php",
data: { keyword:keyword }
}).done(function (data){
$('#content').html(data);
return false;
});
});
and this is the code for pagination:
$(document).on("change", "#paginationSelect", function(){
var productsPerPage=$("#paginationSelect").val();
$.ajax({
type:"GET",
url:"print.php",
data: { productsPerPage:productsPerPage }
}).done(function (data){
$('#content').html(data);
return false;
});
});
I'm wondering what's the best way to save the data sent by last Ajax request so that I can send it again while changing pagination stuff. Should I change the PHP file or Ajax requests and what's the best way to do it?
Edit:
This is the PHP file:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
mysql_connect("localhost", "root", "") or die("Couldn't connect to database.");
mysql_select_db("webshop") or die("Couldn't select a database.");
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
if(isset($_GET["category"]) & isset($_GET["subcategory"])){
$category=$_GET["category"];
$subcategory=$_GET["subcategory"];
$query="SELECT * from proizvod where kategorija='".$category."' and podkategorija='".$subcategory."'";
}
else if(isset($_GET["keyword"])){
$keyword=$_GET["keyword"];
$query="SELECT * from proizvod where ime like '%".$keyword."%'";
}
else{
$query="SELECT * from proizvod";
}
$result=mysql_query($query);
$numProducts=mysql_num_rows($result);
if(isset($_GET["productsPerPage"]))$productsPerPage=$_GET["productsPerPage"];
else if($numProducts>=10) $productsPerPage=10;
else $productsPerPage=$numProducts;
if(isset($_GET["pageNum"]))$pageNum=$_GET["pageNum"];
else $pageNum=1;
if(isset($keyword)) print "<div id=\"keywordMessage\" class=\"col-lg-12\">Traženi pojam: ".$keyword."</div>";
if(mysql_num_rows($result)==0) print "<div class=\"col-lg-12\">Nema rezultata</div>";
for($i=0;$i<($pageNum-1)*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
}
for($i=($pageNum-1)*$productsPerPage;$i<$pageNum*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
print("<div class=\"col-lg-6\">
<table class=\"article\">
<tr><td colspan=\"2\"><img src=\"images/".$row["id"].".jpg\" class=\"imgArticle\"/></td></tr>
<tr><td colspan=\"2\"><b>".$row['ime']."</b></td></tr>
<tr><td>Kategorija: </td><td>".$row['kategorija']."</td></tr>
<tr><td>Opis: </td><td>".$row['opis']."</td></tr>
<tr><td>Cijena: </td><td>".$row['cijena']." kn</td></tr>
</table>
</div>");
}
print("<div class=\"col-lg-12\" id=\"paginationControl\">
<span class=\"col-lg-4\">
Prikazano: ".(($pageNum-1)*$productsPerPage+1)."-".$pageNum*$productsPerPage."/".$numProducts."
</span>
<span class=\"col-lg-4\" id=\"pageNumbers\">");
if($productsPerPage!=0){
for($i=1;$i<=ceil($numProducts/$productsPerPage);$i++){
if($i==$pageNum) print($i."   ");
else print("<a class=\"pageNumControl\" href=\"#\">".$i."</a>");
}
}
print("</span>
<span class=\"col-lg-4\">Proizvoda po stranici:
<select id=\"paginationSelect\">
<option value=\"10\" "); if($productsPerPage==10){ print("selected");} print(">10</option>
<option value=\"20\" "); if($productsPerPage==20){ print("selected");} print(">20</option>
<option value=\"30\" "); if($productsPerPage==30){ print("selected");} print(">30</option>
<option value=\"50\" "); if($productsPerPage==50){ print("selected");} print(">50</option>
</select>
</span>
</div>");
mysql_free_result($result);
?>
You could use jQuery .Data(). But please note, if you refresh the entire page, the .data() information is lost.
So, without have more code this is the best example I could come up with. I am storing the search information in the #searchBar's data, then retrieving it on pagination change.
$("#searchButton").click(function() {
var $sb = $("#searchBar"),
keyword = $sb.val();
$sb.data({
prevKeyword: keyword
}).blur();
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: keyword
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});
$(document).on("change", "#paginationSelect", function() {
var productsPerPage = $("#paginationSelect").val(),
previousKeyword = $("#searchBar").data('prevKeyword');
// Do something with the keyword
console.log(previousKeyword);
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: previousKeyword,
productsPerPage: productsPerPage
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});
I am trying to update a value in a database without refreshing the page using AJAX. I am completely new to AJAX but I have have managed to create a function after searching for answers on Stackoverflow but I am unable to make it work.
One the main page...
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "del_reason.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
The button (which is in a form)
<input type="button" name="delete_pos" value="Delete" class="delRow_pos"
onClick="UpdateRecord(<? echo $row['reasonID']; ?>);"/>
The contents of del_reason.php
$var = #$_POST['id'] ;
$sql = "UPDATE gradeReason SET current = 0 WHERE reasonID = $var";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
//added for testing
echo 'var = '.$var;
The database connection is ok because other functions on the same page connecting to the database work fine and so do other jquery functions but when the button is clicked the alert says the record is upodated but it isn't
The MySQL query on the del_reason.php failed because it needed it's own MySQLi connection to the database.
As soon as I added it the script worked
Having trouble deleting a record from mysql databse using ajax/jquery. Issue I am having is that it does not delete from the database but does delete from the list. What am I doing wrong here?
Here is my code:
jQuery(document).ready(function(){
$(".deleteitem").click(function(){
var parent = $(this).closest('li');
var id = parent.attr('id');
$.ajax({
type: "POST",
data: "id=" +id,
URL: "delete.php",
success: function(msg){
$('#'+id).remove();
}
});
});
});
My php file delete.php:
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$id = $_POST['id'];
if (isset($id)) {
$query = "DELETE FROM img_slider WHERE id = '$id'";
mysqli_query($query) or die('Error, insert query failed');
}
The HTML markup:
<li id='".$row['id']."'>
<a href='#' class='deleteitem'><img src='../img/delete.png'></a>
</li>
Firstly test to make sure calling the delete file with a valid id works. The javascript below should work fine.
<script type="text/javascript">
<!--
$(function() {
$('.deleteitem').click(function(e) {
e.preventDefault();
var id = $(this).parent('li').attr('id');
$.get('delete.php',{ id: id}).done(function(data) {
if(data=='Error, insert query failed') {
// dont delete from list
alert('Failed to delete '+id);
} else {
//delete from list
$('#'+id).remove();
alert('Deleted '+id);
}
});
});
});
//-->
</script>
EDIT: updated the script to assist parent-id handling.
Are you able to say where the error is coming from? Most modern browsers should offer you some insight into what line, or what section the error is occurring on.
The script above should replace all your javascript.