Ajax and PHP not updating database - php

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.

Related

call value of a variable from php page by ajax

I am new to javascript and I've searched this question everywhere but no suitable answer.
I have a "code.php" page as
$query = "SELECT * FROM users WHERE id=1";
$result= mysqli_query($con,$query);
$row=mysqli_fetch_array($result);
echo $row[1];
On the other side in "index.php" i have
<h1>"the value for number is: " <span id="myText"></span></h1>
function myFunction() {
document.getElementById("myText").innerHTML = $row[1];
}
I want to load the value of $row[1] from code.php to index.php.
I know that i have to use ajax but how?
In index php use ajax to get data from code php.
this is example :
<script>
$.ajax({
url: 'code.php',
type:'get',
success:function(data){
$("#myText").html(data);
}
});
</script>
<script>
$(document).ready(function(){
$.ajax({
type:'get',
url:'code.php',
success:function(response){
// ajax will assign the result of code =,php into response
document.getElementById("myText").innerHTML = response; //response;
}
});
});
</script>
Place this at header of your index.php
You can find more tutorials on line to get more understanding of ajax
dont forget to download jquery and embed it your code
https://jquery.com/download/
Or u can copy this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

how to use two $.post methods very well for give data from 2 different database

function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
});
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
/*when i use alert method, this function works very well, why?*/
alert('SomeString');
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
};
in Data1.php
/*give data from database1 and print to HTML File*/
if ($_POST['Sections']) == "String")
{ $results = mysql_query("SELECT * FROM Table1");
while($row = mysql_fetch_array($results))
{ echo $row['Tags']; }
in Data2.php
/*give data from database2 and Use for events*/
if ($_POST['GallerySec']) == "String")
{ $results = mysql_query("SELECT * FROM Table2");
while($row = mysql_fetch_array($results))
{ echo json_encode($row); }
in Client side when i use it then Data1.php works very well but Data2.php only when i write an
alert('Some stringh');
after
var data = jQuery.parseJSON(response);
line, it's work well, why? what's due to this problem?
I'm going to guess that you need the second .post() to be processed AFTER the first .post() and when you put the alert() in, that guarantees that it will go in that order, but without the alert(), it is a race condition and depends upon which .post() returns quicker.
There are a couple ways to fix the sequencing. The most straightforward is to start the second .post() from the success handler of the first so that you know the first has already completed.
You can also use jQuery promises or you could use your own flags to keep track of which has finished and call the last bit of code only when both have finished.
Here's how you would start the second .post() from the success handler of the first to guarantee the order:
function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
});
};

Jquery not connecting to .php

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.

Having an issue with jQuery, AJAX and PHP (posting)

I am using JQuery and AJAX to post to a PHP file which will eventually parse the data and insert it in a database.
I'm having issue display trying to see what's wrong with my javascript that it will not post the PHP file.
I know it is not posting because I don't recieve and email which is the first function in the PHP file.
JS
$(document).ready(function() {
var ptitle = $("#name").val();
var pdesc = $("#desc").val();
var pemail = $("#email.").val();
$('#submit').click(function() {
sendValue(ptitle, pdesc, pemail);
});
});
function sendValue(ptitle, pdesc, pemail) {
$.post("<?=MOLLY.'update.php'?>", {
stitle: ptitle,
sdesc: pdesc,
semail: pemail
}, function(data) {
//
}, "json");
}
PHP
mail($myemail,'test','test');
if ($_POST){
$title = $_POST['stitle'];
$email = $_POST['semail'];
mail($myemail,$email,$title);
}
You have a typo:
$(document).ready(function() {
var ptitle = $("#name").val();
var pdesc = $("#desc").val();
var pemail = $("#email.").val(); // <---- I assume you meant "#email".
$('#submit').click(function() {
sendValue(ptitle, pdesc, pemail);
});
});
Start by checking that your PHP file runs, replace the content with something like:
PHP
echo "Im running";
Then in your JS do:
$.post("<?=MOLLY.'update.php'?>", function(data) {
console.log(data);
}, "json");
and see if the message is returned and logged in the console.
If it is, check your $_POST by echoing back the values you sent, also echo back your email variable to see that it outputs correctly.
If it all works fine, you need to check if your server is set up correctly for the mail command to actually be able to send an email, as the problem is most likely serverside when everything else is eliminated.
Oh, and you should do what cillosis says, use isset and check something in the $_POST superglobal, not just a if($_POST), but since your running the mail function before that in your PHP, that's probably not your main problem.

How do I send and receive vars with jquery and AJAX?

so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);

Categories