Calling a jQuery function from a PHP file - javascript

I am having problems trying to activate a jQuery function from a PHP.
The following is my own test version.
index.php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to temp index</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.8.3.min[2].js"></script>
<script type="text/javascript">
$(document).ready(function() {
//posts info into the userinfo.php file
$.post('userinfo.php', { activate:"colourchange"}, function(data){
$('report').html(data);
});
//the function which is meant to be activated from the php file
function colourchange(){
document.body.style.backgroundColor = 'green';
};
});
</script>
</head>
<body>
<h1>hello</h1>
<div id="report">
</div>
</body>
</html>
PHP file I am attempting to call my jQuery function from
<?php
if( $_REQUEST["activate"])
{
$activate = $_REQUEST['activate'];
};
if($activate == 'colourchange')
{
// This is the code that I believe not to be working as this isn't
// activating the jQuery function to work. (The page background isn't changing colour)
echo "<script>colourchange(); </script>";
};
?>
Thank you to anyone who has an idea of what to do it is much appreciated.
I have now tried ...
<?php
require 'userinfo.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to temp index</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.8.3.min[2].js"></script>
<script type="text/javascript">
function colourchange(){
document.body.style.backgroundColor = 'green';
};
$(document).ready(function() {
$.post('userinfo.php', { activate:"colourchange"}, function(data){
$('report').html(data);
});
});
</script>
</head>
<body>
<h1>hello</h1>
<div id="report">
</div>
</body>
</html>
and the PHP index file is ...
<?php
if( $_REQUEST["activate"])
{
$activate = $_REQUEST['activate'];
};
if($activate=='colourchange')
{
echo "colourchange();";
};
?>

I don't exactly understand why you are using PHP to execute a jQuery function at all - perhaps this is just an oversimplified example. Assuming your primary goal is to have the PHP response trigger a specific Javascript function (and perhaps allow for the PHP response to trigger several different responses) you'd do something like this:
First change the callback from
function(data){
$('report').html(data);
}
to something like:
function(data) {
if (data.indexOf("colourchange") >= 0) { // php page returned "colorchange" or a string containing "colourchange"
colourchange();
} else if (data.indexOf("moodchange") >= 0) {
moodchange(); /// etc... you can add more trigger functions here
}
}
And second... just have your PHP page return "colourchange" instead of an HTML snippet:
if($activate == 'colourchange')
{
echo "colourchange";
};
Does that help?

you could try this-- example call the jquery function on success
$.ajax({
url: //the url,
data: //the data,
type: "POST",
success: function(data){
if(data == "ok"){
colorChange();
}
}
});
here the data will be the success result returned by the php code..
you can call a function depending on the data returned

Related

how to use ajax to put value from javascript variable into a php variable

I need to get the value of a javascript variable and put it into a mysql database. I am trying to use jquery ajax function in (test.html) to Post the variable to a separate PHP file (external.php). I'm not sure why it's not working, I would appreciate any insight. Here are my two files:
Here is test.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
data: { "longitude": longitude }
});
});
</script>
</body>
</html>
And here is external.php:
<?php
$longitude = $_POST['longitude'];
echo json_encode($longitude);
?>
The code below works perfectly fine for me:
The external.php file:
<?php
header('Content-Type: application/json');
$longitude = $_POST['longitude'];
echo json_encode($longitude);
?>
The test.html file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
dataType: "json",
data: { "longitude": longitude },
success: function(data){
console.log(data);
}
});
});
</script>
</body>
</html>
Also, make sure you are not running your file as:
file:///C:/Users/XXX/Desktop/XAMPP/htdocs/test.html
If you run it like this you would get this error:
XML Parsing Error: no root element found
Location: file:///C:/Users/XXX/Desktop/XAMPP/htdocs/external.php
Line Number 5, Column 3:
What you need to do is run Apache and then run the file as:
http://localhost/test.html
Below is the screenshot of what I get:

How to send DELETE request to node with button and jquery?

I have a web page that's showing a "ressource" (aka just one entry from a mongodb collection), and on that web page I want to have a button "delete" that will send a "delete" request to the server to the correct route.
The router works (so when I use an external program to send a delete request, the entry is deleted), but I want to the same with a link.
Apparently, after doing some research, I would need to use an ajax function to do that, as in this post. The problem is that I can't make it work (probably because I just started using jquery), it seems nothing happens when I click on the button. But if I try a simple alert(), it works ('#delete').on('click',function(){ alert('clicked')}); .
So
Here's the basic html :
$('#delete').on('click', function() {
alert('click');
//here would be the code to send the DELETE request ?
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Storystrap Template</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- bower:css -->
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css" />
<!--endbower-->
<!-- bower:js -->
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/printplugin.min.js"></script>
<!--inject:js-->
<script src="/js/app.js"></script>
<script src="/js/modernizr-custom-touch.js"></script>
</head>
<body>
<button class="delete" data-target="/" data-method="DELETE" data-disabled="true">Delete Ressource</button>
</body>
</html>
And here is the route code in node.js (this code works if I manually send a DELETE request), the id is supposed to be in the link of the page
ressourcesRouter.route('/ressources/t/:ressourcesId')
// permet d'afficher UNE ressource spécifique
.get(function(req,res){
var returnRessource = req.ressource.toJSON();
res.render('ressourceView', {
title: 'Ressources',
ressource: returnRessource
});
})
.delete(function(req,res){
req.ressource.remove(function(err){
if(err)
res.status(500).send(err);
else{
res.status(204).send('Removed');
console.log('ressource supprimée');
}
});
});
Could you help me out to figure the ajax code needed ? or is there another way ?
Don't hesitate to ask for more code if needed, I'll be as reactive as possible to answer you quickly.
Best regards.
Take a look at the jQuery ajax docs: http://api.jquery.com/jquery.ajax/
$.ajax({
url: '/ressources/t/123',
method: 'DELETE',
data: yourdata
})
.done(function( data ) {
console.log(data);
});
<script type="text/javascript">
$(document).ready(function(){
$('table#delTable td a.delete_link').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: '../scripts/delete_link.php',
data: 'link=' + $(this).attr('data_link') + '&topic_pk=' + $(this).attr('data_topic') + '&topic_introduction=' + $(this).attr('data_introduction'),
cache: false,
success: function()
{
parent.fadeOut('fast', function() {$(this).remove();});
}
});
}
});
});
</script> just look at this. it can solution your problem. Dont Forget your datatable's name

AJAX returns random hash instead of text

I am working on live notification script.
I have managed to rend request to external file, but the script returns random hash instead of plain text...
This is my function that should get data from test.php
<script>
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "/test.php",
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").append(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
// $("#display").click(load); //if you want to start the display on click
});
</script>
And it should append to the results.
This is the source of test.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Headerview</title>
</head>
<body>
<?php
$p = "<p>test</p>";
echo $p;
?>
</body>
</html>
And this is what I am getting...
inGN^PtJRo(hi*I1HVb&pB0wJs(B)9rID*6O�Eyh6cngWD+93Zr$zYU
The file path was the problem. I did not specify exact file path.
Thank you

Random string picker only execute once per page load

When you press the link text it is supposed to give you an random string from a file, which it does on first click. But second click nothing happens, I need to refresh page before execute it again..
Code:
function randomName() {
$names = file('layout/sub/names.txt', FILE_IGNORE_NEW_LINES);
$array = array_rand($names);
return $names[array_rand($names)];
}
<div class="randomName">
</div>
<button class="aardvark">Pick random name</button>
<script>
$(document).on('click','.aardvark', function(e){
$('.randomName').html('<?php echo randomName(); ?>');
});
</script>
The issue is the age old PHP is server side and and javascript(jQuery) is client side problem, you cant call/run PHP from javascript as its already happened.
You will need to use AJAX to re-request a new name. Here is a copy and paste example, your welcome ;p
<?php
//is ajax
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is get name
if(isset($_POST['get_name'])){
$names = file('names.txt', FILE_IGNORE_NEW_LINES);
exit(json_encode(array('resp' => $names[array_rand($names)])));
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
//get_name function
$.fn.get_name = function(){
var elm = $(this);
var ajax = $.ajax({
url: "./",
type: "POST",
data: {'get_name':true},
dataType: "json"
});
ajax.done(function(data){
elm.html(data.resp);
});
ajax.fail(function(xhr, status, error){
elm.html("AJAX failed:" + xhr.responseText);
});
return this;
};
//do get_name on page load
$('#randomName').get_name();
//do get_name on button click
$('#aardvark').on('click', function(){
$('#randomName').get_name();
});
});
</script>
</head>
<body>
<div id="randomName"></div>
<button id="aardvark">Pick random name</button>
</body>
</html>

How to get csv from url and transform it in array

I'd like to get a csv file from a url and transform it into an array.
So here is my code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Temperatures</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.csv-0.71.js"></script>
<script type="text/javascript" src="jquery.csv-0.71.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['annotatedtimeline']});
var csv_as_array = [];
function drawVisualization() {
$.ajax({
url: "data.txt",
aync: false,
success: function (csvd) {
csv_as_array = $.csv2Array(csvd);
},
dataType: "text",
complete: function () {
// use the array of arrays (variable csv_as_array)
// for further processing
}
});
[Google chart code]
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 1000px; height: 600px;"></div>
</body>
</html>
my data.txt is in the same folder as my .html file.
I know the block success: function (csvd) { } is not executed, because when I write alert("toto");, nothing happens.
Also, in the block complete: function () { }, I have written alert(csv_as_array.length); and it always shows 0.
The error is maybe just an import of a library missing ?
If success callback function was not called, it means error happened and error callback function would be called, if there would be one. You can try:
Adding error function, for example, a line like this error: function(jqXHR, textStatus, httpError) { alert('Error: '+textStatus); alert(httpError); }, to check for error.
Using absolute address in url
And you have a typo in the line aync: false - async, not aync.

Categories