AJAX not working, updating database via JS - javascript

I've made game in phaser (JS library for games) and i now want to make the scoretable with JS/PHP. What interest me is to pass a variable from js to php to update the database. I've read many topics and all the answers lead to AJAX and this example:
function score_submitting() {
var var_data = "Hello World";
$.ajax({
url: "submit.php",
type: "GET",
data: { var_PHP_data: var_data },
});
}
But it's not working. Im sure that the function can be called, cause when I put alert there, it works. But with AJAX happens nothing. The file is in the middle, cause it comes from game:
(HTML)
(...)
<body>
<center>
<div id="gra">
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="create.js"></script>
<script type="text/javascript" src="update.js"></script>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript" src="jquery-3.2.1.js"></script>
</div>
</center>
</body>
(...)
Thanks for answers!

If you are using GET request you should make your request like that :
function score_submitting() {
var var_data = "Hello World";
$.ajax({
url: "submit.php?mydata="+var_data,
type: "GET"
});
}
Or you can use POST request if you don't want to pass your parameters in URL.

You can put success and error function for testing your code like following
you can also fetched data that is returned from ajax call as returnedData
function score_submitting() {
var var_data = "Hello World";
$.ajax({
url: "submit.php",
type: "GET",
data: { var_PHP_data: var_data },
success:function(returnedData)
{
alert('success');
},
error:function()
{
alert('Error');
},
});
}

Related

Ajax not able to post javascript variable to php

I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>

Not getting a response for an AJAX call to PHP (with JSON data)

I have a PHP running on a server, and i call to it via jQuery.Ajax() but it always return to the error portion of it.
If i call the PHP address directly from my browser, i get the response i need, it only breaks in the jQuery call.
The PHP (simply saying) is this:
<?php
if(isset($_GET['getcodenode']))
{
echo json_encode
(
array
(
'itens'=>
array
(
0=>array('id'=>100,'lb'=>'300','ds'=>'300 mm'),
1=>array('id'=>105,'lb'=>'400','ds'=>'400 mm')
)
)
);
die();
}
?>
And on the javascript side i call for it like this:
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>
How to read JSON objects from PHP and display in browser?
There are lots of comments on your code:
While you already getting a json return from server; you don't to parse that. Its already a json object.
You can set async:true to get a promise data
The way you loop through objects you need to do that properly. see image how to get the object path correctly.
You can use $ token instead of jQuery token; unless you purposely need that.
I am not sure if this is the best approach; but it give the needed result as explained in your question.
The code is bellow tested with some comments:
<script type="text/javascript">
loadcall("test");
// as pointed you need to call the function so it runs
function loadcall(data) {
$.ajax({
async: true,
method: 'POST',
crossDomain: true,
dataType: 'json', //your data type should be JSON not JSONP
url: 'page.php?getcodenode',
data: {
'arg': data
},
success: function(result) {
console.log(result);
// see attached image how to get the path for object
var ret = result;
var el = $('#abc');
for (en in ret.itens) {
console.log(ret.itens[en].ds);
el.append('<div id="item_' + ret.itens[en].id +
'">' + ret.itens[en].lb + ', ' + ret.itens[en].ds + '</div>');
}
},
error: function(result) {
console.log(result);
}
});
}
</script>
Open you developer tool in your browser hit F12 (In Chrome, Firefox or Edge):
Go to Console tab and find the results.
Expand the results tell you get to the object you need.
Right click and `copy property path'.
Use the object path as needed in your code.
you need to call loadcall(data)
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
loadcall('somethingData')
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>

Ajax Automatic Div Update w/out page refresh won't work

I am struggling to figure out why this is not working, but I would like it so that the information from load.php is placed in the div sample but if that code is updated (say if i was pulling information from a database), only the information included in load.php would refresh - not the entire page.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'load.php',
success:function(data){
$("#sample").html(data);
}
});
}
setInterval(callAjax,5000);
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id='sample'>100 </div>
</body>
</html>
I had a similar situation with my AJAX calls. I am not sure if your syntax is actually bad but here is how my Ajax call looks for a similar partial load.
var callAjax = function(){
$.ajax({
url: "load.php"
type: "GET",
async: true,
success: function (data) {
$("#sample").html(data);
}
});
}
};
setInterval(callAjax,5000);
I found that my Ajax started working once I added the async:true and made sure my controller was handling GET requests. I had previously forgotten that it was set to HTTPPOST only.
I hope this helps out. Not sure if it will.
cheers.
setInterval('someFunc()', 1000);
function someFunc()
{
$.ajax({
async: true,
type: "GET",
url: "www.domain.com/url",
data: data,
success: function (html) {
$("#myDiv").html(html);
}
});
}

Trigger successhandler from ajax call when someone clicks a button

I have an ajax call which grabs data from a php file that connects to an api. I have a success handler that receives the data from the ajax call and then loads a function from the API library. The issue is, I want the user to click a button and then run the function inside of the success call (using the same data from the ajax call earlier).
I believe my ajax call needs to stay inside the window.onload = function(), it doesn't work if I try to run the ajax call when the user clicks the button.
<html>
<head>
<title>hi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script>
function hello(){
alert("hi");
}
function successHandler(data){
screenleap.startSharing('DEFAULT', data, {
nativeDownloadStarting: hello
});
}
window.onload = function() {
$.ajax({
type: "POST",
url: "key.php",
data: '',
success: successHandler,
dataType: "json"
});
};
</script>
</head>
<body>
<input type="submit" value="submit" id="submit">
</body>
</html>
Please let me know how I can do this, any help would be greatly appreciated.
Update:
so I have tried adjusting my code, but for some reason nothing happens anymore when I click the button. It doesn't even shoot out my console.log confirming I had even clicked the button.
<html>
<head>
<title>hi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script>
var dataFromServer;
function hello(){
alert("hi");
}
function successHandler(data){
dataFromServer = data;
console.log("data from server: ")
console.log(dataFromServer);
}
window.onload = function() {
$.ajax({
type: "POST",
url: "key.php",
data: '',
success: successHandler,
dataType: "json"
});
};
$("#submit").click(function(){
console.log('clicked submit');
if(dataFromServer)
{
console.log(datafromserver);
screenleap.startSharing('DEFAULT', dataFromServer, {
nativeDownloadStarting: hello
});
}
});
</script>
</head>
<body>
<input type="submit" value="submit" id="submit">
</body>
</html>
all the best,
-- 24x7
You can store data to some global variable and on button click use same variable.
var dataFromServer;
function successHandler(data){
dataFromServer = data;
}
jQuery("#submit").click(function(){
if(dataFromServer)
{
screenleap.startSharing('DEFAULT', dataFromServer, {
nativeDownloadStarting: hello
});
}
});
Update:
Instead of window.onload use jquery onload function to populate data.
http://jsfiddle.net/ZGggK/
$(function() {
$.ajax({
type: "GET",
url: "https://api.github.com/users/mralexgray",
data: '',
success: successHandler,
dataType: "json"
});
});

jQuery ajax calling javascript function

I am using jQuery and Ajax.
My MainFile has the following code:
<html>
<head>
<script src="Myscript.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'ajax.php',
success: function(data){
$("#response").html(data);
}
});
});
</script>
<body>
<div id="response">
</div>
</body>
</html>
My ajax.php get the sample data
...
MyScript.js has the following
function display (text,corner)
{
}
..
I have Myscript.js. In this, I have a function called display(text,corner). I have to call this function after executing ajax.php.
How do I do it in jQuery for the above code?
Is it possible to decide the order of execution after ajax.php and make call for display(text,corner)?
You should invoke the display function in the callback function of the Ajax Request, like such:
$.ajax({
type:'POST',
url: 'ajax.php',
success: function(data){
display(data, /* your other parameter, corner */); //Invoking your data function
}
});
In the above case, data is the response that is received from ajax.php

Categories

Resources