How to make a synchronous GET request in JavaScript? - javascript

JS code:
function saveCategories(i){
var categoriesList=JSON.parse(localStorage.getItem("categoriesList"));
var code=localStorage.getItem("gameCode");
if(i == categoriesList.length)
return;
var categoryName=categoriesList[i]['name'];
var items=categoriesList[i]['items'];
$.get('http://localhost:8080/yourfolder/newCategory.php',{GameCode:code,items:items,CategoryName:categoryName},function(resp)
{
saveCategories(i+1);
});
}
PHP code:
<?php
header("Access-Control-Allow-Origin");
$host="127.0.0.1";
$user="root";
$pass="password";
$databaseName="games";
$con=mysql_connect($host,$user,$pass,$databaseName);
if(!$con)
{
die("Connection failed: ".mysqli_connect_error());
}
$code=$_GET["GameCode"];
$name=$_GET["CategoryName"];
$items=$_GET["items"];
$data=array();
foreach($items as $item)
$data[]=addcslashes($item);
$data=implode(",",$data);
$sql="INSERT INTO games.categories(code,name,items) VALUES ('$code','$name','$data')";
$result=mysql_query($sql,$con);
echo $result;
?>
The php file (newCategory.php) should get code, category name and category items and insert them to MYSQL db.
The saveCategories recursive function should get the newCategory.php file for each category (in index i), but for some reason, it proceed to the next iteration without getting a result from the first GET request before.
The unwanted result is that the first category in index 0 is not saved in the MYSQL db.

use async: false in your data
example:
$.ajax({
url : "/your url",
type : "get",
async: false,
success : function(userStatus) {
//your logic
},
error: function() {
}
});

referring to this answer you can specify the asynchronous option to be false to get a synchronous Ajax request using jquery. You just need to specify
{async:false}
this article shows how to do it using a XMLHttpRequest().

Related

Javascript/jquery ajax request

I have a problem with this Ajax request, it causes error during the call, it is not shown in console nor compiler.
Javascript code:
jQuery(document).ready(function(){
jQuery.get({
url: "https://nonsoloalimentatori.it/tools/download-center/index.php?sku="+sku,
dataType: "jsonp",
cache: true,
success: function(){
console.log("success");
},
error: function(){
console.log("error");
}
}).done(function(){
console.log("here");
})
})
PHP:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials:');
header('Content-Type: application/json');
function searchJson($sku){
$array = [];
$json = file_get_contents('./list.json'); //read the file contente
$json_data = json_decode($json,true); //creating the json objectt
$n_elementi = count($json_data); //count the number of object element
for ($mul = 0; $mul < $n_elementi; ++$mul){ //for every element it is
searched the sku
if($json_data[$mul]["sku"] == $sku)//and it is compared to the sku
given by user
{
array_push($array,$json_data[$mul]);//if it is true the element
is added to array
}
}
return $array; //it is returned
}
if(isset($_GET['sku'])){
$result=searchJson($_GET['sku']);
echo json_encode($result, JSON_PRETTY_PRINT);
}
On jsonp response from the server side, jquery expects it to be under a callback function.
Please use the following code to output the server response:
$callback_function_name = !empty($_GET['callback'])? $_GET['callback'] : 'callback';
echo $callback_function_name.'('.json_encode($result, JSON_PRETTY_PRINT).')';
Reason for the callback function is: cross domain ajax call is not allowed in javascript, so in jsonp the url is loaded the way we load a js script file(you can add script from different domains in your site). The loaded script is then evaluated. If plain data is printed, it does nothing. So it is passed to a callback function registered by the caller JS to process.
You can set your own callback function too by setting:
jsonp : "custom_callback_function_name"
inside the ajax function as a parameter.
In that case your server side output should be like:
custom_callback_function_name({...json_data...});

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

Load php function in js file and use function

I have the following php function.
public function dateIndaysoff($mydate=false){
if(!$mydate)return false;
$host = "localhost";
$user = "user";
$pass = "pass";
$databaseName = "database";
$tableName = "table";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
// $db=JFactory::getDbo();
$dbs->setQuery("select date from table WHERE `date`='$mydate'")->query();
return (int) $db->loadResult();
}
This function searches an input value inside a database table column and if it finds then we have a TRUE, else FALSE.
So, i have a jquery inside .js file where i execute a specific action and i want to check if i have a TRUE or FALSE result. In jquery i use a variable called val. So inside jquery in some place i want to have something like this:
if (dateIndaysoff(val)) {something}
Any ideas?
Instead of wrapping the php code in a function you can wrap it in a if($_POST['checkDate']){//your code here}, then in javascript make an ajax request (http://www.w3schools.com/ajax/), which sends a parameter named checkDate and in the success block of the ajax call you can have your code you represented as {something}
function checkDate(){
$.post('yourPhpFile.php', {checkDate:$dateToBeChecked}, function(data){
if(data){alert("true")};
});
};
and the php:
if($_POST['checkDate']){
//your current function, $_POST['checkDate'] is the parameter sent from js
}
Just to work with your current code.
In your php file lets say datasource.php
echo dateIndaysoff()
In your requesting file lets say index.php
$.ajax({
url: "index.php",
context: document.body
}).done(function( data ) {
/* do whatever you want here */
});
You can do it with AJaX. Something like this:
A PHP file with all the functions you are using (functions.php):
function test($data) {
// ...
}
A JS to request the data:
function getTest() {
$.ajax('getTestByAJaX.php', {
"data": {"param1": "test"},
"success": function(data, status, xhr) {
}
});
}
getTestByAJaX.php. A PHP that gets the AJaX call and executes the PHP function.
require 'functions.php';
if (isset($_REQUEST["param1"])) {
echo test($_REQUEST["param1"]);
}
Ok if i got this right i have to do this:
1st) Create a .php file where i will insert my php function and above the function i will put this:
$mydate = $_POST['val'];
where $mydate is the result of the function as you can see from my first post and val is the variable i want to put in $mydate from ajax.
2nd) I will go inside .js file. Now here is the problem. Here i have a code like this:
jQuery(".datepicker").change(function() {
var val = jQuery(this).datepicker().val();
console.log(val);
if (dateIndaysoff(val)) {
console.log("hide");
jQuery('.chzn-drop li:nth-child(9)').hide();
jQuery('.chzn-drop li:nth-child(10)').hide();
} else {
console.log("show");
jQuery('.chzn-drop li:nth-child(9)').show();
jQuery('.chzn-drop li:nth-child(10)').show();
}
});
Inside this code, in the first if, i want to see if the variable val is inside my database table. So, how could i write correctly this jQuery with the Ajax you propose in order for this to work? Also please take a look maybe i have a mistake in my php function (in this function i want to connect with a database and take a TRUE if $myvalue is inside a table column)

Sql not setting value on UPDATE

I've been trying to update my orders table in my database using ajax. It seems as though my sql is not executing or there may be a problem with my syntax, I have checked and verified that the id variable I am passing through has been passed using POST and it successfully alerts when called upon in the javascript. The problem I am having is that my table is not updating.
my php here
if(isset($_POST['completed_id']) === true) {
$comp_id = $_POST['completed_id'];
include 'http://trecoolable.koding.io/res/res_php/conn.php'; //connection successful
$sql = "UPDATE resorder_tb SET res_complete = 1 WHERE res_id =".$comp_id; //not updating, checked and names are correct
echo $comp_id; //shows when echoed into my msg in javascript
}
javascript
$("#compacc_but").click(function(){
var completed_id = record_id;
$.ajax({
url: "http://trecoolable.koding.io/res/res_php/getOrder.php",
type: "POST",
data: {completed_id:completed_id}, ///passing correct values
success: function(msg)
{
alert(msg); //alerting properly
}
});
Are you executing the $sql statement?
Just change this code like below-
$sql = "UPDATE resorder_tb SET res_complete = 1 WHERE res_id =".$comp_id." ";
mysql_qyery($sql);

Categories

Resources