Ajax POST working, but php document cannot get data variable - javascript

When I post something, the network tab of chrome shows that the post is going through with the correct variables, but on the php end, the POST global is empty, and the method on the page is GET for some reason. I hope I am not just missing something obvious, I spent like 4-5 hours troubleshooting. What is occuring, or is suppose to, is that when you type anything in the searchbox, an event listener in the js file triggers and POSTs the value of the search box to the php of the storepage.php. The search bar itself is actually on a seperate php file which makes a header for every html page, but the php that queries the database is in the storepage.php
Picture of network results from entering items into search (notice variable searchInput at bottom of image)
This is where the Ajax POST happens: searchItUp.js
$(document).ready(function() {
console.log("Document Ready. Listening for search bar key presses...");
$('.SearchBar').keyup(function() {
console.log("Key pressed.");
var searchBoxValue = document.getElementById('superSearcher').value;
console.log("Current searchbox value: " + searchBoxValue);
jQuery.ajax({
method: "post",
url: "storepage.php",
data: {searchInput: searchBoxValue},
datatype: "text",
success: function () {
console.log("Ajax functioning properly...");
$('.content').load(document.URL + ' .content>*');
},
error: function() {
console.log("Ajax NOT functioning properly...");
}
});
});
});
Next is the section of the php document (storepage.php) where the javascript file is included, and the POST is directed to.
if (isset($_POST["searchInput"]) && !empty($_POST["searchInput"])) {
echo "searchInput is set... ";
} else {
echo "searchInput is not set... ";
}
echo $_SERVER['REQUEST_METHOD'];
$searchInput = $_POST['searchInput'];
if ($searchInput=="") {
// query all game information based on text in the search bar
$query = "SELECT ProductID,ImgID,Image,GameName,ESRB_ID,ESRB_Img,Rating,ReleaseDate,Description,Tags,Price,PlatformID,PlatformName
FROM PRODUCTS
JOIN PRODUCT_IMAGES USING (ImgID)
JOIN GAME_INFO USING (GameID)
JOIN PLATFORMS USING (PlatformID)
JOIN ESRB USING (ESRB_ID)";
$statement = $db->prepare($query);
$statement->execute();
$GameList = $statement->fetchAll();
$statement->closeCursor();
echo "<script>console.log( 'Game database queried WITHOUT search' );</script>";
}
else {
// query all game information if search is empty
$query = "SELECT ProductID,ImgID,Image,GameName,ESRB_ID,ESRB_Img,Rating,ReleaseDate,Description,Tags,Price,PlatformID,PlatformName
FROM PRODUCTS
JOIN PRODUCT_IMAGES USING (ImgID)
JOIN GAME_INFO USING (GameID)
JOIN PLATFORMS USING (PlatformID)
JOIN ESRB USING (ESRB_ID)
WHERE GameName LIKE '%$searchInput%'";
$statement = $db->prepare($query);
$statement->execute();
$GameList = $statement->fetchAll();
$statement->closeCursor();
echo "<script>console.log( 'Game database queried WITH search' );</script>";
}
I have tried everything I could find online, and I have probably looked at all relevant stackoverflow, and other, posts, but I can't figure it out for the life of me.

You're invoking the script twice. First with $.ajax, where you're sending the search parameter.
Then in the success: function, you invoke it again using $('.content').load. This sends a GET request without the search parameter. So it doesn't show the result of the search in .content.
The AJAX request should return whatever you want to show. Then you can do:
success: function(response) {
$(".content").html(response);
}
Another option is to pass the parameter when calling .load. That changes it to a POST request:
$(document).ready(function() {
console.log("Document Ready. Listening for search bar key presses...");
$('.SearchBar').keyup(function() {
console.log("Key pressed.");
var searchBoxValue = document.getElementById('superSearcher').value;
console.log("Current searchbox value: " + searchBoxValue);
$('.content').load(document.URL + ' .content>*', {
searchInput: searchBoxValue
});
});
});

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.

ajax request is successful, but php is not running

I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:
function getObdDescription(){
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if($length == 5){
window.confirm($length);
$.ajax({ url: '/new.php',
data: {action: 'test'},
type: 'post',
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});
}
return false;
}
Here is new.php
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
?>
I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?
This isnt the way it works if you need to alert the text, you should do it at the front-end in your ajax success function, follow KISS (Keep It Simple Stupid) and in the php just echo the text . that is the right way to do it.
You should do this:
function getObdDescription() {
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if ($length == 5) {
window.confirm($length);
$.ajax({
url: '/new.php',
data: {
action: 'test'
},
type: 'post',
success: function (result) //we got the response
{
alert(result);
},
error: function (exception) {
alert('Exception:' + exception);
}
});
}
return false;
}
In your php
<?php
echo 'message successfully sent';
?>
You are exactly right Muhammad. It was not going to work the way I was expecting it. I wasn't really trying to do an Ajax call, but just to get an alert box to pop up; I just wanted confirmation that the call was working, and the PHP was running. Changing the alert('Successfully called'); to alert(result); and reading the text from the php definitely confirmed that the php was running all along.
I want to stay on topic, so will post another topic if that's what's needed, but have a follow-up question. To elaborate a bit more on what I'm trying to do, I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
Now, I know that this function works. I can then access this function in my Javascript with:
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
This is a block loop, and will loop through the block variable set in the php function. This work upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the php runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the html. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
I'm using this conditional and switch to call the function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. It appears that the block variable is not being set.

how to fetch data from sql server database in php without refreshing the page

I am trying to get some data from the database. I create a function that is located in functions.php file that return a value. On another page, I create a variable and just get that value. I was trying to use the onkey to check the database but then I realize that i need to know the amount of tickets even if they don't type anything.
Here is the function:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$amount_of_tickets = $row['number_of_tickets'];
}
return $amount_of_tickets;
}
And, I am trying to check the database (without refreshing the page) and get the value on this page:
application.php
$amount_of_tickets = is_ticket_able($conn);
Then, I just check that $amount_of_tickets is not 0 or 1. Because if is one then some stuff have to change.
I am doing this (inside application.php):
if($amount_of_tickets !=0){
//show the form and let them apply for tickets.
//also
if($amount_of_tickets == 1){
//just let them apply for one ticket.
}
}
EDIT: I saw that AJAX would be the right one to use, but I am so confuse using it.
UPDATE:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
return $ticket;
}
application.php
$amount_of_tickets = is_ticket_able($conn);
<script type="text/javascript">
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
alert(global_isTicketAble);
if( global_isTicketAble == 0 ){
window.location.replace("http://www.google.com");
}
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
});
}
</script>
So, now the problem is that when I alert(global_isTicketAble); it doesn't alert the value from the database but it does alert everything that is inside application.php...Help plzzz
Server side
Assuming you need to check $amount_of_tickets periodically and this can be computed into application.php, inside that file you'll have
<?php
// $conn is defined and set somewhere
$amount_of_tickets = is_ticket_able($conn);
echo $amount_of_tickets;
exit(0);
?>
This way when the script is invoked with a simple GET request the value is returned in the response as simple text.
Client Side
ajax is the way to go if you want to update information on page without reloading it.
Below is just a simple example (using jQuery) that may be extended to fit your needs.
The code below is a JavaScript snippet. A global is used to store the value (globals should be avoided but it's just for the purpose of the example)
Then a function is invoked and the updated value is fetched from function.php script.
The function -prior termination- schedules itself (with setTimeout) to be re-invoked after a given amount of milliseconds (to repeat the fetch value process).
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
// eventually do something here
// with the value just fetched
// (ex. update the data displayed)
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
}
}
Note that $.ajax() sends the request but does not wait for the response (as async is set to true). When the request is received the function specified as success is executed.
Complete jQuery ajax function documentation can be found here
http://api.jquery.com/jquery.ajax/
I assume that you have a page (application.php) that displays a table somewhere.
And that you wish to fill that table with the data found in you database.
I'm not sure about WHEN you want these data to be refreshed.
On button click or periodically (like ervery 5 seconds)... But it doesn't matter for what I explain below.
In application.php:
Assemble all your page as you already know how.
But inside it, somewere, just insert an empty div where your table should show:
<div id="dynamicContent"></div>
Also add this script at the bottom of the page:
<script>
function getData(){
PostData="";
$.ajax({
type: "POST",
url: "function.php",
data: PostData,
cache: true,
success: function(html){
$(Destination).html(html);
}
});
}
getData(); // Trigger it on first page load !
</script>
There is 2 variables here... I named it "PostData" and "Destination".
About PostData:
You can pass data collected on the client side to your PHP function if needed.
Suppose you'd need to pass your user's first and last name, You'd define PostData like this:
Fname=$("#Fname").val(); // user inputs
Lname=$("#Lname").val();
PostData="Fname="+Fname+"&Lname="+Lname;
In your function.php, you will retreive it like this (like any normal POST data):
$Fname=$_POST['Fname'];
$Lname=$_POST['Lname'];
If you do not need to pass data from your client side script to you server side PHP... Just define it empty.
PostData="";
Then, about Destination:
This is the place for the empty "dynamic div" id ( I named it "dynamicContent" above).
Don't forget about the hashtag (#) for an id or the dot for a class.
This is a jQuery selector.
So here, PostData would be defined like this:
Destination="#dynamicContent";
The result of the ajax request will land into that "dynamic div".
This WILL be the result of what's defined in function.php..
So, if you follow me, you have to build your table in function.php...
I mean the part where you do your database query and your while fetch.
echo "<table>";
echo "<tr><th>column title 1</th><th>column title 2</th></tr>"
while ($row = sqlsrv_fetch_array($stmt)){
echo "<tr><td>" . $row['data1'] . "</td><td>" . $row['data2'] . "</td></tr>";
}
echo "</table>";
So if you have no data, the table will be empty.
You'll only get the table and table headers... But no row.
There is then no need for a function that checks if there is data or not.
Finally... About the trigger to refresh:
In application.php, you may place a button that fires getData()... Or you may define a setInterval.
It's up to you.
This is how I use ajax to refresh part of a page without reloading it completly.
Since ajax is new to you, I hope this answer will help.
;)
------------------------
EDIT based on Ariel's comment (2016-05-01)
Okay, I understand! Try this:
In application.php:
<div id="dynamicDiv"></div>
<script type="text/javascript">
// timer to trigger the function every seconds
var checkInterval = setInterval(function(){
checkTicket();
},1000);
function checkTicket(){
$.ajax({
type: "POST",
url: "function.php",
data: "",
cache: true,
success: function(html){
$("#dynamicDiv").html(html);
}
});
}
function noMoreTikets(){
clearInterval(checkInterval);
window.location.replace("http://www.google.com");
}
</script>
In function.php:
// Remove the "function is_ticket_able($conn){" function wrapper.
// Define $conn... Or include the file where it is defined.
// I assume that your query lookup works.
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
// Add this instead of a return.
if($ticket>0){
echo "There is still some tickets!"; // Text that will show in "dynamicDiv"
}else{
?>
<script>
$(document).ready(function(){
noMoreTikets();
});
</script>
<?php
}
Remember that your PHP scripts are executed server-side.
That is why your "return $ticket;" wasn't doing anything.
In this ajax way to call function.php, its script is executed alone, like a single page, without any relation with application.php, which was executed long ago.
It produces text (or javascript) to be served to the client.
If you want to pass a PHP variable to the client-side javascript, you have to echo it as javascript.
So here, if the PHP variable $ticket is more than zero, some text saying that there is still tickets available will show in "dynamicDiv" and the application page will not be refreshed. I suppose it shows a button or something that allows students to get a ticket.
Else, it will be the javascript trigger to "noMoreTikets()" that will land in the "dynamicDiv".

Ajax call for a a url freezes browser

I have a function in view used to transfer a value from a text box to a table displayed on a page. Basically it updates the URL and goes into a function called update_verified_phone(). There is another function which is used to update the records using a model named user_info_model() and uses controller named users_info().
Problem is when when I use an AJAX function to post to the controller function named update_verified_phone(), the browser freezes and hangs up. I was wondering why it is happening?
Sorry just new to AJAX.
Here is the code :
$(document).ready(function()
{
$('#btnVerify').click(function(event)
{
event.preventDefault();
var uid = $('#user_id').val();
var verified_phone = $('#textNum').val();
if (isNaN(verified_phone))
{
alert("Please enter only numbers for user verified_phone");
}
else
{
$('#textNum').val('');
//$.post(base_url+'users_info/update_verified_phone', {uid:user_id,verified_phone:textNum}, function(response)
//{
$.ajax
({
type: "POST",
url:base_url+'users_info/update_verified_phone',
data: {uid:user_id,verified_phone:textNum},
//async: true,
dataType: 'json',
success:function(data)
{
if(data)
{
var headingHtml = headingTemplate
({
'verified_phone':data[0].verified_phone,
'verified_timestamp':data[0].verified_time
});
$('.userinfo').html(headingHtml);
$('.userinfo tr td:eq(4)').html(data[0].verified_phone);
$('.userinfo tr td:eq(5)').html(data[0].verified_time);
}
}
});
}
});
});
I think you missed to specify JS variable base_url correct it out. After that once you check your AJAX request URL response by direct hit from browser address bar and check what if issue is there OR not.
Let me know if you require any more information regarding this.
Thanks!
This is pretty difficult but I try to solve it.
Query 1: Insert query with SELECT statement
//If history_verified_phone:id is auto incremental then no need to cover it into INSERT statement so removed.
$instVerified = "INSERT INTO history_verified_phone(lastverified_phone,lastverified_time,verified_phone,verified_time)
SELECT users.verified_phone,users.verified_time,'". $textNum ."',NOW() FROM users WHERE id = '". $user_id ."'";
Query 2: Update query
$updtUser = "UPDATE users SET verified_phone = '" . $textNum . "', verified_time = NOW() WHERE id = '" . $user_id . "'";
Query 3: Select query
$selUser = "SELECT verified_phone,verified_time from users WHERE id = '" . $user_id . "'";
Please replace variable with your query, $instVerified for Query 1, $updtUser for Query 2 and $selUser for Query 3 and after that please check what happen. Because I have some doubt with your given query may failed and that is the reason for issue.
Please let me know what is outcomes here.

Select2 filter not working

I use Select2 to handle my dropdownmenu.
The dropdownmenu get's populated via "Ajax-call" to PHP, who get's data from Mysql.
The Select2 dropdownmenu offers serach function and filtering.
When i type in something in the search field, the letters get underlined, but the filter doesn't work.
So the list won't get filtered by the letters i type in. Why?
JS:
$(document).ready(function(){
$("#test").select2({
placeholder: "test",
minimumInputLength: 1,
ajax: {
url: "test.php",
dataType: 'json',
//search term
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
return { results: data};
} //End of results
}, //End of Ajax
}); //End of select2
The filtering must be done in server-side.
This PHP script will make the filtering work.
PHP:
<?php
// setup databse connection
require_once('db.php');
// Select from database, i have set the limit to 40 to speed up results
$result = $db->prepare("SELECT * FROM table WHERE option LIKE :term ORDER BY option ASC LIMIT 0,40");
// bind the value for security with the wildcard % attached.
$result->bindvalue(':term','%'.$_GET["q"].'%',PDO::PARAM_STR);
$result->execute();
// make sure there are some results else a null query will be returned
if($result->rowcount() != 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$answer[] = array(
"id"=>$row['option_id'],
"text"=>$row['option']);
// the text I want to show is in the form of option
}
} else {
// 0 results send a message back to say so.
$answer[] = array("id"=>"0","text"=>"No Results Found..");
}
// finally encode the answer to json and send back the result.
echo json_encode($answer);

Categories

Resources