I have an AJAX call that makes my JSON look this in my JSON file:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
But I would like to have it like this (and this was before I changed my AJAX call with: id: getUrlParameter('id'):
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
The only thing I want to add is the "id": "new", but when I do so (with id: getUrlParameter('id') it gets the id, but it messes up my code.
This is my AJAX call (my JSON starts looking like the first piece of code when I use this)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: $('#my_form').serialize()
},
dataType: 'json',
}).done(function(response) {
});
});
}
How could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my AJAX call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id').
edit: Since someone said it could be my php code.. here is my php code:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>
you can use parse_str($str, $output); it will help you achieve what you need.
Note that parse_str takes two parameters, the first one is the string (get Parameters), second one is the array to return the result on. you can use the below code
parse_str($str, $output);
echo json_encode($output);
The issue is how you process formData parameter. serialize() is building url encoded string, however you want key-value pairs. Try this:
$("#my_form").on("submit", function(event) {
event.preventDefault();
var myData = {id: getUrlParameter('id')};
for (var pair of formData.entries()) {
myData[pair[0]] = pair[1];
}
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: myData,
dataType: 'json',
}).done(function(response) {
window.location = 'index.php';
});
});
}
Related
I'm using a $.post() to push data to a php file. But the $_POST is empty when I make a var_dump of it.
JS script :
$('#Notes').on("click", function (e) {
e.preventDefault();
let $id = $(document).getUrlParam("varname");
let $text = $(this).attr('data');
let $notes = prompt("Modifier la note", $text);
console.log($text, $id, $notes);
if ($notes !== null || $notes !== "") {
$.post(
'../buckets/update_note.buckets.php',
{
id: $id,
notes: $notes,
},
function (data) {
console.log('Data Id : ',data.id);
console.log('Data Name : ',data.name);
})
.then(r =>{
location.replace('../buckets/update_note.buckets.php');
})
}
in php file :
<?php
var_dump($_POST);
var_dump($_GET);
The 1st console.log in js show me the values of the 3 variables but the console.log in the callback show me undefined. But I see in the network debugger :
Form Data
id: xxxx
notes: xxxx
Any idea ?
I believe, data will be text in your case. You need to use json_encode() in you php to print complex objects. Then in your JS you can use JSON.parse() to restore object or define application/json content type in your POST query. Something like:
// php
$json = json_encode([
'post' => $_POST,
'get' => $_GET
]);
// js
function (response) {
const data = JSON.parse(response);
}
You can try in this way.
JQuery CODE
$('#Notes').on("click", function (e) {
e.preventDefault();
let $id = $(document).getUrlParam("varname");
let $text = $(this).attr('data');
let $notes = prompt("Modifier la note", $text);
console.log($text, $id, $notes);
if ($notes !== null || $notes !== "") {
$.post(
'../buckets/update_note.buckets.php',
{
id: $id,
notes: $notes,
},
function (data) {
var data=$.parseJSON(data);
console.log('Data Id : ',data.id);
console.log('Data Name : ',data.notes);
})
.then(r =>{
//location.replace('../buckets/update_note.buckets.php');
})
}
PHP CODE
echo json_encode($_POST);
My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)
When I trying to return the inserted image as json I'm getting error like Cannot use in operator to search for length
Ajax code:
$("#imagesform").submit(function(){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content')
}
});
$.ajax({
url :"{{url('addImages/').'/'}}" + imagesProductId,
type: 'POST',
data:new FormData($("#imagesform").get(0)),
contentType:false,
processData:false,
success: function (data)
{
//alert(data);
//alert(json.parse(data));
$.each(data, function( index, value ) {
$("#insertedImages").append('<img src="'+value+'" width="75"
height="75" class="upload2"><br>');
alert(value);
});
},
});
return false;
});
Here the images get inserted into db.But while returning to the view and trying to display it with the div tag shows error..(specified above)
Controller:
public function addImages(Request $request,$imagesProductId)
{
$product = Product::create($request->all());
$filenames = array();
if (empty($request->images)) {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
$rules = [
'images'=>'required'
];
$validator = Validator::make($request->all(), $rules);
$result = $validator->fails() ? 'QCFailed' : 'QCVerified';
// echo($result);
foreach ($request->images as $photo) {
$filename = $photo->store('public/uploadedImages');
$filename = substr($filename,22);
$filenames[] = asset('storage/uploadedImages/'.$filename);
ProductsPhoto::create([
'product_id' => $product->id,
'productId'=>$imagesProductId,
'nonliveStatus' => $result,
'filename' => $filename
]);
}
return response()->json($filename);
}
This is my controller function for inserting array of images and I'm returning the same to the view and trying to append it using div tag.
Im so noob at this, been working with PHP and Js for like 4 months, sorry if im making a noob question, also, im a spanish speaker, sorry for english grammar fails you are going to read =[
Basically, this is my problem:
In this Php File i have some Vars and VarArrays, i need to send them to another one
//First PHP File - This one Search on DataBase, at the end, i have 5 vars, 2 of them are arrays
<?php
$var1 = '1';
$var2 = '2';
$var3 = '3';
$arr1 = array();
$arr2 = array();
//¿How to json_encode the 5 vars above?//
?>
In this one i need to catch the previus values
//Second PHP File
<?php
$newVar1 = $_POST['var1'];
$newVar2 = $_POST['var2'];
$newVar3 = $_POST['var3'];
$newArr1 = $_POST['arr1'];
$newArr2 = $_POST['arr2'];
?>
I think i have to do something like this, but how should i do it?:
$.ajax({
type: "POST",
url: "php/FIRSTFILE.php",
data: ????,
dataType: "json",
success:
function(respuesta)
{
$('#MainDiv').load('php/SECONDFILE.php', function(data) {
$(this).html(data);
});
$('#MainDivLabelVar1').val(respuesta.¿¿EncodeStuff??);
}
});
maybe you can encode your data like this
json_encode(array(
'var1' => '1',
'var2' => '2',
'var3' => '3',
'arr1' => array(),
'arr2' => array()
));
In this line you are sending values in POST to your php file:
data: {id: id, CAT: CAT},
So, if you need to receive data like (in file "second.php")
<?php
$newVar1 = $_POST['var1'];
$newVar2 = $_POST['var2'];
?>
You should send it by this:
$.ajax({
type: "POST",
url: "php/second.php",
data: {var1: 'value1', var2: 'value2'}
});
you could deocde the json string into object or array
$js_array = json_encode(array(
'var1' => '1',
'var2' => '2',
'var3' => '3',
'arr1' => array('a' => 'mobile', 'b' => 'PC'),
'arr2' => array('price' => 600, 'day' => 7)
));
$decode = json_decode($js_array, true); //decode into array
//you could use or seperate something you get back from json decode like this
foreach($decode as $key => $value) {
if(is_array($value)) {
foreach ($value as $k => $v) {
echo "$k => $v <br />";
}
} else {
echo "$key: $value <br />";
}
}
and the output:
var1: 1
var2: 2
var3: 3
a: mobile
b: PC
price: 600
day: 7
I'm using Bootstrap Typeahead with PHP to display a list from a database using source.php:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = $row['title'] . ',' . $row['id'];
}
// Return the json array
echo json_encode($array);
}
?>
You can see that I add both 'title' and 'id' to the array. All I want it to display in the typeahead is the title but I need the id for the links. Here is the JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + item.replace(/ /g, '-').replace(/\,/g,'/').toLowerCase() + "/";
return item;
}
});
In the line beginning document.location I replace the comma between the two values with a forward slash and it works e.g. /england/123/. But it's the typeahead display that shows it as England,123 rather than just England.
Any help would be greatly appreciated.
OK managed to get a result with the following:
PHP:
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = array('label' => $row['title'], 'id' =>$row['id']);
}
// Return the json array
echo json_encode($array);
}
JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "http://www.stubowker.com/amex/cms/source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.label] = object;
objects.push(object.label);
});
process(objects);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + map[item].label.replace(/ /g, '-').toLowerCase() + "/" + map[item].id +
"/";
return item;
}
});