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.
Related
I have button that is using AJAX post method to post value into PHP.
When I echo that value back in JavaScript it's always echoing 0, even when I am 100% sure that value in PHP is not 0.
Here is JavaScript:
function slanje(br){
$.ajax({
type: 'POST',
dataType: 'html',
data: {
'broj' : br,
}
});
}
function otvaranje(id, broj){
slanje(broj);
var testNumber = <?php echo $br; ?> + "";
And PHP (I do file write to check if PHP received correct value):
if(isset($_POST['broj'])){
$br = $_POST['broj'];
$file = fopen($br . "broj.txt", "w");
fclose($file);
}
Here is what value I get back in Javascript:
And here is value in PHP:
Edit 2: I want to post variable in PHP, than get value of element of PHP array with index I passed with ajax. And that without reloading page. I didn't include array part because while I was testing around I couldn't even make it echo back variable I'm passing using AJAX.
If you want to do it using AJAX, then let your PHP script return the POSTed value and grab it in the success handler of the AJAX request.
For the success handler to be able to change the value of testNumber, the variable has to be declared outside of function otvaranje.
Here are the necessary modifications (also take note of the comments I added):
PHP
if(isset($_POST['broj'])){
$br = $_POST['broj'];
$file = fopen($br . "broj.txt", "w");
fclose($file);
// Just output the value and exit
// If there is business logic doing something with
// $br, then move this after that code.
// But remember to only do this if the script was
// called with POST, otherwise the initial request
// wouldn't work anymore.
print $br;
exit;
}
JavaScript
var testNumber = "<?php echo $br; ?>";
function slanje(br){
$.ajax({
type: 'POST',
dataType: 'html',
data: {
'broj' : br,
},
success: function(data) {
// called when the request succeeded
testNumber = data;
}
});
}
function otvaranje(id, broj){
slanje(broj);
// move outside: var testNumber = <?php echo $br; ?> + "";
// rest of function content
}
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);
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 a form with 17 checkboxes. When one of these changes, JavaScript should submit the values to the server (running PHP).
I want to use JSON, because the checkboxes give two arrays which have to be seperated in PHP
In JS, I create an JSON-String, which I want to submit via POST and read and decode in PHP.
The String looks like this atm: [["2015-06-26","2015-06-27"],["2","3","4","5","6","7","8","9","10","11","12","13","14"]] - This is what I want it to be.
This is, what my AJAX-function looks like:
var fullArray = [dateArray, trackArray];
var jsonFullString = JSON.stringify(fullArray);
//jsonFullString == [["a","b","c"],["d","e","f","g"]]
$.ajax({
type:'POST',
url:'shownitems.php',
data: jsonFullString,
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
When I get it to PHP, and search for $_POST[0] the success function in JS doesn't show anything. When I search for $_POST, I get "Array.." back.
This is, what my PHP looks like (This is my test snippet):
<?php
echo $_POST;
echo ".";
echo $_POST[0];
echo ".";
echo $_POST[0][0];
$array = array();
?>
I am also using jQuery.
In your JS:
/* dateArray and trackArray must be variables with values */
$.ajax({
method: "POST",
url: "shownitems.php",
data: { date: dateArray, track: trackArray }
}).done(function(response) {
alert(response);
});
In your PHP:
<?php
var_dump('Date: '.$_POST['date']);
var_dump('Track: '.$_POST['track']);
?>
You should get your request content instead the $_POST variables.
Something like this would
$json = file_get_contents('php://input');
$obj = json_decode($json); //Will contain your array of two arrays
In case you wanted to get your post variables like you are doing, you could change your AJAX request and use:
$.ajax({
type:'POST',
url:'shownitems.php',
data: {
data: jsonFullString
},
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
And your PHP would be:
$json = $_POST["data"];
$obj = json_decode($json); //Will contain your array of two arrays
When I make a .post() request such as
var data = $(this).serialize();
$('form').on('submit', function(event) {
event.preventDefault();
$.post('server.php', data, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
everything's working - the name from the database appends to the #data element withing the p tags. But, when I try to pass data as an object like this
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
than it doesn't work. I tried changing the argument of the function within the .post() to id and probably every combination of names for .post()'s arguments and variables within the PHP file also, without success. Here's the working intact PHP file compatible with the first version of my .post() request in this question:
<?php
$id = $_POST['id'];
$connection = new mysqli('localhost', 'root', '', 'dummy_db');
$query = 'SELECT name FROM dummy_db_table WHERE id = "' . $id . '"';
$result = $connection->query($query);
$row = $result->fetch_assoc();
echo $row["name"];
$connection->close();
?>
Please note that the name of the input field for the ID in the HTML file is 'id'. I do understand that it is this name attribute within HTML which helps PHP determine the value of it, but how is it doing so without me specifying the connection with the PHP through form's action attribute? I'm doing this exclusively through AJAX (.post()) and AJAX is not telling PHP anything specific about THAT id field. What am I missing here? Also, how would I go about sending the object of values instead of a single one through .post()'s data attribute? Thank you.
You have not add the form code here so lets assume your form have two fields name and address.
Actually you need to put the serialize() function under the event. Like
$('form').on('submit', function(event) {
event.preventDefault();
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
Now on your server.php file if you print the following line:
$id = $_POST['id'];
echo $id;
this will show you the results like: name=iffi&address=UK
I hope this will help you more.