Im using $.ajax in javascript. I need to get the response from php file. The code in javascript is -
var datavalues = {
a: 12,
b: 54
};
$.ajax({
type: "POST",
url: 'http://localhost/example/test.php',
data: datavalues,
success: function(response)
{
console.log(response);
$('#label').html(response);
var responsevalue = response;
}
});
and the code in php file is -
$bt = rand(0, 99);
$bt = intval($bt);
echo $bt;
The issue is that it shows the value in the label but value is not coming fine in the responsevalue variable. I need integer value in the responsevalue variable.
Output of console.log(response); statement is -
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Page</title>
</head>
<body>
</body>
</html>68<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Page</title>
</head>
<body>
</body>
</html>
Here 68 should be the value of responsevalue variable.
I hope you are not confused with the above code.
Use jquery param
var datavalues = {
a: 12,
b: 54
};
$.ajax({
type: "POST",
url: 'http://localhost/example/test.php',
data: $.param(datavalues),
success: function(response)
{
console.log(response);
$('#label').html(response);
var responsevalue = response;
}
});
in PHP file echo $_POST['a'];
The answer is given by #ceejayoz in the comments. For reference Im posting his answer here
"#pareza If that's the response, your http://localhost/example/test.php does more than just echo $bt;. You need to stop it from outputting all that HTML around the value you want."
Related
I want to parse json data created by PHP json_encode in my front end app, i can't do this:
var data= '<?php echo $jsonarr; ?>';
As it is a Cordova app.
Here is my php code:
<?php
$arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
echo json_encode($arr_login);
?>
My ajax code:
$.ajax({
type:"POST",
url: url,
data:data,
success: function(data){
var res = $.trim(data);
if (res == "Password is inccorrect" || res== "Email is inccorrect") {
$("#errmsg").html(data);
}
else{
var response= JSON.parse(data);
alert(response);
//window.open("dashboard.html?sess=logined&","_self");
}
}
});
Now if I alert data it gives me the valid JSON format as sent by PHP, but I need to convert it to javascript object so I can use it in DOM but JSON.parse gives this error in the console:
VM236:14 Uncaught SyntaxError: Unexpected token / in JSON at position 147
var response = JSON.parse(JSON.stringify(data));
Why do you alert all the json variable which is definetely an object?
I have simulated your process, as #Anik Anwar 's mention JSON.stringify is the solution
<?php
$rowlname = "row";
$rowemail = "email";
$rowfname = "rowfname";
$rowmobile = "rowmobile";
$arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
$jsonarr = json_encode($arr_login);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
var data = '<?php echo $jsonarr ?>';
</script>
<script>
$.ajax({
type: "POST",
url: '/',
data: data,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var res = $.trim(data);
var response = JSON.parse(JSON.stringify(data));
window.alert(response.lname);
}
});
</script>
</body>
</html>
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:
I tried all the stackoverflow posts about this, I spend two days and still no success 😔, I am trying to pass a JavaScript variable to a PHP variable, I tried this for example and still not succeed, it does not print noting on the screen, here is a full code:
here cc.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//treehouse code
var $my_variable = "something";
$.ajax({
url: 'cc.php',
data: {x: $my_variable},
type: 'POST'
});
});
</script>
</body>
</html>
and here cc.php:
<?php
if(isset($_POST['x'])){
echo $_POST['x'];
}
?>
What should I do?
You don't do anything with the result of the AJAX call. Add a callback function:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//treehouse code
var $my_variable = "something";
$.ajax({
url: 'cc.php',
data: {x: $my_variable},
type: 'POST'
}).done(function (result) {
alert(result); // <--- do something with the result
});
});
</script>
</body>
</html>
And your PHP code remains unchanged:
<?php
if(isset($_POST['x'])){
echo $_POST['x'];
}
?>
What you do in that callback function is up to you. You can alert() the value, log it to the console, write it somewhere on the page, etc.
If you want to print it on the screen you should use success: function(data)$('#result').html(data)} here is code example:
$(document).ready(function() {
$('#sub').click(function() {
var $my_variable = "something";
$.ajax({
url: 'cc.php',
type: 'POST',
data: { x: $my_variable },
success: function(data) {
$('#result').html(data)
}
});
});
});
You can try $.post too
$.post( "cc.php", { x: $my_variable} );
I am trying to multiply two values that script get from below two different api. I am using document.getelementbyid to get the two id that I need which is gbp and balance. The api script can display the data get from api. However, the multiply script is not working. Nothing is showing. Help please?
first api
$(function() {
$.ajax({
type: "GET",
url: "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=ETH,GBP,HKD",
dataType: "json",
success: function (data) {
console.log(typeof data);
var json = data;
$('#gbp').html(json.GBP);
$('#hkd').html(json.HKD);
}
});
});
second api
$(function() {
$.ajax({
type: "GET",
url: "https://api.nanopool.org/v1/eth/reportedhashrate/1",
dataType: "json",
success: function (data) {
console.log(typeof data); // -- Object
var json = data;
$('#balance').html(json.data);
}
});
});
multiply javascript:
$(function () {
"use strict";
var $butbut =document.getElementById('gbp').html;
var $siksik =document.getElementById('balance').html;
var $lamlam = $butbut * $siksik;
document.getElementById('money').html=$lamlam;
});
html script
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="Untitled-4.js"></script>
</head>
<body>
<div id="balance"></div>
<div id="money"></div>
<div id="gbp"></div>
</body>
</html>
Getting the inner html of an element is .innerHTML, not .html
var $butbut = document.getElementById('gbp').innerHTML;
var $siksik = document.getElementById('balance').innerHTML;
document.getElementById('money').innerHTML = $lamlam;
Alternatively, you can use jquery
var $butbut = $('#gpb').html();
var $siksik = $('#balance').html();
$('#money').html($lamlam);
ajaxcheck.js
var val = "hai";
$.ajax(
{
type: 'POST',
url: 'ajaxphp.php',
data: { "abc" : val },
success :function(data)
{
alert('success');
}
}
)
.done(function(data) {
alert("success :"+data.slice(0, 100));
}
)
.fail(function() {
alert("error");
}
);
ajax.html
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="ajaxcheck.js"></script>
<title>ajax request testing</title>
</head>
<body>
</body>
</html>
ajaxphp.php
<?php
$v_var = $_POST["abc"];
print_r($_POST);
if(isset($_POST["abc"]))
{
echo $v_var;
}
else
{
echo "Data not received";
}
?>
When I run the ajax.html file ,I get success alert. But when I run ajaxphp.php file it shows notice like:
undefined index abc
Why is that the data is not received in $v_var ? where i am mistaking ?please help.
Actually the ajaxphp.php file is used to receive the data from the
post method and i will give response .
In First case by using ajax post method it will call to ajaxphp.php file.
In Second case your using direct file call without any post data(that's way it shows error)
Try this
var val = "hai"
$.post( "ajaxphp.php", {'abc':val}function( data ) {
alert( "Data Loaded: " + data );
});
jQuery expects an object as data, remove the double-quotes:
data: { abc : val }