Hope your are fine!
I'm would like to execute a request (SQL) like this one:
SELECT Name FROM course WHERE IdSectionFK = '.$idSectionFK.';
I have the list of sections:
while($row = $selectAllSection->fetch(PDO::FETCH_OBJ)){
echo "<option value=".$row->IdSection.">".$row->Name."</option>";
}
And I would like to display the data only for the selected value. I tried something like this to get the value of the list:
<script>
function displayVals() {
var idSection = $("#sectionListe").val();
$.post('index.php', { 'idSection': idSection },function (){
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
}
$("select").change(displayVals);
displayVals();
</script>
So, the variable "idSection" is equale to the PHP variable "idSectionFK" in my SQL request.
But how can I execute the right SQL request ?
Thank you so much for your help!
Lapinou.
AJAX is the solution.
JS code:
function displayVals() {
var idSection= $("#sectionListe").val();
$("p").html(idSection);
$.post('/url/to/php/file', { 'idSection': idSection }, function (response) {
// do something with the response here
// e.g: $('select').append(response);
console.log(response);
});
}
$("select").change(displayVals);
displayVals();
PHP code to process the received data:
$idSectionFK = 0;
if (isset($_POST['idSection'])) {
// get the ID from ajax, run SQL here
$idSectionFK = intval($_POST['idSection']);
$query = "SELECT Name FROM course WHERE IdSectionFK = '.$idSectionFK.';";
// .... your code ...
}
Just to give you the basic idea.
Related
I want to show notifications when new row inserted.I've achieved it through the below code,
Ajax
<script>
var old_count = 0;
var i=0;
setInterval(function(){
$.ajax({
url : "shownotify",
success : function(data){
if (data > old_count)
{
if (i == 0)
{old_count = data;}
else{
$('#notify').html("New user");
old_count = data;
}
} i=1;
}
});
},1000);
</script>
Now I want to show the count of new users which I returned from controller,
public function shownotify()
{
$action=DB::table('users')->where('admin_action_at', 'null')->count();
$data=Move::count();
return compact('action', 'data');
}
How do I get it in ajax function?Can anybody help?
You need to pass the array $data but you are passing a string.
public function shownotify()
{
$action=DB::table('users')->where('admin_action_at', 'null')->count();
$data=Move::count();
$return_array = compact('action', 'data');
return json_encode($return_array);
}
And make a little change in your ajax success callback function like:
success : function(data){
if (data.data > old_count)
{
if (i == 0)
{old_count = data.data;}
else{
$('#notify').html(data.data + "New user");
old_count = data.data;
}
} i=1;
So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;
Please help,
I have a dynamically generated set of button-incremented inputs. First i store id's and values into localstorage, and everything goes fine and i can see all the id-value pairs, but i cannot send the data using AJAX call.
Here's what it looks like:
The AJAX is assigned on button click:
<script>
$("#send_order").click(function (e) {
if (localStorage) {
if (localStorage.length) {
for (var i = 0; i < localStorage.length; i++) {
var pid = localStorage.key(i);
var value = localStorage.getItem(localStorage.key(i));
$.ajax({
url: "update.php?pid="+pid+"&qty="+value,
success: function(){
alert( "Прибыли данные: ");
}
});
}
} else {
output += 'Нет сохраненных данных.';
}
} else {
output += 'Ваш браузер не поддерживает локальное хранилище.';
}
)};
</script>
But nothing happens when the button is clicked.
What i do wrong?
While your code looks fine it is little inefficient to send your localstorage data one by one in a loop. It makes more sense to convert your localstorage to a json string and send everything at the same time. You can json_decode the json string in your php update script. Also I included a function to test if localStorage is available by trying to write in it. This is more reliable then if(localStorage)
$("#send_order").on("click", function () {
var output='';
if(localStorageTest() === true){
console.log('localStorage is available');
if(localStorage.length){
var data=JSON.stringify(localStorage);
$.ajax({
type: "GET",
url: "update.php?data="+data,
success: function(){
alert( "your data is send correctly!");
}
});
}else{
output += 'localStorage is empty\n';
}
}else{
output += 'localStorage is not available\n';
}
})
function localStorageTest(){
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
Im trying to send some data to the server through AJAX with the value i get from a JS variable.
Code:
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/'+_src;
}
function guardarCambios() {
$.post("guardarCambios.php",
{url: url},
function(response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
}
alert(url);
}
</script>
The idea is update the user picture with the url i get from aplicarFoto(_src) with the variable url .
The first function (aplicarFoto(_src)) alone works correctly, but when i put the another function (guardarCambios()), the first function doesnt work, therefore the second neither! I dont know why, but it just happens when using ajax functions because i did a test with an alert(url) (sunrrounding the rest of code with comments) in the second function and both work correctly!
Some guess? Thank you!
Your script alone has syntax errors.
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/' + _src;
}
function guardarCambios() {
$.post("guardarCambios.php", {
url: url
}, function (response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
alert(url);
}
);
}
</script>
So, for some reason my script refuses to work, although it seems to be correct.
I tried using $.ajax instead, but not working with that either. Any ideas what's gone wrong?
<script>
$(document).ready(function() {
$('#saveForm .submit').click(function() {
var _user = $('#saveForm .user');
_userId = $('#saveForm .userId');
_password = $('#saveForm .password');
$('#saveForm').append('<p>Loading...</p>');
$.post("ajax/fetchPhotos.php", {user:_user, userId:_userId, password:_password}, function(data) {
alert(data);
});
return false;
});
});
</script>
In ajax/fetchPhotos.php i have this:
<?php
set_time_limit(0);
session_start();
require_once("includes/functions.php");
require_once("includes/pclzip.lib.php");
/*
Huge block of code here (commented out for the moment)
*/
echo "wut?";
So, when clicking .submit, it should send a request to fetchPhotos.php with three params and then alert "wut?". Right now the page hangs in chrome.. nothing happens. In firefox the page just refreshes. I do get one error in the console, but i only see it for a split second as the page refreshes directly.
Thanks,
Pete
you must use the .val() method to get the value of the inputs.
try this way:
<script>
$(document).ready(function() {
$('#saveForm .submit').bind('click', function() {
var
user = $('#saveForm .user').val(),
id = $('#saveForm .userId').val(),
password = $('#saveForm .password').val();
$('#saveForm').append('<p>Loading...</p>');
$.post("ajax/fetchPhotos.php", {user:user, userId:id, password:password}, function(data) {
alert(data);
});
return false;
});
});
</script>
It seems syntax related problem and also try with absolute url or can do in this way
new Ajax.Request("ajax/fetchPhotos.php", {
method: 'post',
parameters: 'id='+id,
onComplete: function(transport) {
alert(transport.responseText);
}
});