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>
Related
This is driving me crazy. I'm trying to post a variable to a PHP script using AJAX but while I can verify that $_POST is set, the varibale remains undefined.
I've used almost identical code elsewhere and it works fine - I just cant see what the problem is here.
Here is a very stripped down version of the code -
The JS
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: "scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
// execute script
},
error: function(data, status, errorString)
{
alert('error');
}
});
return false;
});
});
The PHP
if (isset($_POST)) {
echo "POST is set";
if (isset($_POST['limit'])) {
$newLimit = $_POST['limit'];
echo $newLimit;
}
}
UPDATE
var_dump($_POST) returns array(0) { } so I know that AJAX is definitely is not posting any values
Using slightly modified version of the above I am unable to reproduce your error - it appears to work fine.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
if( isset( $_POST['limit'] ) ){
echo $_POST['limit'];
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: location.href, //"scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
alert( result )
},
error: function(data, status, errorString){
alert('error');
}
});
return false;
});
});
</script>
</head>
<body>
<!-- content -->
<div id='load_more_comments'>Load more...</div>
</body>
</html>
Try :
if (count($_POST)) {
Instead of
if (isset($_POST)) {
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."
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 am trying send an array from php to js via ajax but don't it run, no matter what I do.
I'm sure it must be simple but I've tried everything.
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
<link type="text/css" rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scriptJS.js"></script>
</head>
<body>
<div>
<div class="tweets-container">
<p>Loading</p>
</div>
</div>
</body>
</html>
$(document).ready(function() {
var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
'<h1>Welcome!</h1>' +
'<div class="seeTweets"><select>';
var count = 0;
$.get({
url: 'scriptPHP.php',
type: 'GET',
data: {
usUsers: 'usuarios'
},
success: function(response) {
contPrincipalLastTwitter += '<option value =' + response + '>' + response + '</option>';
count++;
},
error: function(e) {
console.log(e.responseType);
);
}
});
console.log(count); contPrincipalLastTwitter += '</select></div></div>'; $(document.body).append(contPrincipalLastTwitter);
});
<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
echo json_encode($test);
?>
I reduced it as much as I could, originally this one was sent to a class and this one, having several requests acted according to who have called it.
the problem is that you try to concatenate the same string in two different time and place (first inside the document ready, secondly in the success of the ajax call)
js code:
$(document).ready(function() {
var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
'<h1>Welcome!</h1>' +
'<div class="seeTweets"><select id="test-select"></select></div></div>';
$(document.body).append(contPrincipalLastTwitter);
$.get({
url: 'scriptPHP.php',
type: 'GET',
data: {
usUsers: 'usuarios'
},
success: function(response) {console.log(response);
console.log(response);
for(var idx in response){
$('#test-select').append('<option value =' + idx + '>' + response[idx] + '</option>');
}
},
error: function(e) {
console.log(e.responseType);
}});
});
scriptPHP.php
<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
// add header
header('Content-Type: application/json');
echo json_encode($test);
A slightly simpler option
const target = document.querySelector('#target');
$.ajax({
url: 'script.php',
dataType: 'JSON',
success: response => {
for (let key in response) {
const option = `<option value="${key}">${response[key]}</option>`;
target.innerHTML += option;
}
},
error: error => {
// todo
}
});
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 }