i use this code for on change
<script>
$('.BIR').change(function() {
var id = $(this).val(); //get the current value's option
$.ajax({
type:'POST',
dataType: "json",
url:'assets.php',
data:{'id':id,MainM : IR},
success:function(data){
$("#IRd").html(data);
}
});
});
</script>
i send multi variable form this javascript to the assets.php successfully
<?php
$id = $_POSt['id'];
$MainM = $_POST['MainM'];
// some php functions here to get the final data
$Otp = "xxxxx";
$name = "bbbbb";
?>
i want to pass this data back to the javascript..
if i passed one i use this
echo $Otp;
this works fine , but i want to pass this 2 variables or more .. but i don't know how to do this .. so please help.
I think the ideal way to be to use json. something like
echo json_encode(['Otp': $Otp, 'name': $name])
On your php side would work, and then you could use that data in your success function like such :
success:function(data){
//you can then use your data like object properties, for an example
const name = data.name;
const Otp = data.Otp;
}
Put the variable in an array on assets.php page like below
$newArray['Otp'] = "xxxxx";
$newArray['name '] = "bbbbb";
echo json_encode($newArray);
Add this in javascript
success:function(data){
var text = "OTP: "+data.Otp+" Name: "+data.name;
$("#IRd").html(text);
}
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
}
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 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.