I tried to do that when I'm pressing the turn on button it calls the turnon() function which opens the JSON file named light.json and writes there {"light" : "on"} but it doesn't work for me and I don't know why. Can anybody help me?
<?php
$light = $_GET['light'];
$file = fopen("light.json", "w") or die("can't open file");
if($light == "on") {
fwrite($file, '{"light": "on"}');
}
else if ($light == "off") {
fwrite($file, '{"light": "off"}');
}
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LED for ESP8266</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
</head>
<body>
<div class="row" style="margin-top: 20px;">
<div class="col-md-8 col-md-offset-2">
<form>
<input type="button" id="StartButton" value="Turn On" onClick="turnOn()">
</form>
<!--<button onclick="turnOn()">Turn On</button>
<button onclick="turnOff()">Turn Off</button>-->
<div class="light-status well" style="margin-top: 5px; text-align:center">
<script type="text/javascript">
function turnOn() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://192.168.1.108/test/light.json",
data: {"light": "on"},
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
}
</script>
</div>
</div>
</div>
</body>
</html>
Thanks!
You use POST method to send AJAX request, but try to get it by using GET method from PHP.
Simply change AJAX method from POST to GET can solve the problem.
You are sending an AJAX request directly to light.json instead of PHP page. Moreover you're using type: "POST" on AJAX but reading from $_GET on PHP.
If the PHP script is on the same page, you won't need to specify url in your AJAX request
<?php
if (isset($_GET['light'])) {
$light = $_GET['light'];
$file = fopen("light.json", "w") or die("can't open file");
if($light == "on") {
fwrite($file, '{"light": "on"}');
} else if ($light == "off") {
fwrite($file, '{"light": "off"}');
}
echo fread($file, filesize($file));
}
?>
$.ajax({
type: "GET",
data: {"light": "on"},
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
Be sure that light.json is in the same directory, otherwise specify the correct path on fopen().
Related
This is simple but my JS is a bit rusty..
I am trying to trigger a get request by pressing a JQuery Mobile element.
I can see the button but failing to do an actual Get Request
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<p><input type="checkbox" data-role="flipswitch" name="flip-checkbox-1" id="generator_button"></p>
</form>
</body>
<script>
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
</script>
Please, note: in your markup there is a Flip switch of type checkbox, not a button, so I believe you may better check the state of the underlying checkbox instead of stick to a tap event.
Reference: jQuery Mobile Flip switch
Moreover, you it would be nice to provide a JQM page structure to the whole stuff.
Here is an example:
function sendRequest() {
$.ajax({
'url': '192.168.8.110:5000/generator_on',
'type': 'GET',
'success': function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
}
$(document).on("change", "#generator_button", function() {
var state = $("#generator_button").prop("checked");
if (state === true) {
// Flip switch is on
console.log("Request sent.");
//sendRequest(); // uncomment
} else {
// Flip switch is off
//...endpoint _off
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="page-one" data-role="page">
<div data-role="header" data-position="fixed">
<h1>Header</h1>
</div>
<div role="main" class="ui-content">
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<input type="checkbox" data-role="flipswitch" name="generator_button" id="generator_button">
</div>
<div data-role="footer" data-position="fixed">
<h1>Footer</h1>
</div>
</div>
</body>
</html>
You are missing }); on last line of your javascript.
Your javascript code should look like this
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
});
Ok, so I had to change the url to: 'http://192.168.8.110:5000/generator_on and tested it on a browser without an adblock I mentioned to make it work!
As the title states, getting this error in Chrome remote debugging. I am trying to send an ajax request (jsonp) to my .php file in localhost which will then do something to the database using the URL in the QR Code after a QR code is scanned. However, I am getting this error.
I am aware that jsonp is different from json and uses different syntax, however the code I am using worked for other ajax calls. I am unable to figure out the problem, and would appreciate some help.
Here are the codes:
.html file
<!DOCTYPE html>
<html>
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<title></title>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header">
<h1></h1>
</div>
<div data-role="main" class="ui-content">
<p>
<a target="_blank" href="javascript:scan();" style="text-decoration: none"><button>Scan</button></a>
</p>
</div>
</div>
<div data-role="page" id="display">
<div data-role="header">
<h1>Display</h1>
</div>
<div data-role="main" class="ui-content">
<table data-role="table" data-mode="column" id="allTable" class="ui-responsive table-stroke">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type= "text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script>
function scan()
{
cordova.plugins.barcodeScanner.scan(
function (result) {
if(!result.cancelled)
{
if(result.format == "QR_CODE")
{
var value = result.text;
$.ajax({
type: "GET",
url: value + '?callback=?',
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
if (response == "Success")
{
alert(response);
}
else
{
alert(response);
}
}
});
}
}
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
</script>
</body>
</html>
.php file
<?php
header('Content-Type: application/json');
require 'dbcon.php';
session_start();
$acc_points = $_SESSION["acc_points"];
$acc_id = $_SESSION["acc_id"];
$result = $con->prepare(" UPDATE `points` SET `acc_points` = acc_points+1 WHERE `acc_id` = ? ");
$result->bind_param("i", $acc_id);
$result->execute();
if($acc_points != null)
{
$response = "Success";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "Failed. Please try again.";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>
Error was:
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Duplicate entry '12' for key 'PRIMARY'' in C:\xampp\htdocs\MP\appqrcode.php:14 Stack trace: #0 C:\xampp\htdocs\MP\appqrcode.php(14): mysqli_stmt->execute() #1 {main} thrown in C:\xampp\htdocs\MP\appqrcode.php on line 14
Solved the problem by changing the primary key of the table.
I try to do a submit ajax with ASP .net and jquery but he never fire d«the event, I already try with this two examples and he never fire the event alert.
<form id="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m.VatNumber,new { #class = "form-control", #id="VatNumber"})
#Html.ValidationMessage("VatNumber")
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Check VAT" />
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#form').submit(function () {
alert("cheguei");
$.ajax({
url: '#Url.Action("CheckVat")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
VatNumber: $('#VatNumber').val(),
}),
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
return false;
});
});
$(function () {
$('#form').submit(function (event) {
alert("cheguei");
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function (data) {
// Optionally alert the user of success here...
}).fail(function (data) {
// Optionally alert the user of an error here...
});
});
});
</script>
I figure out : I have to include the scripts in the Head section and the problem is fixed.
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/bootstrap.min.css")
#*#Styles.Render("~/Content/css")*#
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-3.1.0.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</head>
i don't know why $.ajax never called on my code ?
i use xampp as localhost
jquery called ok , so when i click on the button , the text below it changed .. but $.ajax part never execute ?
my page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script type="text/javascript" src="layout/js/jquery-1.12.4.min.js">
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
my js :
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
and my moremore.php :
<div class="alert alert-success"> alerts alerts by ajax </div>
1) Look for console.log errors or errors in network header
2) Make sure you .php script where you are requesting the ajax, has major headers to allow access control.
3) Sometimes, the headers doesn't allow to make you request.
4) When making request, keep your console opened (F12) and enable Log XMLhttpRequest
Try adding these headers to you moremore.php
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
header("Access-Control-Allow-Origin: http://localhost");
Also to give it a try, check the ajax request with the ajax header, add this too in your moremore.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo '<div class="alert alert-success"> alerts alerts by ajax </div>';
} else {
echo 'no ajax';
}
This will give you an idea if ajax request is working fine or not.
New ajax js:
$(document).ready(function() {
$('#btn').click(function() {
var ID = $(this).attr('id');
$(this).html("Loading ... ");
$.ajax({
type: "POST",
url: "http://localhost/my_projects/testing/moremore.php",
data: {
id: ID
},
cache: false,
xhrFields: {
withCredentials: true
},
dataType: html,
success: function(html) {
$('.container').append(html);
$('#btn').html("done");
},
error: function() {
alert("Something went wrong");
$("#btn").html("hmmmm, it was called... ");
}
});
});
});
Do leave comments for more help!
I tested your code, and it pretty much works as is. The only thing that I changed was the ajax url from absolute http://localhost/my_projects/testing/moremore.php to relative moremore.php and I threw in the official jQuery CDN in case yours was borked.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="http://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script>
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
moremore.php:
<div class="alert alert-success"> alerts alerts by ajax </div>
Results in this expected output after a couple clicks:
Try to wrap anonymous function, and change selector document to '#btn'
(function($) {
$('#btn').on('click',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
})(jQuery);
I try to access login service from some web service for user validation directly to html page using jquery, but it seems not working, even when I access the web service with browser the web service work perfectly. Here is the html code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script type="text/javascript">
$("#login").click(function(){
var username=$("#username").val();
var password=$("#password").val();
var dataString="username="+username+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "some url here",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data.success=="true")
{
localStorage.login="true";
localStorage.username=username;
window.location.href = "index.html";
}
else if(data.success="false")
{
alert("Login error");
$("#login").html('Login');
}
}
});
} return false;
});
</script>
</head>
<body>
<div class="bar bar-header bar-positive" style="margin-bottom:80px;">
Home
<h1 class="title">Login</h1>
</div>
<br/><br/>
<input id="username" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="login">Login</button>
</body>
Even the "beforeSend" code is not working, I mean when I click on Login button the text on it doesn't change to Connecting. How can I make it work?
Replace
$.trim(email).length
To
$.trim(username).length
One more problem in code in success function;
/* Now */
}else if(data.success="false"){
/* should be == because here we are comparing not assigning */
}else if(data.success=="false"){
/* OR we can remove if part completely because we don't need any comparison if not success */
}else{
One more thing if we are getting the response as true or false i don't thing it would be string value, it would be Boolean so update code for success function like following:
success: function(data){
if(data.success){
localStorage.login = "true";
localStorage.username = username;
window.location.href = "index.html";
}else{
alert("Login error");
$("#login").html('Login');
}
}
And one more problem your code won't execute because here you are trying to reference element that not loaded that is login button;
Use following code with all fixes;
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script type="text/javascript">
/* code wrapped in $(function(){ to make sure the all elemtents loaded before we make use them */
$(function(){
$("#login").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var dataString = "username=" + username + "&password=" + password + "&login=";
if($.trim(password).length > 0 & $.trim(password).length > 0){
$.ajax({
type: "POST",
url: "some url here",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){
$("#login").html('Connecting...');
},
success: function(data){
if(data.success){
localStorage.login = "true";
localStorage.username = username;
window.location.href = "index.html";
}else{
alert("Login error");
$("#login").html('Login');
}
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="bar bar-header bar-positive" style="margin-bottom:80px;">
Home
<h1 class="title">Login</h1>
</div>
<br/><br/>
<input id="username" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="login">Login</button>
</body>
</html>
email is not defined before
$.trim(email)
Change it to and the connecting... will appear
$.trim(username)
change $.trim(email).length
To
$.trim(username).length