Cant get PHP value in jquery - javascript

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);
});

Related

How to pass a get parameter into an ajax url

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.

How do I to pass html cell id to php variable

I'm trying to create a sign up page for people to select open time slots for an event booth. I've hijacked code from "phpmyreservation" but I need specific dates. So I've created two arrays. One for "Day" and One for "Time". The combination of these two values are the id of the each table cell and are values stored in the MySQL table with the person/group that has chosen to man the booth on that date and time.
Assuming I need code to replace "void(0)" and a script that would put the $Aday and $Atime into one or two php variables.
How do I pass the HTML TABLE CELL ID to PHP variables?
<?php
echo '<table><tr><td></td> ';
foreach($global_days as $Aday) {
echo '<th>'.$Aday.'</th>';
}
echo '</tr>';
foreach($global_times as $Atime) {
echo '<tr><th class="reservation_time_th">' . $Atime . '</th>';
foreach($global_days as $Aday) {
echo '<td><div id="div:' . $Aday . ':' . $Atime . '" onclick="void(0)">' . read_reservation($Aday, $Atime) . '</div></div></td>';
}
echo '</tr>';
}
echo '</table>';
?>
This may be useful:
https://github.com/olejon/phpmyreservation
I think I've made progress, but I'm still stumped
I changed:
onclick="void(0)"
to
onclick="process(\'' . $Aday . '\',\'' . $Atime . '\')"
and
created the js file:
function process() {
var theDay = Aday;
var theTime = Atime;
var request = $.ajax({
type: 'post',
url: 'reservation.php',
dataType: "html",
data: { Aday: theDay, Atime: theTime }
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
and added to php file:
if(isset($_GET['theDay']))
{
$day = $_POST[$theDay];
$time = $_POST[$theTime];
}
The page appears to work to some extent but not... $day & $time are null
According to your if statement, a blank response is expected.
You need to check $_POST instead of $_GET since you are making a POST request and of course output something.
if(isset($_POST['theDay']))
{
$day = $_POST[$theDay];
$time = $_POST[$theTime];
echo $day . " " . $time;
}
Also, you have to make process() accept parameters. So your code would look like:
function process(Aday, Atime) {
var theDay = Aday;
var theTime = Atime;
var request = $.ajax({
type: 'post',
url: 'reservation.php',
dataType: "html",
data: { Aday: theDay, Atime: theTime }
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
And your onclick attribute would look like onclick="process($Aday, $Atime)".

Ajax MySQL query does not return current data

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() ,

pass array values from javascript to php

<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>

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);

Categories

Resources