why $.ajax does not work with me? - javascript

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);

Related

send array from js to php

I'm doing some assignment for school, and I'm stuck at passing array from js to php.
I have to say I'm not some expert and I'm still learning. I can't figure out what am I missing. Hope someone will help me.
I try like this.
if(bets.length > 0) {
$.ajax({
url: "mybet.php",
method: "POST",
data: { bets : JSON.stringify( bets ) },
success: function(res) {
console.log(res);
}
});
}
and php file
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($bets);
}
bets is an array in js.. and I want if I click on button proceed to collect that array and pass to php so I can work with it. I'm getting undefined index for bets on line $bets = json_decode($_POST['bets']);
print_r($_POST) is empty
You are not sending a 'proceedBet' variable in your ajax request, either you send that variable by changing the data like this:
if(bets.length > 0) {
$.ajax({
url: "mybet.php",
method: "POST",
data: { bets : JSON.stringify( bets ), proceedBet: 'Some Value' },
success: function(res) {
console.log(res);
}
});
}
Or you have to change your condition to check if the bets exist like so:
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($_POST['bets']); // use print_r to check the data in the array
// User::redirect("ticket.php");
}
Hi here is an example I made for you:
first the html part is a simple modal to display data from request.php if the data I send from my js array is okay:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" id="btnDisplayModal" >
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal" >×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<br>
<div id="add-takeout-messages">
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
the javascript part is an ajax call which display data inside the modal when the request is done:
$(document).ready(function() {
var formData = {id:"1",name:"stan",lastname:"chacon",color:"blue"};
function _ajaxMessage(formData){
return $.ajax({
url: "request.php",
type: 'POST',
data:{data:JSON.stringify(formData)},
dataType: 'json'
})
}
$("#btnDisplayModal").on('click', function(){
_ajaxMessage(formData)
.done(function(response){
console.log(JSON.stringify(response));
$('#add-takeout-messages').empty();
$.each(response.messages,function(index,value){
console.log(index,value);
$('#add-takeout-messages').append('<div class="alert alert-success">' +
'<button type="button" class="close" data-dismiss="alert">×</button>' +
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> From: '+ value.from + '<br>' + ' msg: ' + value.msg +
'</div>')
})
$("#myModal").modal();
})
})
})
The request.php file is simple like the request file you are already using, so I guess the problem you have is your array, maybe it has an invalid format and thats why it goes empty.
if (isset($_POST["data"])) {
$data = json_decode($_POST["data"],true);
if ($data["name"] == "stan") {
$array = [
"status"=>"success",
"messages"=> [
array('date' => "2019-04-11", 'msg'=>'Love you', 'from'=>'Annie' ),
array('date' => "2019-04-10", 'msg'=>'Have a nice day', 'from'=>'Annie' )
]
];
echo json_encode($array);
}
}
check your array ant let us know if that was the problem =)
Hiope it helps
Simple working example you can change the logic if needed.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
let bets = [1,2,3]; // This must come dynamically.
if(bets.length > 0) {
$.ajax({url: "server.php", method: "POST", data: { bets : JSON.stringify( bets) }, success: function(result){
$("#div1").html(result);
}});
}
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Send Ajax Request</button>
</body>
</html>
Server side
<?php
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($_POST['bets']);
}

Triggering a Rest API call with a JQuery Mobile button

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!

Edit JSON file with a use of AJAX

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().

Uncaught SyntaxError: Unexpected token < ajax call jsonp

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.

Can't Get Data for Simple Login with HTML to PHP Web Service

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

Categories