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!
Related
I got problem when parsing JSON from my AJAX. This is my error and the data that I want to parse
This my code:
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
data: { kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust:
codeCustomer },
success: function(result) {
if(result) {
console.log(result);
obj = $.parseJSON(result);
}
My controller
public function get_produk_by_eancode() {
$eancode = $this->input->post('kodePilihan');
$kodeScala = $this->input->post('kodeScala');
$codecust = $this->input->post('codecust');
$barangPilihan = $this->web_ordering_model->get_produk_by_eancode_page3($eancode, $kodeScala, $codecust)->row_array();
echo json_encode($barangPilihan);
}
My result data from the controller or you can see in picture
{"SC01132":"*1038 AR BRU KM","SC01002":"BOX-50 dengan Roda","SC01011":"A-19","brand":"Kiramas","verpacking":12,"List1":"76250.00000000","SC01001":"625050","Free":".00","LastTglProduksi":"1900-01-01 00:00:00.000","PricelistName":"Netto"}
You get this error because what you give to parseJSON is not a string.
First try to add content-type to you AJAX call :
contentType: "application/json; charset=utf-8",
dataType: "json",
Also you can convert your object to a string.
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
dataType: "json", //changes
data: ({ kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust: codeCustomer }),
success: function(result) {
if(result) {
console.log(result);
var obj = JSON.parse(result); //changes
console.log(obj); //changes
}
}
Solved by this code
$.trim()
Sorry for my long report, thanks.
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?
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.
I have a JSON from a PHP file and I want to send that output to another PHP file. This is my JavaScript:
var data_1;
$.ajax({
type:"POST",
url:"sd.php",
success:function(result){
data_1 = result;
test(data_1);
var st = JSON.stringify(data_1);
$.post('get.php',{q:st},function(data){
window.location = "get.php";
});
}
});
And my PHP file to store the JSON:
<?php
$obj = json_decode($_POST['q']);
echo $obj;
?>
But it outputs nothing. What should I do? Please help.
You may try this i wrote for you, but its not tested
/**
* Created by vladimirnikolic on 3/24/14.
*/
$('#submit').click(function(e){
e.preventDefault();
var form_data = $('#your_form').serializeArray();
var submit_data = serializedFormToDTO(form_data);
$.ajax({
url: 'sd.php',
type: 'POST',
dataType: 'json',
data: submit_data
})
.done(function(xhr) {
$.post("get.php", {
q: submit_data
},
function (data) {
// handle data here
// console.log(data);
}, 'json');
}
)
.fail(function(xhr) {
var response_text = $.parseJSON(xhr.responseText)
console.log(response_text);
})
});
function serializedFormToDTO (data, json) {
json = (typeof json !== 'undefined') ? json : false;
if ((json !== true) && (json !== false) ) {
console.log('invalid value of second parameter (should be true/false for json output)');
return false;
}
var result = {};
for (var i = data.length - 1; i >= 0; i--) {
result[data[i].name] = data[i].value;
}
if (json === true) {
result = JSON.stringify(result);
}
return result;
}
$.ajax({
url: 'sd.php',
type: 'POST',
data: JSON.stringify(data_1), // data_1 is a javascript object here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(returned_data) {
alert(returned_data);
}
});
Here's my java script file:
$('#addSchoolForm').trigger("reset");
//$(document).ready(function() {
$(function() {
$("#dialog").dialog({
autoOpen: false,
maxWidth:600,
maxHeight: 350,
width: 500,
height: 300,
});
$("#addSchool").on("click", function() {
$("#dialog").dialog("open");
});
$("#addSchoolForm").submit(function(e) {
e.preventDefault();
$("#dialog").dialog("close")
var postData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "AddSchools.php",
data: postData,
success: function(data){
alert(data); }
});
});
$("#editSchool").submit(function(e) {
e.preventDefault();
var editData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "GetSchoolID.php",
data: editData,
dataType: 'json',
success: function(data){
var schoolID = $.parseJSON(data);
alert("success");
alert(schoolID.name);
//alert(data["json"]);
//alert(data);
//document.addSchoolForm[sname].value = data[0].name;
//document.addSchoolForm[abbrev].value = data[abbrev];
//document.addSchoolForm[abbrev].value = data[0].abbrev;
}
alert(schoolID.name);
});
//$("#dialog").dialog("open");
});
})
And here's my get schoolID php file
<?php
$school_id = $_POST['school_id'];
$db = mysqli_connect("localhost", "root", "imagroup123","mytrack");
if(!$db){
exit("Error in database connection");
echo("couldn't connect to database");
}
else{
$q = "SELECT * FROM `School` WHERE `SchoolID`='$school_id'";
$schoolresults = mysqli_query($db,$q);
$row = mysqli_fetch_assoc($schoolresults);
$school["name"] = $row['SchoolLong'];
$school["abbrev"] = $row['SchoolShort'];
echo json_encode($school);
}
?>
When I just tested the php file with jsonlint.com I get a correct json object but it's not getting carried through the javascript file. I'm fairly new to this so I'm pretty suck with this problem. I also want to add the data to a form values and then open the dialog form after.
Change:
success: function(data){
var schoolID = $.parseJSON(data);
to:
success: function(schoolID){
because $.ajax automatically calls $.parseJSON() when you specify dataType: 'json'.
Here is the php backend structure that I use all the time:
$query = " SELECT *
FROM school
WHERE SchoolID = $school_id;
$result = mysqli_query($cxn, $query) or die ("could not query database 1");
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result);
$variablestopass = array
(
'schoolname' => $row['SchoolLong'],
'schoolabbrev' => $row['SchoolShort'],
);
echo json_encode($variablestopass);}
else
{ echo "Error selection id"; }
And here is some js to call it and read it:
$.ajax({
type: 'POST',
url: 'thenameofyourfile.php';
data: {schoolid: schoolid},
dataType: 'json'
})
.done( function() { alert( "Got it!"" );
Do other stuff here
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR.responseText, textStatus, errorThrown);
});