Some of the records I'm bringing back from the database include an apostrophe.
Various records have a name like the following:
CC CHÂTEAU D'IF
Inspecting the element, the data-attribute looks like this:
data-vesselname="CC CHÂTEAU D" IF'
I need the data-attribute to look like this:
data-vesselname="CC CHÂTEAU D'IF"
Here is the ajax call:
$.ajax({
url: 'api/searchVoyageInfo.php',
type: 'POST',
data: '',
dataType: 'html',
success: function(data, textStatus, jqXHR){
var jsonObject = JSON.parse(data);
var table = $('#example1').DataTable({
"data": jsonObject,
"columns": [{
"data": "",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
{
$(nTd).html("<a href='#' title='Edit Account' class='modAccount'
data-vesselname='"+oData.VESSEL_NAME+"'>Edit</a>");
}
},
{ "data": "ANOTHER_COLUMN" },
{ "data": "ANOTHER_COLUMN" },
// SEVERAL MORE COLUMNS
]
});
I removed a lot of code that wasn't necessary for this question. You can see the data-vesselname attribute above. The problem seems to occur there.
I tried to do the following:
data-vesselname='"+escape(oData.VESSEL_NAME)+"'
But upon inspecting the element, I see this:
data-vesselname="CC%20CH%C2TEAU%20D%27IF"
You need to escape the quotes in the string you append. You can either do this manually, or you can let jQuery do it for you:
"fnCreatedCell": function(nTd, sData, oData, iRow, iCol) {
$('<a />', {
'href': '#',
'title': 'Edit Account',
'class': 'modAccount',
'data-vesselname': oData.VESSEL_NAME,
'text': 'Edit'
}).appendTo(nTd);
}
Related
I need your help. I'm trying to put an autocomplete on dynamically create text input but I have got some problem. I would like to use the JSON file because the ajax request took 1/2 sec and for my use it's too much.
Here is the code:
$(document).on('keydown.autocomplete',"[id$=_buy_mod]",function() {
$(this).autocomplete({
source: function(request,response) {
$.ajax({
ttpe: "GET",
url: "js/articoli.json",
data: {
term: request.term
},
dataType:'json',
dataFilter: function(data) {return data;},
success: function(data) {
response($.map(data,function(product) {
return {
label: product.label,
value:product.value
};
}))
},
})
},
minLength: 1,
select: function( event, ui ) {
var localid = $(this).attr('id');
var numerolocal = localid.match(/\d+/);
console.log(numerolocal);
$(this).val(ui.item.label);
$("[id$="+numerolocal+"_buy_id_mod]").val(ui.item.value)
return false;
}
});
Actually timing is good but autocomplete is not filtering data and it show me all possible words.
Here is the json file
[{"value": "1","label": "Panasonic Lumix L1"},
{"value": "10","label": "Sigma 17-50mm f 2.8 OS Canon"},
{"value": "11","label": "Canon 1000D"},
{"value": "1100D","label": "Canon 1100D"}
-------
How can I solve?
I am trying to create a dashboard that will show some data from a database. Right now I am using a separate JSON encoded file named "data.php". I am using a jQuery Ajax request for this data to populate a Chart.js chart.
I have also been following an example similar to this
At the moment I am running into an issue seen here on my app.js file:
$(document).ready(function(){
$.ajax({
url: "http://{redacted ip}/swordtest/data.php",
method: "GET",
success: function(data) {
//var myData = $.parseJSON(data);
console.log(data);
var teamid = [];
var teamName = [];
var ticketCount = [];
for (var i in data) {
teamid.push("ID " + data[i].id);
teamName.push(data[i].name);
ticketCount.push(data[i].count);
}
console.log(data);
var chartData = {
lables: teamName,
datasets: [
{
label : 'Teams',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 0.75, 1)',
hoverborderColor: 'rgba(200, 200, 200, 0.75, 1)',
data: ticketCount
}
]
};
var ctx = $("#mycanvas");
var myDoughnutChart = new Chart(ctx, {
type: 'bar',
data: chartData
});
},
error: function(data) {
console.log(data);
}
});
});
What is happening though is that when I try to loop through the JSON object to separate the id's, names of the teams and amount of tickets, it will loop through the id continuously and give me this:
teamid = (1) ["ID undefined", "ID undefined"]
It will also add one and keep saying undefined. When I put breakpoints in the code it seems to only loop through the id as well. Any sort of help would be greatly appreciated. Thank you!
UPDATE
one thing to mention is that the data that I am getting from my data.php is a little different looking than the example I am working from (the link mentioned above). when I print the data it comes in this format:
data = "{"playerid":"1","score":"10"},{ "playerid":"2","score":"40"},{ "playerid":"3","score":"20"},{ "playerid":"4","score":"9"},{ "playerid":"5","score":"20"}"
Where in the example it looks like:
[{"playerid":"1","score":"10"},{ "playerid":"2","score":"40"},{ "playerid":"3","score":"20"},{ "playerid":"4","score":"9"},{ "playerid":"5","score":"20"}]
Different with brackets and without. I had a friend just try taking out the double quotes, replacing them with single quotes and wrapping the whole JSON in brackets. It seemed to start working then. I am guessing it has something to do with the way the JSON is getting formatted in my data.php.
Try to add the dataType property to the object literal that is the argument of the ajax() function. As you are getting a JSON from PHP, the property should have "json" as its value.
$.ajax({
url: "test.php",
method: "GET",
dataType: "json",
success: function(data) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("AJAX ERROR",textStatus,errorThrown,jqXHR);
}
});
I tested with this PHP file.
test.php
<?php
echo '[{"id":"1", "name":"John Doe", "count":"7"},{"id":"2", "name":"ABC", "count":"5"},{"id":"3", "name":"XYZ", "count":"29"}]';
?>
I am having trouble sending $_POST data via jQuery Ajax. I have read over everything I can find regarding the matter and still I am getting nowhere. I have even gone back to very basic data and still nothing, the JSON data has been validated using the JSON validate site. For the life of me I cannot echo/print_r/var_dump or get access to any data.
My JavaScript:
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(){
alert("success");
console.log(content);
window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
});
My PHP:
<?php
if(isset($_POST['data'])) {
$json = stripslashes($_POST['data']);
var_dump(json_decode($json, true));
} else {
echo "No Data";
}
?>
So I do get the alert("success"), and then get redirected to test.php
once at test.php I get the echo "No Data".
Thanks in advance for any help with this issue.
The reason is you are using window.location to redirect to the PHP file (without any post data) instead of posting the form on test.php.
You should either post the form without ajax on test.php.
Or use the response from test.php in your success function.
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(response){
alert("success");
console.log(response);
//window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
You are passing data as a string to ajax file. Please use JSON.stringify(conten) to pass data as a json format in ajax file.
use
data: {data: JSON.stringify(content)}
in place of
data: {data: content}
Use:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
Then access each field as follows:
$field1 = #$request->field1Name;
$field2 = #$request->field2Name;
etc..
EDIT:
Well, the first part of the answer is still valid.
I've tried your code and slightly modified it on my machine, and i was able to access the whole data as you will see below:
Javascript: removed the square brackets from the outside of your JSON and removed the curly brackets from the 'data' part of the ajax since they are not necessary
as you can see, i've also added the "data" to the success function so i can debug the response from test.php better
$(document).ready(function(){
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: JSON.stringify(content),
cache: false,
success: function(data){
alert(data);
console.log(content);
},
error:function(){
alert('ajax failed');
}
});
});
});
PHP:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$field1 = #$request->id;
echo $field1;
and $field1 is echoed as "21", the correct answer
You can apply this to your code and check also.
Thanks everyone for the help I have managed to figure it out with the help of each of you.
I needed to create in the test.php file a, $json = array(), and then populate the array, $json[] = json_decode($_POST['data']);
that then allowed me to place the contents in a JSON file.
here is the php code:
<?php
$json = array();
if($_POST['data']) {
$json[] = json_decode($_POST['data']);
file_put_contents("../JSON/test.json",json_encode($json));
} else {
echo "No Data";
}
?>
and as long as the file "JSON/test.json" exists then it will write the JSON passed from the JS.
I would like to note:
without the JSON.stringify(content); the data is NULL so thank you # Rahul Patel for making sure this was being applied.
the JSON data is valide according to the JSON validate site.
also just for keeps sake the JS code:
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: JSON.stringify(content)},
cache: false,
success: function(){
alert("JSON Updated");
},
error:function(){
alert('ajax failed');
}
});
});
I am attempting to return a json encoded array to JS from PHP and i've done so many times before but now i'm getting a weird error. I am successfully getting the data and it's displaying the array in chrome. However, I cannot get it to enter the AJAX success function if I specify the dataType: 'json'. If I remove the dataType and use var parsed = JSON.parse(data); it will enter the success function but it will throw an unexpected type error. Please help.
Chrome output:
[
{
"fullURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s912/2010raptor_firstdrive002_opt.jpg",
"thumbURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s128-c/2010raptor_firstdrive002_opt.jpg",
"location": "",
"caption": "",
"tags": "",
"program_instance_id": "a0Ji0000001pPO6EAM"
},
{
"fullURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s912/220px-Microchip_PIC24HJ32GP202.jpg",
"thumbURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s128-c/220px-Microchip_PIC24HJ32GP202.jpg",
"location": "",
"caption": "",
"tags": "",
"program_instance_id": "a0Ji0000001pPO6EAM"
}
]
PHP
$arr = array();
foreach($photoURLS as $photo)
{
$arr[] = $photo;
}
}
echo json_encode($arr);
JS
$.ajax
({
async: "false",
type: 'POST',
data: {action: 'var1', albumName: 'var2'},
dataType: 'json',
url: '/controller/function',
success: function(data)
{
//alert($.isArray(data));
$.each(parsed, function(i, index) {
alert(index.fullURL);
});
}
});
So I worked the code back and think this solution might work for you.
$.ajax({
async: "false",
type: 'POST',
data: {
action: 'var1',
albumName: 'var2'
},
dataType: 'json',
url: '/controller/function',
success: function(data) {
$.each(data, function(index, element) {
console.log(index);
console.log(element.fullURL);
console.log(element);
});
}
});
I can't test the ajax event however I have tested out the json you provided with the each loop and it seams to work. LINK TO FIDDLE
var data = [{
"caption": "",
"fullURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s912/2010raptor_firstdrive002_opt.jpg",
"location": "",
"program_instance_id": "a0Ji0000001pPO6EAM",
"tags": "",
"thumbURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s128-c/2010raptor_firstdrive002_opt.jpg"
}, {
"caption": "",
"fullURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s912/220px-Microchip_PIC24HJ32GP202.jpg",
"location": "",
"program_instance_id": "a0Ji0000001pPO6EAM",
"tags": "",
"thumbURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s128-c/220px-Microchip_PIC24HJ32GP202.jpg"
}];
$.each(data, function (index, element) {
console.log(index);
console.log(element.fullURL);
});
also good news is that your json is 100% valid so what is being passed back seams correct. Hope this helps
Maybe you need to send the correct HTTP header with your response.
See here: https://stackoverflow.com/questions/267546/correct-http-header-for-json-file
The variable parsed at your $.each function is not defined. you should use data instead of parsed as data is the variable at your success callback function.
$.each(data, function(i, index) {
alert(index.fullURL);
});
What I want to do is : If user has only one credit card number in database then display text field onto page which I did successfully but if user's multiple credit card numbers has stored in my database then instead of displaying text field I want to display all his credit card numbers into the combo box.
Following is the ajax response I am getting:
{
"fname": "abc",
"lname": "xyz",
"creditCardInfo": [
{
"creditCardNumber": "378282246310005",
"creditCardType": "AX",
"securityCode": "1234",
"expirationDate": "2020-02-01"
},
{
"creditCardNumber": "6011000990139424",
"creditCardType": "DS",
"securityCode": "321",
"expirationDate": "2030-12-01"
}
],
"creditCardNumber": "6011000990139424",
"creditCardType": "DS",
"creditCardCVC": "321",
"creditCardExpirationMonth": "12",
"creditCardExpirationYear": "2030"
}
(Note : The above response containing all testing credit card numbers and cvc code)
I tried by using jquery each loop but able to do it.
Following is my code:
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['HOST']; ?>"+action,
dataType: 'json',
data: formdata,
success: function(data)
{
var userinfo = eval(data);
alert(userinfo);
if(userinfo['msg'] == 'fail'){
$(".usrmsg").show();
$(".validate").hide();
}
else{
if(!$("#fname1").val()) $("#fname1").val(userinfo['fname']);
if(!$("#lname1").val()) $("#lname1").val(userinfo['lname']);
if(!$("#billingCity").val()) $("#billingCity").val(userinfo['billingCity']);
if(userinfo['creditCardInfo']){
$('#creditCardComboBox').show();
$('#creditCardTextField').show();
// $(userinfo['creditCardInfo']).each(function(index) {
// alert(index + ': ' + $(this).text());
// $("#creditCardNumber option[value="+index['creditCardNumber']+"]").attr("selected", "selected");
// });
$("#creditCardType option[value="+userinfo['creditCardInfo']['creditCardType']+"]").attr("selected", "selected");
$("#creditCardExpirationMonth option[value="+userinfo['creditCardInfo']['creditCardExpirationMonth']+"]").attr("selected", "selected");
$("#creditCardExpirationYear option[value="+userinfo['creditCardInfo']['creditCardExpirationYear']+"]").attr("selected", "selected");
}
if(!$("#billingFirstName").val()) $("#billingFirstName").val(userinfo['fname']);
if(!$("#billingLastName").val()) $("#billingLastName").val(userinfo['lname']);
if(!$("#creditCardCVC").val()) $("#creditCardCVC").val(userinfo['creditCardCVC']);
}
}
});
Need Help.
Thanks in advance.
Guess this will be your code. use jquery hide/show/ use .innerHtml tag to show your content.
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['HOST']; ?>"+action,
dataType: 'json',
data: formdata,
success: function(data)
{
//Check the length of the json array
var creditcardinfo = data.creditCardInfo
do
{
if(creditcardinfo.length==1){
$('#creditCardTextField').show();
$('#creditCardComboBox').hide();
//Set value of creditcardText
$('#creditCardTextField').val(creditcardinfo[i].creditCardNumber);
}else if(creditcardinfo.length>1){
$('#creditCardComboBox').show();
$('#creditCardTextField').hide();
//ASSUMING YOU Are using <select> tag
var newOption = $('<option>');
newOption.attr('value',creditcardinfo[i].creditCardNumber).text(creditcardinfo[i].creditCardNumber);
$('#creditCardComboBox').append(newOption);
}
}while (i<creditcardinfo.length);
}
});