Sending data from knockout to php - javascript

I created a login function
self.login = function() {
var credentials = {
email: self.email(),
pass: self.pass()
}
var data = ko.toJS(credentials);
$.ajax({
url: 'client/scripts/pages/login/login.php',
type: 'post',
data: {data: data},
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
}
This will send request to php file when the form is submitted.
Here is the login.php code,
$data = json_decode($_POST['data']);
return $data['email'];
When i execute this, the result is Undefined index: data
I tried JSON.strignify but it is not working. how can I get the email of the user in php?

I'm using the following code:
Client-side (JS):
$.ajax((<any>{
type: "POST",
async: async,
url: dataServiceBaseUrl + "request.php", //
data: {
"jsonrpc": "2.0",
"method": method,
"dbname": dbName,
"params": JSON.stringify(params)
},
success: function(data) {
var obj = JSON.parse(data);
},
error: function() {
}
}));
Server-side (PHP):
function process_request() {
$dbname = $_POST["dbname"];
$method = $_POST["method"];
$params = json_decode($_POST["params"], true);
$result = call_user_func_array("methods::" . $method, $params);
return json_encode(array("jsonrpc" => "2.0", "result" => $result, "error" => null, "usename"=>$usename));
}
Of course,
var data = ko.toJS(credentials);
is necessary to get serializable data to sent.

Related

JQuery ajax function sends the correct value.But RestController receives null

These codes are RestController of my spring boot project,
#RestController
#RequestMapping(value="/rest/user")
public class UserRestController {
#Autowired
private UserService userService;
#PostMapping("login")
public ResponseEntity<Boolean> authenticated(#RequestBody User user) {
System.out.println(user.getUsername() +":"+ user.getPassword()); //This line returns NULL password value
Boolean blogin = userService.authenticate(user.getUsername(), user.getPassword());
if(!blogin)
return new ResponseEntity<Boolean>(blogin, HttpStatus.NOT_ACCEPTABLE);
return new ResponseEntity<Boolean>(blogin, HttpStatus.OK);
}
}
And Below codes are JQuery ajax java-script codes.
function ajax_login_submit() {
var user = {
username: $("#username").val(),
password: $("#password").val()
};
console.log(user);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "rest/user/login",
data: JSON.stringify(user),
dataType: 'json',
success: function (data) {
var resultJson = JSON.stringify(data);
$('#helloUserDiv').html(resultJson);
console.log("SUCCESS : ", data);
alert(data);
},
error: function (e) {
var resultJson = e.responseText;
$('#helloUserDiv').html(resultJson);
console.log("ERROR : ", e);
}
});
}
console.log(user); of java script returns the correct value.
{"username":"joseph","password":"password"}
But in the RestController codes, password value is missing, "NULL".
The line System.out.println(user.getUsername() + ":" + user.getPassword()); returns strange value, "joseph:null"
Is it possible for JQuery ajax method not to transfer the json value to REST server? If I make some mistakes, kindly inform me how to send the json value to REST server correctly.
Try this:
$.ajax({
type: "POST",
contentType: "application/json",
url: "rest/user/login",
data: JSON.stringify({"username": $("#username").val(), "password": $("#password").val()}),
dataType: 'json',
success: function (data) {
var resultJson = JSON.stringify(data);
$('#helloUserDiv').html(resultJson);
console.log("SUCCESS : ", data);
alert(data);
},
error: function (e) {
var resultJson = e.responseText;
$('#helloUserDiv').html(resultJson);
console.log("ERROR : ", e);
}
});

Cant fetch array from server side

I want to get some data from a php script to my html page. They array $UniqueNames has a value on the server side, but nothing seems to happen when i use json_encode on the html page, the console.log returns an empty array (BilderID). Any suggestions?
code:
<script>
var BilderID = [];
$(document).ready(function (e) {
$('#SubmitBild').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('Myfilefield').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("Bilder[]", document.getElementById('Myfilefield').files[x]);
}
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
BilderID = <?php echo json_encode($UniqueNames); ?>
console.log(BilderID);
});
});
</script>
Php:
$UniqueNames = array();
for($i=0;$i<count($file_array);$i++)
{
if($file_array[$i]['error']){
echo $phpFileUploadErrors[$file_array[$i]['error']];
} else {
$extensions = array('jpg','png','gif','jpeg');
$file_ext = explode('.',$file_array[$i]['name']);
$file_ext = end($file_ext);
if (!in_array($file_ext, $extensions)){
echo "Invalid file extension!";
} else {
$fileNameNew = uniqid('', true).".".$file_ext;
$UniqueNames[] = $fileNameNew;
move_uploaded_file($file_array[$i]['tmp_name'], 'Bilder/'.$fileNameNew);
echo $phpFileUploadErrors[$file_array[$i]['error']];
}
}
}
The solution was to remove the datatype specifier, echo out the array in php and receive it inside the success method:
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
BilderID = response;
console.log(BilderID);
},
error: function (response) {
console.log("error:");
}
});
i mean, why use "datatype" if javascript figures it out anyway?

Undefined index in post method of JSON object sent by jQuery AJAX

I've tried almost all suggestions but it doesn't work. My ids are working properly in the JavaScript function when I alert my array using arr['id']. However, when I try $_POST['id'] on a different PHP file (I've used AJAX and specified the URL) is gives me an error.
scriptfile.php:
<script>
function detailsmodal(cid, pid) {
var arr = { "cid": cid, "pid": pid };
jQuery.ajax({
url: '/frontend/include/detailsmodal.php',
method: "post",
data: arr,
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
}
detailsmodal.php
<?php
echo $_POST['cid'];
?>
You could try sending your data as json like this:
$.ajax({
type: "POST",
url: "/frontend/include/detailsmodal.php",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ cid: cid, pid: pid }),
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
For the decoding you could use javascript JSON.parse
var myObj = JSON.parse(this.responseText);
or
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["cid"];

Javascript dynamic post ajax/json not sending parameters

I'm trying to send a POST dinamically in a javascript code to a PHP script.
It seems to me that there is something wrong that the data are not sending json data as parameters.
Here is how I generate de json data:
query_string_fn = {};
query_string_fn ["cdinterno"] = cdinterno;
o.row.find("input, select").each(function() {
var val = $(this).val();
var id = $(this).attr('name');
query_string_fn [id] = val;
if (id == 'cdfornecedor_new') {
var cmbSelected = $(this)[0];
value_label = cmbSelected.options[cmbSelected.selectedIndex].text;
} else if (id == 'cdtipo_new') {
var tipocmbSelected = $(this)[0];
tipovalue_label = tipocmbSelected.options[tipocmbSelected.selectedIndex].text;
} else {
$(this).val(val);
}
}).end();
if (value_label.length > 0)
o.row[0].innerHTML = value_label;
if (tipovalue_label.length > 0)
o.row[11].innerHTML = tipovalue_label;
editarFN_Post(query_string_fn);
Here is how I'm sending the data to php. There are some tests commented that I have tested:
function editarFN_Post(query) {
query["action"] = 2;
var data = query;
$.ajax({
type: "POST",
dataType: "json",
url: "funcoesFN_Fornecedor_Produto_post.php",
//processData: false,
//contentType: "application/json; charset=UTF-8",
//contentType: 'application/json; charset=UTF-8',
//data: data,
//data: data.toString(),
data: JSON.stringify(data),
//data: {data: query},
success: function(rsp) {
alert ("Success!");
alert (rsp);
},
failure: function(rsp) {
alert ("Failed...");
alert (rsp);
}
});
}
Here is the PHP code that I check if the parameters have been sent:
header("Content-type: application/json; charset=utf-8");
echo "action=" . $_POST["action"] . "<br>";
foreach ($_POST as $key => $value)
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
var_dump($_POST);
None of these tests above return data.
Thanks!

ajax function not going to php codeigniter controller

I have a ajax function written which is posting different numbers.
Here is the ajax function.
self.giveCashtoChild = function(){
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/addUserChildrenCash'+"/"+self.selectedchild(),
contentType: 'application/json; charset=utf-8'
})
.done(function() {
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
}
self.selectedchild() has the value of 2 , so Basically the url is addUserChildrenCash/2 but then it does not go to the codeigniter controller and change the page. Here is the controller function.
public function addUserChildrenCash($childID){
if (!$this->session->userdata('user_id')){
redirect('main'); // the user is not logged in, redirect them!
}
$userid= $this->session->userdata('user_id');
$this->load->model('main_page');
$childname = $this->main_page->getChildName($childID, $userid);
$data = array(
'name' => $childname['children_name']
);
$this->load->view('header2_view');
$this->load->view('add_user_children_cash_view' , $data);
$this->load->view('footer_view');
}
You define ajax as POST but you sending it via GET
type: 'POST',
url: BASEURL + '/index.php/main/addUserChildrenCash'+"/"+self.selectedchild(),
So your code should be
In Ajax
var id = self.selectedchild(); # Assign data to here
$.ajax(
{
type:"post",
url: "<?php echo base_url(); ?>index.php/main/addUserChildrenCash",
data:{ id:id},
success:function()
{
}
error:function()
{
}
always:function(){
}
});
In controller
public function addUserChildrenCash()
{
$id = $this->input->post("id");
echo $id
}
self.giveCashtoChild = function(){
var id = self.selectedchild();
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/addUserChildrenCash/"+id,
contentType: 'application/json; charset=utf-8'
})
.done(function() {
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
}
In your codeigniter use case I would pass your ajax parameter like this:
$.ajax({
type: 'post',
url: BASEURL +'/index.php/main/addUserChildrenCash',
data: { 'childID': self.selectedchild() },
})
...
In the codeigniter controller I would receive the parameter like this:
public function addUserChildrenCash() {
$childID = $this->input->post("childID");
...
}
You should also check wether your BASEURL has the correct value assigned. Hope this helps.

Categories