I'm collecting some data from my page, storing the data in an array for multiple uses on the page, and sending a copy of the array via AJAX, storing the data in the database on a PHP page.
One piece of data I'm storing in the array is the output of a TinyMCE WYSIWYG editor, so it contains HTML, but have just found this to be a problem - I'll explain:
After entering one line of text in my WYSIWYG editor and I trigger my AJAX event, this is the JSON string displayed in my console and everything worked okay, the database was sent and stored:
{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>","keywords":""}
If I write two lines of text, this is the JSON string and was successful:
{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>\n<p>fgfgfdg</p>","keywords":""}
Now, if I write one line of text and press return and not type anything on the second line, I get the following which fails.
{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdgdfgdfgdfgdfg.</p>\n<p> </p>","keywords":""}
It seems broke my JSON output somehow. My PHP can't access the decoded array values, as there is no array. print_r(json_decode($json)) returns nothing. Can anybody help?
This is my HTML page with jQuery:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
var post_data = {};
post_data.id = post_id;
post_data.topic = topic;
post_data.title = title;
post_data.description = description;
post_data.content = tinyMCE.activeEditor.getContent();
post_data.keywords = keywords;
post_data = JSON.stringify(post_data);
save_post_request = $.ajax({
url: 'ajax/save-post.php',
type: 'POST',
data: "save_mode="+save_mode+"&post_data="+post_data,
dataType: 'text',
cache: false
});
</script>
This is my PHP page:
header('Content-type: application/json; charset=UTF-8');
$post_data = isset($_POST['post_data']) ? $_POST['post_data'] : null;
$post_data_arr = json_decode($post_data, true);
$post_id = $post_data_arr['id'];
$topic = $post_data_arr['topic'];
// others
$content = $post_data_arr['content'];
if (!$post_data_arr['id']) {
// fails here
// id is not accessible when the JSON contains <p> </p> in the 'content' item
}
This is what Firebug says:
You are placing the JSON into some URL Encoded data, but you are not URL Encoding it.
The & character has special meaning in URL Encoded data (it separates key/value pairs), so this means you are breaking the data.
Use the encodeURIComponent function to properly encode your data before adding it to the string:
data: "save_mode="+encodeURIComponent(save_mode)+"&post_data="+encodeURIComponent(post_data),
However, since you are using jQuery, you shouldn't be constructing your URL Encoded data by hand in the first place. jQuery can do it for you. Pass data an object instead of a string:
data: {
save_mode: save_mode,
post_data: post_data
},
Related
I'm rather new to terminology and coding in general, but I've tried to trim down my code, though it may still have redundancies. Thanks in advance for your understanding.
I'm using an ajax and php script to write some data to a file on the server called data.json. The script works fine, and opening the json file shows that it's indeed updated with the data. The json file simply contains an array of objects.
Here's the code that does this:
function writeData() {
$.ajax({
type : "POST",
url : "save.php",
async : true,
data : {
json : JSON.stringify(dataToWrite)
}
});
document.getElementById('success-box').innerHTML = "Data successfully written.";
};
...and the PHP:
<?php
$json = $_POST['json'];
$file = fopen('data.json','w+');
fwrite($file, $json);
fclose($file);
?>
The problem I'm having is this: The user can navigate to a separate HTML page, and can click a button to view the data in the json file in a nicely-formated way. This is done via another ajax script that reads the data. This latter ajax script doesn't seem to be able to "see" the newly updated json file. It instead loads the old version of the file, before it was updated with the first ajax script. I'm sure that this second ajax script is run after the above writeData() is finished, because it's actually on a separate HTML page entirely, which is loaded later, after the user clicks a button.
Here's the second ajax script that reads the data from the data.json file (it's on another, separate HTML page):
$.ajax({
type : "GET",
url : "http://eslquiz.net/ell_errors/data.json",
async : true,
dataType : 'json',
success : function(response) {
data = response;
document.getElementById('main').innerHTML = `
<div id='top-stuff'>
<button onClick='viewData()'>Reset Filter</button>
<button onclick="print2()">Print Worksheet</button>
</div>
<br>
<div id='left-column' class='column'></div>
<div id='right-column' class='column'></div>
`;
leftColumn = document.getElementById('left-column');
rightColumn = document.getElementById('right-column');
leftColumn.innerHTML = "<b>Sentences:</b> <br><br>";
rightColumn.innerHTML = "<b>Errors:</b> <br><br>";
//add the sentences and their errorTypes:
for (i=0; i<data.length; i++) {
var senBox = document.createElement('div');
senBox.className = 'box';
senBox.setAttribute('id', 'sen' + i)
senBox.innerHTML += data[i].text;
var errBox = document.createElement('div');
errBox.className = 'box';
errBox.setAttribute('id', 'err' + i)
errBox.innerHTML += data[i].errorType;
leftColumn.appendChild(senBox);
rightColumn.appendChild(errBox);
}
}
});
All of these files are hosted in the same directory on One.com.
The strange thing is that when I manually open the data.json file and edit its contents in any way (by deleting everything, for example), the next time the ajax call is made, it reads the version I just manually updated. This makes me think it might be something to do with the One.com server refreshing itself?
I tried adjusting the ajax between synchronous/asynchronous, and using cache: false, but these don't seem to affect anything.
I've searched around, and can't seem to find out what's going on here. Thanks for any guidance you could provide.
Thanks. I ended up using the following:
jQuery.ajaxSetup({
cache: false
});
I tried using this before, but for some reason it didn't work, not sure why. But it's working now! Thanks.
first, GET method can be cached by the browser.
second, Make sure the response is a json type
$.ajax({
type : "GET",
url : "http://eslquiz.net/ell_errors/data.json?rand_v=" + Matn.random(), // add a random try again
async : true,
dataType : 'json',
success : function(response) {
// Make sure the response is a json type
// console.log(typeof(response));
// console.log(typeof(JSON.parse(response)));
data = response;
// ...
I have a form and an array containing some data. I am trying to post both these objects to my php script. The code I am using to post the form and array is shown below:
var json_data = JSON.stringify(data_vendor); //array to be posted
$.ajax({
url: '/crm/inventory/add_purchase_order.php',
type: 'POST',
data: {data_vendor:json_data,form_data:$("#purchase_orderform").serialize()},
dataType: 'json',
In the PHP script I am able to decode the array using the following :
$vendor_codes = json_decode($_POST["data_vendor"],true);
The form contains several fields/inputs one of which is called "order_quantity" . I am trying to retrieve this value using:
$order_quantity = $_POST["order_quantity"];
The data read shows up as NULL.
(i) Is the method used correct for posting multiple objects/strings correct?
(ii) Is the method used to retrieve the form inputs correct?
Usually when you use serialize() that is all you send because it is a urlencoded string. Then the form control names are available as keys in $_POST
But you currently only have 2 keys available to $_POST ... $_POST["data_vendor"] and $_POST["form_data"]
$_POST["form_data"] is a urlencoded string which you did with serialize() so it also needs to be decoded now manually
Try
$formData = urldecode($_POST["form_data"]);
$order_quantity = $formData ['order_quantity'];
To validate this just do a dump of $_POST["form_data"] and you will see that it is a string...not array
I am sorry if this is a duplicate question. I have searched for an answer but nothing seems to work.
I am trying to send quite a large JSON object to a PHP file via POST.
This is my JavaScript code :
var grid =
{
"user": 1,
"grid": JSON.stringify(hz),
"week": WEEK,
"AP": AP,
"X_VAL": X_VAL,
"Y_VAL": Y_VAL
};
grid = JSON.stringify(grid);
$.ajax({
url:"php/saveGrid.php",
type: "POST",
data : "g="+grid,
success: function (data, textStatus, jqXHR)
{
console.log(data);
}
});
This is my PHP code :
$g = stripslashes($_REQUEST["g"]);
echo $AP = $g->AP;
But this returns an error which says :
Trying to get property of non-object
What am I doing wrong?
Your primary problem is that you are trying to treat a string of JSON as if it were a PHP object.
You need to parse it first.
$g = stripslashes($_REQUEST["g"]);
$g = json_decode($g);
echo $AP = $g->AP;
You also have some secondary issues.
You failed to URL encode the JSON, so if it contains characters with special meaning in URLS, it will break.
data : "g="+grid,
should be:
data : { g: grid },
You should not need to run stripslashes over input from $_REQUEST/POST/GET.
If you don't have magic quotes turned on, then it could break the incoming data if it contains slashes.
If you do have magic quotes turned on, then you should turn them off or upgrade to a modern version of PHP (which wouldn't support them).
Nesting JSON inside JSON is silly. It bloats the data and makes it more work to read.
"grid": JSON.stringify(hz),
should be:
grid: hz,
$_REQUEST could get data from the query string, or the request body, or a cookie. You know it is coming in the request body so just use $_POST to remove the ambiguity.
You need to decode the json object then can use it as an array. Try, json_decode. Like,
$g = stripslashes($_REQUEST["g"]);
$json_de=json_decode($g);
echo $AP = $json_de['AP'];
Or if you want to see the full array then use,
print_r($json_de);
Hope this will help you.
Here is a script.
It provides some select inputs which allow picking from various types of options. When the submit button is pressed it records the data in mats and pushes the mats array into an array called materialsUsed. Everytime the submit button is clicked a new array is added in materialsUsed.
I want to know how to send the materialsUsed array through a URL to php to extract the data there and insert it into an array created in PHP.
var mats = [name= "", thick= "", size= "", quantity= 0, price= 0];
mats.name = document.getElementById("mat").options[document.getElementById("mat").selectedIndex].value;
mats.thick = document.getElementById("thick").options[document.getElementById("thick").selectedIndex].value;
mats.size = document.getElementById("size").options[document.getElementById("size").selectedIndex].value;
mats.price = parseFloat($('#priceto').val()).toFixed(2);
mats.quantity = parseInt($('#quant').val());
materialsUsed.push(mats);
If you would like to simply load them as GET values into the URL just set them directly in the URL using location.href. Then simply use $__GET (IE: $__GET['mat']) in PHP to grab values.
var baseURL = "http://yourdomain.com";
window.location.href = baseURL + "?mat=" + mats.name + "&thick=" + mats.thick etc...
First you have to properly prepare your mats array and convert materialsUsed array into JSON format. Then you can call an ajax function like below, to send it to the php script.
var jsonString = JSON.stringify(materialsUsed);
$.ajax({
type: "GET",
url: "your_script.php",
data: {data : jsonString},
success: function(){
alert("Successfully sent the data!");
}
});
From the your_script.php file, you can perform this to extract the array.
$data = json_decode(stripslashes($_GET['data']));
Important
When using GET method, the amount of the data (length of url) is
limited. So, if your materialUsed array is too huge, you should use
POST method instead.
I think what you're looking for is making an ajax call to your php script providing your js array as its data.
You should listen for the form submission event in your javascript and launch an AJAX call to your PHP script providing your array. You may send your array via the URL (query string) using a GET or in the request body using a POST (that's an option you specify in your AJAX call). Then you would just retrieve your array in your php script an do whatever you want with it.
I suggest you read more on form submission events and AJAX calls in javaScript.
Quick hint : if you have the possibility to do so, try using jQuery as AJAX is way easier to use with jQuery.
You are trying to use associative array, but it's not possible in Javascript as far as I know.
I'd say the best way to do that is creating a object, parsing to json and sending to php. Does't look that hard.
My ASP.NET MVC4 controller returns an XML string, when we pass it a SERIAL. Now when I send a request using C#, it works fine, XML string comes back , and looks like
<CalculatedCode> 12312312 </CalculatedCode>
I need to also do it via jquery like below. Query is working but it is returning an XMLDocumentObject , instead of an xml string. I looked at Jquery documentation to try to parse it, but I'm a jquery noob and I'm sure I'm making an error in the code.
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
dataType: 'xml',
data: { SERIAL: serial}, //SERIAL comes from a textbox
success: function (responseData) {
//Code below is messed up, it simply needs to find the CalculatedCode tag
//and extract the value within this tag
xmlDoc = $.parseXML(response);
$xml = $(xmlDoc);
$thecode = $xml.find("CalculatedCode");
// ToDo: Bug stackoverflow members with this noob question
}
});
Thank you very much :)
It's already parsed when you set the dataType to XML, so no need for $.parseXML, but if the element is a root element, find() doesn't work, as it only finds children, you'll need filter()
$xml = $(responseData);
$thecode = $xml.filter("CalculatedCode").text();
an trick that gets the element either way is to append the xml to another element :
$xml = $('<div />').append(responseData);
$thecode = $xml.find("CalculatedCode").text();