Call php script with php variables via JavaScript - javascript

I have a url that I can call with a userid, and it will update an SQL table. (e.g. domain.com/postback.php?userid=userid). That works fine manually, but not when trying to get JavaScript to call it. I've only just started learning JavaScript as of 3 days ago, so please forgive me if it's an easy one - but I can't see it.
I call the JS in question here:
<input type='button' id='countdw' value='Wait 30s' class='btn btngo disabled'>
<script>
var secsLeft = 30;
setInterval(function(){
secsLeft--;
if(secsLeft > 0){
$('#countdw').val('Wait ' + secsLeft + 's');
} else if(secsLeft == 0){
$('#countdw').removeClass('disabled');
$('#countdw').val('Go');
$('#countdw').attr("onclick","doSomething2()");
}
}, 1000);
Here is my JS. I've tried many different ways and this is just one of them.
<script type="text/javascript">
$(document).ready(function(){
function doSomething2(){
$.ajax
{ url: 'update.php',
data: { userid : userid },
type : 'GET',
dataType: 'json',
success : function ( jsXHR) {
},
failed : function(status,data){ }
}
);
}
});
</script>
<?php
$subid = $_GET['userid'];
?>
Here is the update.php script (I'm aware it's not mySql - yes I need a new book.) I just can't get the JS above to call it.
$uped = 1;
$subid = $_REQUEST['userid'];
mysql_query("UPDATE ".MYSQLTABLE." SET view=view+".$uped." WHERE userid='".$subid."'") or die(mysql_error());
mysql_close();
?>

This seems to be working for me.
function count() {
window.secsLeft--;
if (window.secsLeft > 0) {
$('#countdw').val('Wait ' + window.secsLeft + 's');
} else if (window.secsLeft === 0) {
$('#countdw').removeClass('disabled');
$('#countdw').val('Go');
$('#countdw').attr("onclick", "doSomething2()");
}
}
function doSomething2() {
$.ajax({
url: 'update.php',
data: {
userid: <?php echo $userid; ?>
},
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
(function () {
"use strict";
window.secsLeft = 30;
setInterval('count()', 1000);
}());
<input type="button" id="countdw" value='Wait 30s' class="btn btngo disabled">

Related

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

Difficulties using AJAX to pass input value to controller

I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}

Trying to pass POST from JavaScript to PHP

For a few days now I have been trying to pass a simple POST call to a php script from JavaScript. I've done countless amounts of searching online without any positive results.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function successHandler(location) {
var dataString = '?lat=' + location.coords.latitude + '&long=' + location.coords.longitude + '&accuracy=' + location.coords.accuracy;
alert(dataString);
if (location.coords.latitude == '0') {
} else {
alert("AJAX made");
$.ajax({
type: "POST",
url: "updatepos.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
setTimeout(navigator.geolocation.getCurrentPosition(successHandler),15000);
}
}
function getLocation() {
navigator.geolocation.getCurrentPosition(successHandler);
}
getLocation();
</script>
Above is my JavaScript file. The datastring gets made, and it alerts it out to my browser. No problem there. The problem is, my variables don't get passed to PHP whatsoever.
Here is the PHP that is in the same directory as the JavaScript.
<?php
include 'wp-load.php';
/*global $current_user;
get_currentuserinfo();
echo $current_user->user_login;*/
include('dbconnect.php');
global $current_user;
get_currentuserinfo();
$lat = $_POST['lat'];
$long = $_POST['long'];
$accuracy = $_POST['accuracy'];
/*$lat = $_GET['lat'];
$long = $_GET['long'];
$accuracy = $_GET['accuracy'];*/
$query = "UPDATE ltc_users SET lat='$lat',accuracy=$accuracy,lon='$long' WHERE name='$current_user->user_login'";
mysqli_query($GLOBALS['DB'],$query);
echo mysqli_error($GLOBALS['DB']);
echo $lat;
echo $long;
echo $accuracy;
echo $current_user->user_login;
?>
I may note that before the script would return mysql syntax errors as it was echoed in php due to missing variables. The syntax works if I use the $_GET method and just type in the data into my browser address bar for testing. It just doesn't get the JavaScript variables for whatever reason.
You're passing a string to jquery. When you do that, the string is sent out as-is by jquery. Since it's just a bare string, and not a key:value pair, there's no key for PHP to glom onto and populate $_POST with.
In fact, you shouldn't ever have to manually build a string of key:value pairs for ajax - jquery will take an array/object and do it all for you:
var stuff = {
lat : location.coords.latitude,
long : location.coords.longitude,
accuracy : location.coords.accuracy
}
$.ajax({
data: stuff
});
Here is your code combined with #Marc B
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > </script>
<script type="text/javascript">
function successHandler(location) {
if (location.coords.latitude == '0') {
} else {
alert("AJAX made ");
$.ajax({
type: "POST",
url: "updatepos.php",
data: {
"lat":location.coords.latitude,
"long":location.coords.longitude,
"accuracy":location.coords.accuracy
},
dataType: "json",
async:true,
cache: false,
success: function(html) {
alert(html);
},error: function(a,b,c){
console.log(a.responseText);
}
});
setTimeout(function(){navigator.geolocation.getCurrentPosition(successHandler);},15000);
}
}
function getLocation() {
navigator.geolocation.getCurrentPosition(successHandler);
}
$(function(){
getLocation();
});
</script>
code in jsfiddle http://jsfiddle.net/y7f1vkej/ it seems to be working for me

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}

Looping through AJAX and callbacks in jquery

I'm currently doing an AJAX call with jquery and callback functions to retrieve a result outside of the AJAX call and I am having trouble in attempting to use a loop to printout more data from my json file (ticker.json) provided here:
{
"test": {
"msgOne": [
"Remote One",
"Remote Two",
"Remote Three"
],
"msgTwo": "Remote2",
"msgThree": "Remote3"
}
}
My code is also below:
<html>
<head>
<title>Weather Data for Emergency Models</title>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
<script Language="JavaScript">
function hmm(callback) {
$.ajax({
url : 'ticker.json', // ___ |I want to loop this
dataType: 'json', // | |index as a variable
success: function(response) { // v
result = response['test']['msgOne'][2];
callback(result);
}
});
}
hmm(function(result) {
document.write(result); //currently outputs as "Remote Three"
});
</script>
</body>
</html>
The main problem is that I want to continue as asynchronous using the callback functions and loop through the "msgOne" array in the json file and print out all three results to the webpage sequentially. I have tried introducing a for-loop in multiple places previously, but I keep getting errors. I realize there are other ways to do this, but under the wanted conditions (asynchronous & callback functions because I want to eventually apply this to jsonp for json files found on multiple websites on a list), is there a way to do this? I ultimately want to modify the given code to deal with arrays and more complex code.
Try this -
do this in your success
success: function(response) {
callback(response);
}
and in your function
hmm(function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
});
});
Try this
Assuming response['test']['msgOne'] is an array
success: function(response) {
$.each(response['test']['msgOne'], callback);
}
hmm(function(i, result) {
document.write(result); //currently outputs as "Remote Three"
});
$.ajax({
url : 'ticker.json', // ___ |I want to loop this
dataType: 'json', // | |index as a variable
success: function(response) { // v
var result = response['test']['msgOne'];
$.each(result,callback ).
}
});
function callback(index ,data){
document.write(data);
}
This helped me iterate through div rows, pull their data-id atribute and retrieve data from an ajax call using that data id. There happened to be 40+ ajax calls to itterate through. I have to leave them async true but watterfall the calls so as not to overload the server. I also used PHP to retrieve cached data and converted the PHP cached array to a javascript object:
public static function load_footer_js_css() {
$screen = get_current_screen();
$whitelist = array('post','page');
if(!isset($screen) || !in_array($screen->post_type , $whitelist )) {
return;
}
$transient = get_transient( 'inbound_ga_post_list_cache' );
$js_array = json_encode($transient);
?>
<script type="text/javascript">
<?php
echo "var cache = JSON.parse('". $js_array . "');\n";
?>
function inbound_ga_listings_lookup( cache, post_ids, i , callback , response ) {
if (!post_ids[i]){
return true;
}
if (typeof response == 'object' && response ) {
jQuery('.td-col-impressions[data-post-id="' + post_id + '"]').text(response['impressions']['current']['90']);
jQuery('.td-col-visitors[data-post-id="' + post_id + '"]').text(response['visitors']['current']['90']);
jQuery('.td-col-actions[data-post-id="' + post_id + '"]').text(response['actions']['current']['90']);
}
if (i == 0) {
post_id = post_ids[0];
i++;
} else {
post_id = post_ids[i];
i++;
}
if (typeof cache[post_id] != 'undefined') {
jQuery( '.td-col-impressions[data-post-id="' + post_id + '"]').text( cache[post_id].impressions.current['<?php echo self::$range; ?>'] );
jQuery( '.td-col-visitors[data-post-id="' + post_id + '"]').text(cache[post_id].visitors.current['<?php echo self::$range; ?>']);
jQuery( '.td-col-actions[data-post-id="' + post_id + '"]').text(cache[post_id].actions.current['<?php echo self::$range; ?>']);
} else {
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'inbound_load_ga_stats',
post_id: post_id
},
dataType: 'json',
async: true,
timeout: 10000,
success: function (response) {
callback(cache, post_ids, i, callback , response);
},
error: function (request, status, err) {
response['totals'] = [];
response['totals']['impressions'] = 0;
response['totals']['visitors'] = 0;
response['totals']['actions'] = 0;
callback(cache, post_ids, i, callback , response);
}
});
}
}
jQuery(document).ready( function($) {
var post_ids = [];
var i = 0
jQuery( jQuery('.td-col-impressions').get() ).each( function( $ ) {
var post_id = jQuery(this).attr('data-post-id');
post_ids[i] = post_id;
i++;
});
inbound_ga_listings_lookup( cache, post_ids, 0 , inbound_ga_listings_lookup , null );
});
</script>
<?php
}

Categories