I have a button here:
<button type="button" class="btn btn-primary">add me</button>
I tried to use AJAX; in my database I have a sp_status ( in my $UserData which is an array). I wanted to change the user sp_status in database with id of $UserData['sp_id'] from 5 value to 0.
Here is the code I try to do this with it:
<script>
$(document).ready(function(){
$(".btn").click(function(){
alert("PROBLEM IS HERE!");
$.ajax({
url: "update.php",
type: "POST",
data: {uid: $UserData['sp_id']}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
}
});
});
});
</script>
The $UserData array has sp_id as identifier of the user.
Inside of update.php in same folder I wrote this code:
<?php
if(isset($_POST['uid'])){
$query = mysql("UPDATE `signup_participant` SET sp_status = 0 WHERE sp_id = ".$_POST['uid']));
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
There are two main problems I face with. First when I move alert("PROBLEM IS HERE!");one line down, and click, nothing happens.
The other problem is about update.php. I copy and paste UPDATEsignup_participantSET sp_status = 0 WHERE sp_id =10 (static value of 10) and everything works fine in console of phpMyadmin.I read a lot of questions here on stack, but no one helps.
Can anyone fix this?
EDIT:
As friends said, I change my code to this ( the AJAX part):
<script>
$(document).ready(function(){
$(".btn").click(function(){
alert('Hello');
$.ajax({
url: "update.php",
type: "POST",
data: {uid: "<?php echo $UserData['sp_id'];?>"}
success: function(data){
data = JSON.parse(data);
}
});
});
});
</script>
The weird thing is that the popup alert is not shown anymore. Is there any ideas?
Yes, you have to mistakes:
The first one is "$UserData['sp_id']" which you called in a Javascript code, it's not clear what do you mean from this variable or where did it come from, if it's a value of an Html element then it should be:
data: {uid: $('#sp_id').val();},
And if it's a Php variable it would be:
data: {uid: <?php $UserData['sp_id']; ?>},
The next mistake is in the Php server code:
$query = mysql("UPDATE `signup_participant` SET sp_status = 0 WHERE sp_id = ".$_POST['uid']));
$results = mysql_fetch_assoc($query);
Those two commands are separated, the first one is for updating database and the second one for showing results from it and they must be like follow:
$query = "UPDATE `signup_participant` SET sp_status = 0 WHERE sp_id = ".$_POST['uid'];
mysql_query($query);
$query = "SELECT * from `signup_participant` WHERE sp_id = ".$_POST['uid'];
$select = mysql_query($query);
$results = mysql_fetch_assoc($select);
Related
I'm working on a project where I have an HTML file with 2 different divs: "product" and "price". The text inside these divs must come from a row into a database. I can easily access these text values with a php file. I'm also able to get just one of them using AJAX and I can put it inside one of the divs. The problem is I don't know how I can get both product and price and put them inside the divs. I've found some very similar questions but none of the answers have worked for me.
Here is the JS code that I have:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#product").html(response);
}
});
Here is the php (the columns I have are just id, product and price):
mysqli_query($link, $query);
$query = "SELECT * FROM products WHERE id = 1";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
echo "{$row['product']}";
}
}
As I said, the code above works, but only for "product". I want to get both "product" and "price". I really appreciate any help you can provide.
You need to use JSON. Here is a simple example:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#name").html(response.name);
$("#shoes").html(response.large);
},
dataType: 'json'
});
And then in the PHP to return back JSON use this approach:
$array = array('name' => 'Bob', 'shoes' => 'large');
echo json_encode($array);
You can amend my PHP so you return back whatever you query from your database.
So i have a for each function that prints the "local" column from this database:
https://i.imgur.com/IzKOzkt.png
It is working all good till here, this is what i get:
https://i.imgur.com/WH7d4uh.png
Now i want to send variables by post, when the user clicks on different menu items, i've tried everything, but i cant get it to work. Here is my code:
<?php
$query = "SELECT * FROM credenciais_sensores where ambiente = '1'";
$results = mysqli_query($conn, $query);
foreach ($results as $result){
$local = $result['local'];
$local = substr($local,0,7);
echo "<li><a class='clsPostData' data-oxiid='".$result['oxi_sensorid']."' data-oxikey='".$result['oxi_apikey']."' data-redoxid='".$result['redox_sensorid']."' data-redoxkey='".$result['redox_apikey']."' href='#'>".$local."</a></li>";
}
?>
This is working fine, the menu is being printed as i want, but now i cant get to post the data i want, like the "oxi_sensorid", etc... Here is my javascript:
<script type="text/javascript">
$(function(){
$('.clsPostData').click(function(e){
e.preventDefault();
var objPost = {};
objPost.oxiid = $(this).data('oxiid');
objPost.oxikey = $(this).data('oxikey');
objPost.redoxid = $(this).data('redoxid');
objPost.redoxkey = $(this).data('redoxkey');
$.ajax({
url: 'getObjects.php',
type: 'post',
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});
});
});
</script>
And my getObjects.php file:
<?php
$oxiid = $_POST["oxiid"];
$oxikey = $_POST["oxikey"];
$redoxid = $_POST["redoxid"];
$redoxkey = $_POST["redoxkey"];
$response["message"] = "Grettings from php, we receive your data: ".$oxiid . $oxikey . $redoxid . $redoxkey;
echo json_encode($response);
?>
But i'm always getting the popup saying "undefined" when i click on any menu item... Any help?
I think the problem there is you need to set the dataType to json. Try adding dataType: 'json' after type: 'post' on your ajax code:
$.ajax({
url: 'getObjects.php',
type: 'post',
dataType: 'json', // add this
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});
Can some body help me get the current value from this option tag
to account.php as a session variable or anything ..
// loadsubcat.php This code is for dependent dropdown
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
var javascriptVariable = $('#sub_cat').val();
I know this can be solve using ajax but I don't know how.
I will use the javascript variable as a reference for a couple of checkboxes under it but first must be passed as a php variable.
you ajax will look like this,
$.ajax({
type: 'POST',
url: "account.php",// path to ajax file
data: {javascriptVariable:javascriptVariable},// you can pass values here in key value pairs.
success: function(data) {
alert(data);
}
});
You can send n number of key => value pairs.
like
parent_cat:100
Next:
echo $_POST['javascriptVariable']; // <--- grabbing ajax data here
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
what ever echoed in php file will come in ajax success data,
alert(data) will alert what you had echoed in php. you can use that in your html file.
I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.
When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.
<script type="text/javascript">
$(document).ready(function() {
$(".content-short").click(function() { //
$.ajax({
type: "GET",
url: "content.php", //
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
});
</script>
content.php
<?php
include "mysql.php";
$query= "SELECT Content FROM blog limit 1";
$result=mysql_query($query,$db);
while($row=mysql_fetch_array($result))
{
echo $row['Content'];
}
mysql_close($db);
?>
Is there an alternate way to do this or something that I need to correct for it to work?
Thanks
First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:
$(".content-short").click(function() {
// get the ID
var id = $(this).attr('data-id');
$.ajax({
type: "post",
url: "content.php",
data: 'id=' + id
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
Next up is reading the value you passed in using the script:
<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id = intval($id);
$query = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
echo $row['Content'];
}
mysql_close($db);
?>
There you go, I have modified your query to allow fetching by id. There are two major caveats:
First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.
The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:
echo $row['Content'];
with this:
echo json_encode(array('success' => $row['Content']));
Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:
success: function(response){
$(".content-full").html(response);
}
into this:
success: function(response){
if(response.success) $(".content-full").html(response);
else alert('No results');
}
Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php
You can look at passing a parameter to your script, generally like an id by which you can search in the db.
The easiest way to achieve this is by get parameters on the url
url: "content.php?param=2",
Then in php:
<?php $param = $_GET['param'];
...
I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.