i have been trying to fix this problem for a while and i am hoping that someone can help.
I want to pass an id from a php page to be included in the url of an ajax call.
See what i mean
$(document).ready(function(){
$.ajax({
url: "http://localhost/app/data-(ID)",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var value = [];
From the php page
$parameter = $_SERVER['QUERY_STRING'];
$ID = $mysqli->escape_string($_GET['id']);
Is it possible. If not how can a parameter from mysql database be included in an ajax url. Thanks inadvance
in your php page you can have a 'script' html element, where you can do something like this:
<script>
$(document).ready(function(){
$.ajax({
url: "http://localhost/app/data-<?php echo $ID?>",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var value = [];
Preprocessing javascript in a php file is generally considered bad practice, but if you really need to, you can use echo inside your php file to concatenate your $ID to the url value of the ajax call:
page.php
<?php
echo " $(document).ready(function(){ " .
" $.ajax({ " .
" url: 'http://localhost/app/data-" . $ID . "'," .
" method: 'GET', " .
" success: function(data) { " .
" console.log(data); " .
" var date = []; " .
" var value = [];" ;
?>
Note the example above won't run correctly, as it is only a portion of the JavaScript.
Related
I want to write an Ajax request that Returns data from a MySQL-database. But it does not work properly, because the Ajax request does not return the current values of the mysql database, if data has changed. Instead it always returns the old data of the database. The php-file is working properly, if I open it in a browser, it shows the correct current data values. I found out, that the Ajax request only shows the correct current data values, if I first open the php-file manually in a browser. If I then again use the ajax request, it returns the correct current data. What am I doing wrong?
This is the code for the Ajax request:
var scannedTubes = (function() {
var tmp = null;
$.ajax({
async: false,
url: "ajaxtest.php",
success: function(response) {
alert("RESPONSE: " + response);
tmp = response;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
return tmp;
})();
The code of the ajaxtest.php file is the following:
<?php
$con = mysqli_connect("", "root");
if(mysqli_connect_errno()){
echo "FAIL: " . mysqli_connect_error();
}
mysqli_select_db($con, "multitubescan");
$queryStr = "SELECT code FROM scan WHERE row = 0 AND code <> 'EMPTY'";
$res = mysqli_query($con, $queryStr);
$num = mysqli_num_rows($res);
$scannedTubes = "";
while($data = mysqli_fetch_assoc($res)){
$scannedTubes = $scannedTubes . " " . $data["code"];
}
$scannedTubes = $num . " " . $scannedTubes;
mysqli_close($con);
echo $scannedTubes;
?>
I suppose data is cached by your browser.
Make the url unique:
url: "ajaxtest.php",
to
url: "ajaxtest.php?rnd=" + Math.random() ,
<script>
$("#submit").click(function () {
var newhour= [];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]); // output: each: 07:00,08:30
each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
var jsonString = JSON.stringify(newhour);
$.ajax({
type: "POST",
url: "exp.php",
data:{data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
});
<script>
I want to pass the newhour array values to php and use them to insert into a table.
so php file, exp.php:
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
$sql = "insert into exp_table (hour) values ('$d')";
mysql_query($sql);
}
However I can not take the values. What is wrong with the code?
Could you please help me?
Thanks in advance.
according to the answers i tried this on php side, but it returns NULL.
$data = json_decode($_POST['data'],true);
//$data = explode(",", $_POST['data']);
echo "data: " .$data;
var_dump($data); // no output
foreach($data as $d){
echo $d; // no output
}
You do not have to stringify an array in the javascript.
.ajax looks after all that.
pass
data: {newhours: newhour},
then you will get $_POST['newhours'] in the PHP code which will be the array you had in javascript.
In Ajax there is not "type" params, use "method".
Beside that everything should works, you might need to decode the json using json_decode($_POST['data']) on in your php file.
Hopes it helps !
Nic
Pass the array without JSON.stringify in ajax data post. And fetch the data in php file using $_POST['data'].
I just have tried below code and it working great.
<?php
if(isset($_POST['data'])){
print_r($_POST);exit;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var newhour= [];
arrayNumbers = [['07:00','08:30'],['08:30','18:00','19:00']];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]);
// output: each: 07:00,08:30 each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
$.ajax({
type: "POST",
url: "abc.php",
data:{data: newhour},
cache: false,
success: function(data){
console.log(data);
}
});
});
</script>
my Php code;
$sql = "SELECT * FROM login_speak";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_assoc())
{
$tempArray[] = $row;
}
$resultArray = json_encode($tempArray);
echo $resultArray;
}
mysqli_close($con);
?>
my jquery code;
$.getJSON("url.php", function(data){
$("ul").empty();
$.each(data.result, function(){
$("ul").append("<li>Name:"+this['Name']+"</li>");
alert("kj");
});
});
I have done several things ,But nothing works.I php is correct and I have problem in script ,I guess.
Please give me the answer ,What wrong is done.
Thanks
json_encode from php can be accessed easily in a Javascript varible
There are many ways of doing this, however consider the simple way first if it works with the array you are sending.
in your example - assuming jquery:
var valu = [];
$.ajax(url: "url.php",
success: function(data){
valu=data;
});
see: http://www.dyn-web.com/tutorials/php-js/json/array.php
works for numeric and associative arrays.
I think you want change your code to something like this..
$.each(data.result, function(index,value){
$("ul").append("<li>Name:"+value.name+"</li>");
alert("kj");
});
Heres what I would do.
$.ajax({
url: "url.php",
type: "GET",
dataType: 'json'
}).done(function (data) {
$.each(codes, function(key,value){
$("ul").append('<option value="' + key + '">' + key + ' - ' + value + '</option>');
});
}).fail(function (jqXHR, textStatus, error) {
alert("error message");
console.log("error message: " + error);
});
I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.
I have below jquery AJAX,
var reply_content = $('#summernote_1').code();
$.ajax({
type:"POST",
url: "<?php echo base_url();?>index.php/test/send_reply/"+<?php echo $testinfo->test_id;?>,
data: $("#test_fm").serialize()+'&file=' + file + '&test_subject=<?php echo $testinfo->testsubject;?>' +'&reply_content=' + reply_content,
});
i have file variable is array contains like below
array([0]=> a [1]=>b),
This was returned with other function which i am passing in AJAX,
How can i pass this in AJAX?
var reply_content = $('#summernote_1').code();
$.ajax({
type:"POST",
url: "<?php echo base_url();?>index.php/test/send_reply/"+<?php echo $testinfo->test_id;?>,
data: {$("#test_fm").serialize()+'&file=' + file + '&test_subject=<?php echo $testinfo->testsubject;?>' +'&reply_content=' + reply_content},
});
and you can use serilizeArray()
If you are trying it in php then you can try like this:
$url = urlencode(serialize($your_array))
append $url in the data
data: {$("#test_fm").serialize()+"&file=<?php echo $url; ?>&test_subject=<?php echo $testinfo->testsubject;?>" +"&reply_content=" + reply_content}
and to restore the variable you can use
$arrVar = unserialize(urldecode($_POST['file']))
You can use serializeArray() to create an object you can add too.
Its also a good idea to separate your php from you js where possible to aid readability:
var url = "<?php echo base_url() . 'index.php/test/send_reply/' . $testinfo->test_id;?>";
var test_subject = "<?php echo $testinfo->testsubject;?>";
var data = $("#test_fm").serializeArray();
data.push(
{
file: file,
test_subject: test_subject
}
);
$.ajax({
type:"POST",
url: url,
data: data
});