I am a newer for study php and jQuery, I tried many times myself, but also not work well.
How to modify a PHP json_decode into a jQuery.getJSON()? I want modify all the PHPcode into javascript.
$json_data = file_get_contents("data.txt");
$data = json_decode($json_data, true);
if($data){
$num = 1;
foreach ($data as $result) {
?>
$.ajax({
url: "page2.php",
dataType: "html",
type: 'POST',
data: "value=<?php echo $result['name']; ?>",
success: function(data){
$("#result<?php echo $num; ?>").html(data);
}
<?php
$num++
}
}
?>
json tree:
[
{"name" : "name1"},
{"name" : "name2"},
{"name" : "name3"},
]
If you're sure the text file is json then the following should work as JSON is a subset of javascript.
<?php
$json_data = file_get_contents("data.txt");
echo "var json_data = $json_data;";
?>
for (var i = 0; i<json_data.length; i++) {
$.ajax({
url: "page2.php",
dataType: "html",
type: 'POST',
data: "value="+json_data[i].name,
success: function(data){
$("#result"+String(i+1)).html(data);
}
}
Related
I have gone through many answers
How to upload file using ajax in codeigniter
File upload in codeigniter using ajax
which does not work with my code.
I want to upload word pdf img any sort of file using ajax.
This is my code:
Controller:
public function saveDetailData()
{
$rowId = $this->input->post('rowId',true);
$rowData = $this->input->post('rowData',true);
$rowColumn = $this->input->post('rowColumn',true);
$detailTableName = $this->input->post('detailTableName',true);
if($rowColumn == 'attachment'){
$filename2 = 'Query_'.rand(0,999999);
if( ! is_dir('uploads') ){mkdir('uploads',0777,TRUE); };
$path='uploads/queries/';
$imgtmpname=$_FILES['rowData']['tmp_name'];
$name = $_FILES["rowData"]["name"];
$ext = end((explode(".", $name)));
$fullpath= $path .$filename2.'.'.$ext;
$filename = $filename2;
move_uploaded_file($imgtmpname,$fullpath);
if ($ext <> '')
{
$fields = array(
'attachment' => $fullpath
);
}
else
{
$fields = array(
'attachment' => ''
);
}
}
$this->user_model->saveDetailData($rowId,$fields, $detailTableName);
echo "Successfully Saved";
}
View:
<?php echo form_open_multipart('editMatter');?>
<input onfocusout="saveDetailData1('<?php echo $detail->id; ?>',$(this).attr('name'),'attachment' )" type="file" id="attachment_<?php echo $detail->id; ?>" name="attachment_<?php echo $detail->id; ?>" value="">
<script>
function saveDetailData1(rowId,rowData,rowColumn) {
attachment = new FormData( $('#'+rowData)[0] );
$.ajax({
type: "POST",
url: "<?php echo base_url('user/saveDetailData')?>",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'rowId': rowId,
'rowData' :attachment,
'rowColumn' :rowColumn,
'detailTableName': 'tbl_mattersdetail',
},
dataType:"JSON",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(response){
//alert(response);
}
});
}
</script>
Try to modify the saveDetailData1 function like this :
function saveDetailData1(rowId,rowData,rowColumn) {
attachment = new FormData();
attachment.append('rowData', $('input[type=file][name="attachment_'+rowId+'"]')[0].files[0]);
$.ajax({
type: "POST",
url: "<?php echo base_url('user/saveDetailData')?>",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'rowId': rowId,
'rowData' :attachment,
'rowColumn' :rowColumn,
'detailTableName': 'tbl_mattersdetail',
},
dataType:"JSON",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(response){
//alert(response);
}
});
}
This will skip the rowData function parameter, but instead directly select the file input as the rowData ajax parameter.
I send data via json. It is working well:
$.ajax({
url: "json.php",
type: "POST",
dataType: "json",
encode: true,
data: {},
success: function (data) {
$(".blue").html(data.blue);
$(".red").html(data.red);
}
});
json.php
$array['blue'] = "blue array";
$array['red'] = "red content";
echo json_encode($array);
My problem is now, that instead of..
blue array
...I want to send:
$pdo = $db->query('SELECT * FROM data;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "<li>".$row['name']."</li>";
}
is this possible?
Here's an extremely basic example:
<?php
$json = array(
'blue' => '',
'red' => 'Empty red content or whatever'
);
$pdo = $db->query('SELECT * FROM data;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
$json['blue'].= "<li>".$row['name']."</li>";
}
echo json_encode($json);
Not sure what logic you would use to actually populate red but you can work it into the while loop or whatever.
i want to get the specific value from the json, but i can't get it to work.
this is my save format, these are values from input fields.
$.ajax({
type: "POST",
url: "speichern.php",
dataType: 'json',
data: {
"Produkt": {
"Produktkategorie": Produktkategorie,
"Optionen": {
"MaxBreite": MaxBreite,
"MaxHoehe": MaxHoehe,
"MinBreite": MinBreite,
"MinHoehe": MinHoehe,
"ProduktStaerke": ProduktStaerke,
"KantenAuswahl": KantenAuswahl, },
"Formen": {
"FormRund": FormRund,
"FormEllipse": FormEllipse,
"FormHexagon": FormHexagon,
"FormSchnittlinks": FormSchnittlinks,
"FormRechtQuad": FormRechtQuad,
}
}
},
}).done(function( msg ) {
console.log( msg );
});
here it gets saved to file:
$neu = json_encode($_POST);
$file = file_get_contents('results.json');
$data = json_decode($file);
unset($file);
$data[] = $neu;
file_put_contents('results.json',json_encode($data));
unset($data);
and now i want to echo these values seperately:
$string = file_get_contents("results.json");
$jsonObject = json_decode($string);
$jsonArray = json_decode($string, true);
echo $jsonObject->Produkt->Produktkategorie . " and " . `$jsonArray['Produkt']['MaxBreite'];`
but this only throws me following errors:
for the object: Notice: Trying to get property of non-object in
for the array: Notice: Undefined index: Produkt in
this is the complete json file:
["{\"Produkt\":{\"Produktkategorie\":\"TestArtikel\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Ecke\"},\"Formen\":{\"FormRund\":\"true\",\"FormEllipse\":\"true\",\"FormRechtQuad\":\"true\"}}}"]
could you help me please?
When you posting the data, maybe you have to set the datatype.
dataType: 'json'
$.ajax({
url: 'speichern.php',
type: 'post',
dataType: 'json',
success: function (data) {
},
data: {data:jsondata}
});
And in your php file, you could get the json data like following.
$json=json_decode(stripslashes($_POST['data']), true);
Hope it helps you.
You need to decode the json two times because the way you have it in the file. Try this:
$json = file_get_contents('results.json');
$json = json_decode($json, true);
$json = json_decode($json[0], true);
echo $json['Produkt']['Produktkategorie'];
Simply replace your last line with
echo $jsonObject->Produkt->Produktkategorie . " and " . `$jsonArray['Produkt']['Optionen']['MaxBreite'];
So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")
Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this
If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}
I have the following php:
1) echo json_encode(array('message' => 'Invalid Login Details: '.$user));
I also have the following:
2) $row = mysql_fetch_assoc($result);
echo(json_encode($row));
Now consider the following jQuery:
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
})
This succeeds for (1) but not for (2). This is obviously because jQuery expects a php response containing a message variable. (2) does not conform to this...I don;t know how to make this work as I am using different methods for creating the arrays...
How can I make $row in the php compatible with the data.message in the jQuery?
try:
$data = array();
$data["message"] = "Valid request";
$data["row"] = mysql_fetch_assoc($result);
echo(json_encode($data));
message = row:
$data = array();
$data["message"] = mysql_fetch_assoc($result);
echo(json_encode($data));
or two line solution (inspired by val):
$row = mysql_fetch_assoc($result);
echo(json_encode(array("message" => $row)));
Try
$row = mysql_fetch_assoc($result);
echo(json_encode(array('message'=>'I am the message','result'=>$row));
Then to answer your second question on the comments something similar to this could show the information ....
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
var html = '';
for(var i = 0; i<data.result.length;i++){
html +='<div>'+data.result[i].fname+'</div>';
}
$('#result').html(html);
}
})
ofcourse you need to edit it abit where applicable .
i believe you don't have $row['message'] from mysql_fetch_assoc.
you have to explicitely define the message key on the array before json_encode.
$row = mysql_fetch_assoc($result);
$row['message'] = 'Hello '.$row['username'];
echo(json_encode($row));