getJSON callback not happening - javascript

I have looked at similar queries here, but I can't seem to apply them to my problem. I am pretty new to jquery, so I may be doing something dumb.
I have a simple getJSON test:
$(document).ready(function() {
$(".testurl").click(function() {
// do a json call
var url="testjson.php";
var rc=$.getJSON(
url,
{parm1: "P1", parm2: "P2", parm3: "P3"},
function(data){
alert("callback function inline");
});
var x = 1;
});
});
that calls a really simple script:
header("Content-Type: application/json");
echo "{\"results\": [";
$arr = array();
$arr[] = "{\"fld1\": \"result1\", \"fld2\": \"result2\", \"fld3\": \"result3\"}";
echo implode(", ", $arr);
echo "]}";
that returns valid JSON (I checked on JSON lint)
The var rc that I use to receive the result of the request has the following values:
getResponseText \"{\"results\": [{\"fld1\": \"result1\", \"fld2\": \"result2\", \"fld3\": \"result3\"}]}\""
getReadyState 4
getStatus 200
Why does the callback function not fire?

If the click handler is attached to an anchor element then maybe the ajax call doesn't have time to execute before redirecting to a different page. Try adding a return false to the click callback:
$(".testurl").click(function() {
// do a json call
// ...
return false;
});

The $.getJSON call is just assigned to a variable, it is not being called.

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.

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)

Passing values from jQuery to PHP in same page instantly

I have written a PHP program to confirm deletion of data through jQuery confirm message (Refer: http://rathur.fr/jQuery/MsgBox/) and record the result back to the same page itself instantly. If the page refreshes, it'll return back its state to previous.
The part of line is below:
print "
<script type='text/javascript'>
$(document).ready(function(){
$.msgbox('<br/>Are you sure you want to delete the selected record from the database?', {
type : 'confirm'
}, function(result){
$('#output').text(result);
var output = result;
});
});
</script>";
I want to get the result of the action button to PHP variable instantly, like below (just a trial):
$x = $_SESSION['output']; OR
$x = $_POST['output']; OR
$x = print "<div id=\"output\"></div>"; OR
$x = some_function(output);
Please help me, or suggest if there is other better options.
Here is a simple Ajax call to a Php File by an event : Click on a button.
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#action").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
You should use jQuery to POST the data to a PHP script using AJAX if you want to use the second pass.
http://api.jquery.com/category/ajax/ has many functions and tutorials on writing AJAX functions and handling return data. In particular, look at the post() function.

Set a delay in a repeating jQuery / Ajax function

I am trying to add a delay to a repeatable query.
I found out that .delay is not the one to use here. Instead, I should go with setInterval or setTimeout. I tried both, without any luck.
Here's my code:
<?php
include("includes/dbconf.php");
$strSQL = mysql_query("SELECT workerID FROM workers ORDER BY workerID ASC");
while($row = mysql_fetch_assoc($strSQL)) {
?>
<script id="source" language="javascript" type="text/javascript">
$(setInterval(function ()
{
$.ajax({
cache: false,
url: 'ajax2.php',
data: "workerID=<?=$row['workerID'];?>",
dataType: 'json',
success: function(data)
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
}),800);
</script>
<?php
}
?>
<div id="output"></div>
The code works fine, it outputs the result as asked. It's just loads without the delay. The timout and / or interval doesn't seem to work.
Anybody knows what I am doing wrong?
I've never understood why people always add their AJAX requests in intervals rather than letting the successful AJAX calls just call themselves, all the while risking severe server load through multiple requests and not just making another call once you had a successful one come back.
In this light, I like to write solutions where the AJAX calls just call themselves on completion, something like:
// set your delay here, 2 seconds as an example...
var my_delay = 2000;
// call your ajax function when the document is ready...
$(function() {
callAjax();
});
// function that processes your ajax calls...
function callAjax() {
$.ajax({
// ajax parameters here...
// ...
success: function() {
setTimeout(callAjax, my_delay);
}
});
}
I hope this makes sense! :)
Update:
After reviewing this again, it's been brought to my attention that there was also a problem in the PHP code in the original question that I needed to clarify and address.
Although the script above will work great in creating a delay between AJAX calls, when added to the PHP code in the original post the script will just be echo'd out as many times as the number of rows the SQL query selects, creating multiple functions with the same name and possibly making all AJAX calls simultaneously...not very cool at all...
With that in mind, I propose the following additional solution - create an array with the PHP script that may be digested by the JavaScript one element at a time to achieve the desired result. First, the PHP to build the JavaScript array string...
<?php
include("includes/configuratie.php");
$strSQL = mysql_query("SELECT workerID FROM tWorkers ORDER BY workerID ASC");
// build the array for the JavaScript, needs to be a string...
$javascript_array = '[';
$delimiter = '';
while($row = mysql_fetch_assoc($strSQL))
{
$javascript_array .= $delimiter . '"'. $row['workerID'] .'"'; // with quotes
$delimiter = ',';
}
$javascript_array .= ']';
// should create an array string, something like:
// ["1","2","3"]
?>
Next, the JavaScript to digest and process the array we just created...
// set your delay here, 2 seconds as an example...
var my_delay = 2000;
// add your JavaScript array here too...
var my_row_ids = <?php echo $javascript_array; ?>;
// call your ajax function when the document is ready...
$(function() {
callAjax();
});
// function that processes your ajax calls...
function callAjax() {
// check to see if there are id's remaining...
if (my_row_ids.length > 0)
{
// get the next id, and remove it from the array...
var next_id = my_row_ids[0];
my_row_ids.shift();
$.ajax({
cache : false,
url : 'ajax2.php',
data : "workerID=" + next_id, // next ID here!
dataType : 'json',
success : function(data) {
// do necessary things here...
// call your AJAX function again, with delay...
setTimeout(callAjax, my_delay);
}
});
}
}
Note: Chris Kempen's answer (above) is better. Please use that one. He uses this technique inside the AJAX routine. See this answer for why using setTimeout is preferable over setInterval.
//Global var
is_expired = 0;
$(function (){
var timer = setInterval(doAjax, 800);
//At some point in future, you may wish to stop this repeating command, thus:
if (is_expired > 0) {
clearInterval(timer);
}
}); //END document.ready
function doAjax() {
$.ajax({
cache: false,
url: 'ajax2.php',
data: "workerID=<?=$row['workerID'];?>",
dataType: 'json',
success: function(data) {
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
}); //END ajax code block
} //END fn doAjax()
I've devised a a wrapper method which adds a custom delay on-top of the default $.ajax method. This is a way to have (on all jQuery ajax calls) a delay, throughout your entire app.
Very handy in simulating real-life random latency.
(function(){
$._ajaxDelayBk = $.ajax; // save reference to the "real" ajax method
// override the method with a wrapper
$.ajax = function(){
var def = new $.Deferred(),
delay = typeof $.ajax.delay == 'undefined' ? 500 : $.ajax.delay,
delayTimeout,
args = arguments[0];
// set simulated delay (random) duration
delayTimeout = setTimeout(function(){
$._ajaxDelayBk(args)
.always(def.resolve)
.done(def.resolve)
.fail(def.reject)
}, delay);
def.abort = function(){
clearTimeout(delayTimeout);
};
return def;
}
})();
USE EXAMPLE:
// optional: set a random delay to all `ajax` calls (between 1s-5s)
$.ajax.delay = Math.floor(Math.random() * 5000) + 1000;
var myAjax = $.ajax({url:'http://whatever.com/API/1', timeout:5000})
.done(function(){ console.log('done', arguments) })
.fail(function(){ console.log('fail', arguments) })
.always(function(){ console.log('always', arguments) })
// Can abort the ajax call
// myAjax.abort();
var takeInput=true;
$('#searchDrug').on('input',function() {
if(!takeInput){return false;}
takeInput=false;
var timer = setTimeout(function() {
$.ajax({
type: 'POST',
url: "{{route('AjaxSearchDrug')}}",
data: {
_token: '<?php echo csrf_token() ?>',
'searchkeyword': searchkeyword,
},
success: function (data) {
//do some logic then let keys be effective once more
takeInput=true;
}
});
}, 700);

Categories

Resources