This question already has answers here:
Reading JSON POST using PHP
(3 answers)
Closed 6 years ago.
I have this html / javascript :
<html>
<head>
</head>
<body>
<script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var data = {'user_id':'2680',
'ship_to_name':'John Doe',
'ship_to_address':'Somewhere in Jawa Timur',
'ship_to_city':'Surabaya',
'ship_to_area':'Wonocolo',
'ship_to_phone':'080000000'};
$.ajax({
url: "../controller/ctrl.php",
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json'
});
});
</script>
</body>
</html>
and I have this PHP on my server :
<?php
$jsonReceiveData = json_encode($_POST);
file_put_contents('storedvar.php', $jsonReceiveData);
?>
but what I got in storedvar.php is just empty variable of json. just like this [].
why I can't get json sent data? thank you.
your data is json , not a string.
replace it like this but dont split the lines.
var data = "{'user_id':'2680',"+
"'ship_to_name':'John Doe',"+
"'ship_to_address':'Somewhere in Jawa Timur',"+
"'ship_to_city':'Surabaya',"+
"'ship_to_area':'Wonocolo',"+
"'ship_to_phone':'080000000'}";
if that works you might wish to remove the stringify and see if the original json works.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I tried sending data stored in an array(emp) using ajax and other string variables like 'gtotal' in code but data has not been transferred to the PHP file. It doesn't show any error but when I removed the isset() function it says unidentified index. I tried with different variables but no luck so far. Console function is working in HTML file and returning the values passed but data has not been collected in PHP file-like return value of $_POST shows empty array.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script >
$('#btn').click(function(){
var grandtotal=document.getElementById("gt");
var x =grandtotal.textContent;
var gtotal= String(x);;
var emp={};
emp.name=gtotal;
if(x=== '₹0'){
alert("Add to your cart")}
else{ $.ajax({
method: "POST",
url: "connect2.php",
data: emp,
success: function(data){
console.log(data);
}
});
// location.href='connect2.php'
}});
</script>
<?php
print_r($_POST);
if(isset($_POST['gtotal']))
{
$gtotal = $_POST['gtotal'];
echo $gtotal;
}
?>
The problem is that no item called gtotal is being sent in the $_POST.
Do a var_dump($_POST) to check exactly what is being sent.
You asked for an object to be sent which has an item name. If you see that in the dump then you need to use $_POST['name'] not $_POST['gtotal']
This question already has answers here:
How to assign JavaScript variable to PHP session variable?
(2 answers)
Closed 4 years ago.
This is my code I am Assigning a value to PHP but Not able to get in PHP SESSION. Tried all possible way. Also, I tried to set SESSION from javascript not get values.
var designation = $("#Designation").val();
<?php $_SESSION['lclDesignation'] = "<script type='text/javascrip'>alert(desi);</script>"?>
It's not possible to directly assign session value. using AJAX to assign the session value. Please review below code
var designation = $("#Designation").val();
$.ajax({
url: "session.php",
type: "POST",
data : {'designation' : designation },
success: function(html){
}
});
Then create the session.php file paste the below code
session.php
session_start();
$_SESSION['lclDesignation']=$_POST['designation'];
This question already has answers here:
I keep getting "Uncaught SyntaxError: Unexpected token o"
(9 answers)
Closed 7 years ago.
I am having a problem parsing simple JSON strings. I have checked them on JSONLint and it shows that they are valid. But when I try to parse them using either JSON.parse or the jQuery alternative it gives me the error unexpected token o:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
Note: I'm encoding my strings using json_encode() in PHP.
Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);
Try parse so:
var yourval = jQuery.parseJSON(JSON.stringify(data));
Using JSON.stringify(data);:
$.ajax({
url: ...
success:function(data){
JSON.stringify(data); //to string
alert(data.you_value); //to view you pop up
}
});
The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
As the other respondents have mentioned, the object is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details.ques_title);
</script>
</body>
</html>
cur_ques_details is already a JS object, you don't need to parse it
Response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o". if you need to get it as string, you could use JSON.stringify()
I had the same problem when I submitted data using jQuery AJAX:
$.ajax({
url:...
success:function(data){
//server response's data is JSON
//I use jQuery's parseJSON method
$.parseJSON(data);//it's ERROR
}
});
If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text", data is a JSON string. Then the use of $.parseJSON is okay.
I was seeing this unexpected token o error because my (incomplete) code had run previously (live reload!) and set the particular keyed local storage value to [object Object] instead of {}. It wasn't until I changed keys, that things started working as expected. Alternatively, you can follow these instructions to delete the incorrectly set localStorage value.
According to jquery API this is the wat of sending value asigned to a name with ajax
.data( key, value )
Problem is my values are already in php variables. how can i send them using ajax?
this problem is relate to this question i asked yesterday. Still couldn't find a way to send php variables to another php page when a button is clocked. sad that jQuery API Documentation doesn't have examples.
You have two php....let say page.php and ajax.php. If you call ajax.php from ajax in page.php you must write variables from php to javascript with something like
var data1 = <?= $data1 ?>;
var data2 = <?= $data2 ?>;
and then add these variables to ajax call.
Best regards,
nele
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var ajax_value1 = $("#ajax_value1").val();
var ajax_value2 = $("#ajax_value2").val();
$.ajax({
type: "POST",
url: 'sample.php?ajax_value1='+value1+'&value2='+ajax_value2,
//Specify the datatype of response if necessary
data: $("#your_form_id").serialize(),
success: function(data){
}
});
</script>
<!-- Set your ajax value in html input fields -->
<input type="text" name="ajax_value1" id="ajax_value1" value="<?php echo $ajax_value1;?>" >
<input type="text" name="ajax_value2" id="ajax_value2" value="<?php echo $ajax_value2;?>" >
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
Im using AJAX to request a php file that returns JSON
$.ajax({ url: 'php/invoice.php',
dataType: "json",
data: {id: 1},
type: 'post',
success: function(response) {
alert(response);
}
});
The php file im using is echoing json via json_encode:
while($row = mysqli_fetch_assoc($result))
{
$queryResults[] = $row;
}
echo json_encode($queryResults);
an example of what the php is sending back is:
[{"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}]
What im getting when I alert(response) is "[object Object]"
What I want is to alert the first name or any other property in the json ie. "Brent"
Iv'e tried alert(response.firstname); and it returns as undefined.
iv'e also tried to remove the dataType: "json" from the ajax request and just parse the json when it gets returned via var obj = $.parseJSON(response) and alert(obj.firstname)
I dont know what im doing wrong, I also dont know why there [ ] around the json when I use json encode. Im assume its because its returning a array from json objects which may be my problem? Im new to this and would appreciate any help or resources!
Iv'e done a couple hours of research and still cant find a answer. Thanks in advance!
The problem lies here (as #echeese first pointed out)
while($row = mysqli_fetch_assoc($result))
{
$queryResults[] = $row;
}
echo json_encode($queryResults);
Notice how the JSON looks (notice the [..] ?)
[{"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}]
It translates to this:
0 => {"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}
and you need to access it like this:
response[0].firstname
The problem that you're having is that your response is returning an array of objects. You should be able to get the first name by using response[0].firstname