Using ajax request variable to populate a dropdown - javascript

My limits in javascript are preventing me to solve a problem I am facing at present.
I am doing an ajax request for retrieving some database values.
I receive the data I need alright, but
I am unable to use that value "cityareax" to either populate an existing dropdown or to create a new one.
Here is the code:
<script type="text/javascript">
function autocomp_city() {
var min_length = 2; // min caracters to display the autocomplete
var keyword = $("#city_namex").val();
if (keyword.length >= min_length) {
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
} else {
$("#city_list").hide();
}
}
// set_item : this function will be executed when we select an item - a city name
function set_item(cityname, statename, cityarea) {
$("#city_namex").val(cityname);
$("#statex").val(statename);
// hide proposition list
$("#city_list").hide();
$("#cityareax").val(cityarea);
}
</script>
Can somebody help me?
tx Roberto

and thanks for your interest. I found my own solution. The main problem was timing.
I was trying to use data that I received from Ajax in a script that was inactive, having been executed onload.
When I moved my variable processing code in the function that was working AFTER THE AJAX REQUEST, everything went fine. It was about a week that I was running in circles trying to find a solution ...
Roberto

Are you missing a return type?
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
datatype: "html",
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
What's the php output?
Need to use echo in PHP instead of return.
<?php
$output = some_function();
echo $output;
?>

Related

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

Check mysql DB on input using JS

&I have a qty field for goods receiving. I want to check the receipts table against the orders table and make sure that value being entered does not exceed the total order value. I have this code in my field:
<div class="pure-control-group">
<label for="rec_qty">Qty Received:</label>
<input type="text" name="rec_qty" id="rec_qty" onChange="receiptTotal()"></input>
</div>
Javascript Code:
function receiptTotal(){
$.ajax({
type: "GET",
url: "receipts.php?do=checkrec&id="+row.pur_ID,
//dataType: 'json',
success : function(data) {
// Here I want to do the comparisons of the two fields.
// If data.rec_qty + form.rec_qty > pur_qty then throw error.
}
});
}
Finally PHP Code:
if($_GET['do'] == "checkrec") {
$rec = [];
//First get the receipts total for this ID
$getRows = $db->query(sprintf("SELECT sum(rec_qty) as total_qty, pr.pur_qty from receipts inner join purchases pr on rec_purID = pr.pur_ID WHERE rec_purID = '$groupid' GROUP BY pur_ID")) or SQLError();
while($rec = $getRows->fetch_assoc()) {
$result[] = $rec;
}
echo json_encode($result);
}
I am a complete novice just incase anyone was wondering. I would really appreciate the help!
At first I thought you were asking how to do it in your database, but now I see you are already getting the data from your server and returning it. So I'll answer now, hopefully its what you meant.
function receiptTotal(){
$.ajax({
type: "GET",
url: "receipts.php?do=checkrec&id="+row.pur_ID,
//dataType: 'json',
success : function(data) {
var rec_qty = $('#rec_qty').val();
if((data.rec_qty+rec_qty) > data.pur_qty){
alert('Value is too high!!'); // or whatever error you want
}
}
});
}
I will say this though.....you are basically firing a server request along with a database request, every time the field changes. Which is extremely inefficient. You should just load the data once, and then refer to it locally for the check. But I'll let you figure that out on your own :)

Sending form data with ajax echo data with php not displaying

Im learning Ajax...normally I dont like posting about a subject I know very little of but I believe Im on the right path here (maybe not...?) so I will take a chance to find out.
Ive got 3 select boxes each box populates with values based on the the selection of the box before it:
Everything is working perfectly, when the user clicks submit I want to send the 3 textbox values to 3 php variables and echo it on the same page...
Now my data is not echoing (the data of the variables are not displaying) but when I look in my console on firefox I can see the value of the variables...
Here is the selection made on the select boxes
Here is what im seeing in my console
Yet it is does not echo on the page....?
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
PHP below form
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$sport = $_POST['sport'];
$round = $_POST['round'];
$tournament=$_POST['tournament'];
echo $sport;
echo $round;
echo $tournament;
}
I don't see anything in your code that would make the values display on the page. You would need to either do some DOM insertion in your AJAX success function, or do a full page refresh and echo the data out via PHP (but that would probably defeat the purpose of doing an AJAX call in the first place.)
If you want to go the AJAX route, I would suggest editing your PHP to the following:
echo json_encode(array(
'sport' => $sport,
'round' => $round,
'tournament' => $tournament
));
This will return a JSON object for your jQuery AJAX call to consume.
In your jQuery success function, do something with those values, like so:
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
dataType: 'json',
success: function(data) {
$('<div></div>').text(data.sport).appendTo('body');
$('<div></div>').text(data.round).appendTo('body');
$('<div></div>').text(data.tournament).appendTo('body');
}
});
Note the additional dataType argument to $.ajax. To do it the right way, you'll also want to set your headers in your PHP response to "application/json"
You ajax is just displaying the output in console. Change the ajax success to display it in page.
Make changes after success as:
success:function(data){
$('someelementclassorid').text(data);
}

Calling a php function from Javascript and using a javascript var in the php code

JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !

How to send a JQuery Variable to another PHP page via dblclick()?

So guys, I made a listbox and if I dblclick to an item the value of it gets saved into "val", but I can't send it to the next PHP File. I also alerted "val" - the value is really saved in it. I also get the function succes displayed in the browser console. what to do?
thanks
My Function:
$(document).ready(function () {
$("option").dblclick(function () {
var lb = document.getElementById("liste");
var val = lb[lb.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'about.php',
dataType: 'HTML',
data: {
aufid: val
},
success: function (data) {}
});
});
});
PHP Code in about.php:
$id = $_POST['aufid'];
Can you try to see what variables are in the $_POST superglobal?
print_r($_POST);
try to set the url your full adrees
url: 'http://myadress.com/about.php',
java script is running on your local computer so it might send the request to you own pc where no about.php exist

Categories

Resources