AJAX post method from JS to PHP - variable null - javascript

I want to call the server function from client side via AJAX.
index.php:
<?php
?>
<html>
<head>
...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
...
console.log(position); // there IS a value! good!
console.log(result); // there IS a value! good!
jQuery.ajax({
type: "POST",
url: 'crud.php',
data: {functionname: 'insertLocation', arguments: [position, result]},
success:function(data) {
alert(data);
}
});
crud.php:
<?php
$position = $_POST["position"]; //NOTHING!
$result = $_POST["result"]; //NOTHING!
include ("insert.php");
switch($_POST["functionname"]){
case 'insertLocation':
insertLocation($position,$result);
break;
}
?>
insert.php
<?php
function insertLocation($position,$result){
...
}
?>
I am losing the value when passing it to the server side. I am able to log the value from JS , but then when I am logging in php there is null (or empty string?). Also query to Database works but no value is inserted.
I am beginner with web programming so I apologise in advance for bad smells, etc.

Yes, $_POST has your variables, but they are located in the array $_POST['arguments'] :
$_POST['arguments'][0] == position
$_POST['arguments'][1] == result
If you want to be able to do $result = $_POST["result"] you must change the params in your AJAX request to
...
data: {functionname: 'insertLocation', position: position, result: result},
...

data: {
functionname: 'insertLocation',
position: position,
result: result
}

Related

How to get a multidimensional array after submitting my form from javascript into PHP?

One php file with php and javascript inside. I have a multidimensional array defined in the javascript part. I can see the proper output of "key" and "value" in the console but I do no get the array into php after submitting my form.
What I am doing wrong?
<?php
echo "Postcmd: ".$_POST["postcmd"];
print_r($_POST["postcmd"]);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var postcmd =[];
var key;
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd.hasOwnProperty(key)) {
console.log(postcmd[key])
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd
});
}
</script>
Not even this simple and often found script example works for me - what else might be the issue? Are there other (basic) things to know about js->PHP?
<?php
// index.php
?>
<html>
<head>
<title>Pass JS array to PHP.</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var arrayfromjs = "123";
$.ajax({
type: "POST",
url: "index.php",
data: { testArray : arrayfromjs},
success: function() {
alert("Success");
}
});
</script>
</head>
<body>
<?php
echo "<br>Pass JS array to PHP.<br>";
$myArray = $_POST['testArray'];
print_r($myArray);
?>
</body>
</html>
Per the jQuery documentation,
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Thus, your data field must contain an object (such as {foo: bar, foo_again: bar_again}; in PHP, this would read as $_POST['foo'] == "bar"). However, your code submits an array with one element: the object specified. In addition, PHP does not magically turn your JS array/object into a PHP array. You have to parse the string passed into PHP and turn it into the array you need.
If you print $_POST, you can see what exactly is being passed into your PHP. That might help you see what is happening.
You are creating the following structure using the push method:
[
{
"key":"first_name",
"value": "Bob"
}
]
Using your code, all you need to do is index the postcmd variable to the object. You also had some indexing issues with your loop. The key variable would just be index 0. So you would need to set it to postcmd[key] to check for the key named "key".
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd[0]
});
}
Using the above snippet, jQuery will then parse the data into the correct key value pairs. Without specifying the index, the data would be posted as undefined=Bob
On the PHP side you should be able to grab those values as such:
<?php
echo $_POST['key'].PHP_EOL;
echo $_POST['value'];
?>
Alternative Method - JSON Submission
You could make the following modification to post the data as JSON:
function formsubmitplus(ele) {
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
contentType: 'application/json',
data: JSON.stringify(postcmd)
});
}
Then on the PHP side you can grab the POST body using the following:
<?php
echo "<pre>";
$json_data = json_decode(file_get_contents('php://input'), true);
print_r($json_data);
?>
If you would rather work with a PHP Object vs an Associative array. Just change true to false.
Ad the end I found a solution without jquery which works for me the best.
It is "playing" with HIDDEN form fields.
Maybe someone finds it helpful:
function submitform() {
Object.getOwnPropertyNames(postcmd).forEach(function(val, idx, array) {
var outarrayoutput = val + ' ==== ' + postcmd[val];
console.log(outarrayoutput);
var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'outArray[]';
newHidInp.value = outarrayoutput;
maintable.appendChild(newHidInp);
});
document.maintable.submit();
}

Call Php controller function with AJAX Codeigniter

I , im working with Ajax and Codeigniter to call function client-server
the php
public function mainViewClean() {
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
return "Ready";
}
//route $route['cleantags'] = 'user/mainViewClean';
And ajax:
<script type="text/javascript">
$(document).ready(function(){
$("#btn_recargar").button().click(function(){
//window.location.href = "<?= base_url('home')?>";
$.ajax({
type:'POST',
url:'<?php echo base_url("cleantags"); ?>',
data:{'id':100},
success:function(data){
//window.location.href = "<?= base_url('home')?>";
alert(data);
}
});
});
});
</script>
The function excuse good , but javascript don't show any data , what im doing wrong?
Well, the ajax call reads the response from the server, and that response must be rendered as some type of readable data, such as application/json or text/html.
In order to write that data, you need to echo it from the server with PHP.
The return statement doesn't write data, it simply returns at the server level.
If you want to communicate between PHP functions, you have to use return. But if you want to output some data, you have to use echo
Client side
$.ajax({
url:'<?php echo base_url("cleantags"); ?>',
dataType: 'application/json',
success:function(response)
{
alert(response.foo);
}
})
Server Side
public function mainViewClean()
{
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
echo json_encode( array("foo"=>"Ready"));
}
Change return into :
echo "Ready";
If you're sending an array, at server side you need to json_encode, example :
// encode array into json string format
echo json_encode( array( 'name' => 'Osman' ) );
And in Js, you have 2 options, the 1st solution is :
success : function ( data ) {
// data now is coming in this form { "name" : "osman" }
// as the string data is coming from server-side
// you must parse it back into Javascript object
var newData = JSON.parse( data );
}
And the 2nd option is, add dataType properties inside ajax properties like following :
$.ajax({
...
dataType : 'json', // with this, no need to write JSON.parse()
...
});
I'm fairly new as I only have been using AJAX , but I think your code has a few syntactical errors.
data: { id:100 } with no quotations around id.
I advise you need to look at more examples of ajax calls to fix these little errors.
You said your JS is working but not showing data?

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

Getting undefined on my Ajax call

I'm getting undefined in the console when trying to log the "data.billAmount" statement. Why is this happening and how do I fix it?
I tried doing JSON.parse and JSON.stringify but those didn't work. I tried using dataType: 'json' but that didn't work. I'm not sure what else to try. I'm stuck.
PHP:
if (#$_POST['action'] == 'addBill')
{
$billName = $_POST['bill_name'];
$billAmount = intval($_POST['bill_amount']);
$data = array(
'billName' => $billName,
'billAmount' => $billAmount,
);
echo json_encode($data);
$stmt = $db->prepare("INSERT INTO bills (billName, billAmount) VALUES(?,?)");
$stmt->bindParam(1, $billName);
$stmt->bindParam(2, $billAmount);
$stmt->execute();
}
JavaScript:
$(".addBill").on("click", function(e) {
e.preventDefault();
var billAmount = $('.billAmount').val();
var billName = $('.billName').val();
$.ajax({
type: "POST",
url: "index.php",
data: {
billAmount: billAmount,
billName: billName,
action: 'addBill'
},
success: function(data) {
console.log(data.billAmount);
}
});
});
Suggest you to move functionality which is responsible for adding bill into separate file. Then make AJAX call to that file and everything would works well, because if you want a particular value point request to particular file which echo that value for you...
No needs to looking for workaround when that could be done in clear and right way by separating functionality into smaller junks.
In case if you insist to use index.php
after
$stmt->execute();
put one more line
exit();
As Mohamed-Yousef commented on question.

json import breaks down but from same server source

I am exploring the ajax synchronous json import into my javascript code.
The JSON source link I want to use is
http://www.nusantech.com/hendak/default.php?m=galaksi&galaksi=1&viewID=1&t=json
But to keep server loads down, a week ago or so I created a static page showing the same data at
http://www.nusantech.com/hendak/noobjson.php
My javascript import is as below:
<head>
<title>Nusantech</title>
<script src="\OpenLayers213\OpenLayers.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = {};
$.ajax({
url: "http://hendak.seribudaya.com/noobjson.php",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
alert("Galaksi value retrieved from JSON (expected: 1) : "+jsonData.galaksi);
</script>
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
</head>
From there I retrieve the values I want on jsonData, eg, (x,y) coordinates as
(jsonData.planets[7].coordinates[0].x,jsonData.planets[7].coordinates[0].y)
It works fine with the noobjson.php link, but when I point it back to default.php, nothing appears. The page took a while to load which make it seem like its loading the json values, but the alert("Galaksi value retrieved") returns undefined.
I copy & pasted the output from the default.php page on a JSON verifier on the web and it showed OK. I don't know why the static link works but the $_GET based link doesn't.
Can someone suggest me what is happening?
EDIT
I have tried:
<script type="text/javascript">
var jsonData = {};
$.ajax({
// url: "http://hendak.seribudaya.com/noobjson.php",
url: "http://hendak.seribudaya.com/default.php?"+encodeURIComponent("galaksi=1&viewID=1&m=galaksi&t=json"),
// url: "http://hendak.seribudaya.com/default.php?galaksi=1&viewID=1&m=galaksi&t=json",
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json",
success: function(data) {
jsonData = JSON.parse(JSON.stringify(eval("("+data+")")));
alert("Success");
},
error: function(data) {
alert("Failed to download info." + data);
}
});
</SCRIPT>
enter code here
I always get the Failed to download info unless I use the noobjson URL.
It is as if that URL with the GET doesn't exist.
You have to encode the URL component before sending the request. Try:
$.ajax({
url: "http://www.nusantech.com/hendak/default.php?" + encodeURIComponent('m=galaksi&galaksi=1&viewID=1&t=json'),
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
Reference: encodeURIComponent()
I have solved it.
In the default.php, what I have done was:
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
if ($_GET["t"]!="json") { echo "<PRE>\n"; $lb="\n"; }
echo "{\"galaksi\": ".$galaksi.",";
echo $lb."\"hari\": ".$hari.",";
echo $lb."\"planets\": [";
//etc
//etc
}
So I replaced all the individual echoes with $JSONstr like below.
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
$JSONstr="";
// if ($_GET["t"]!="json") { $JSONstr="<PRE>\n"; $lb="\n"; }
$JSONstr=$JSONstr."{\"galaksi\": ".$galaksi.",";
$JSONstr=$JSONstr.$lb."\"hari\": ".$hari.",";
$JSONstr=$JSONstr.$lb."\"planets\": [";
//etc
//etc
//and at the end:
echo $JSONstr;
}
Then I added the echo $JSONstr; at the end. Originally I did that so that I can do :
echo json_encode($JSONstr);
but this creates {\"Galaksi\" : 1} at the JSON output instead of the intended { "Galaksi": 1 }
So I removed the json_encode and just output the string.
Also I had to remove the
if ($_GET["t"]!="json"){ $JSONstr="<PRE>\n"; $lb="\n"; }
I also used a different JSON tester this time.
Originally I used http://www.freeformatter.com/json-validator.html which says JSON Valid for my initial JSON output. Then I used this one, which said that my JSON output url was invalid, although if I copy+paste the output string it returned valid. http://jsonformatter.curiousconcept.com/
So after making those changes and removing the "<PRE>", the curiousconcept validator gave me a valid status.
Then I used this in the javascript, and I am now able to retrieve expected values.
Thank you all, hope this helps someone else too.

Categories