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);
}
});
Related
I'm trying to validate an designation name with a remote rules.
On first time form submit by entering test value, form submitted and value bind by ajax. but after second time without refresh page i m trying to submit form by adding same value test which i added. i m not getting error for existing name.
here is the js code
$("#designationaddedit").validate({
rules: {
designation_name: {
required: true,
},
designation_copy_name: {
remote: {
url: base_url + 'Designation/designation_name_exists',
type: "post",
data: {
designation_copy_name: function() {
console.log("1");
return $( "#designation_copy_name" ).val();
}
}
}
},
},
messages: {
designation_name: {
required: "Enter Designation name"
},
designation_copy_name: {
remote: 'Designation name is already exists.'
},
},
});
$(document).on('submit', '#designationaddedit', function(event) {
event.preventDefault();
var designation_id = $('#designation_id').val();
var designation_name = $('#designation_name').val();
var action = $('#action').val();
var table = $('#designationTable').DataTable();
var info = table.page.info();
var currentpage = info.start;
if ($("#designationaddedit").valid()) {
$('.preloader').show();
$.ajax({
url: base_url + 'designation/add',
type: 'POST',
dataType: 'json',
data: { submit: 1, designation_id: designation_id, designation_name: designation_name, action: action },
success: function(response) {
$('.preloader').hide();
if (response.success == 1) {
$("#designation_model").modal('hide');
} else {
}
}
});
}
})
below code fixed my issue. I hope it's help you.
remote: { url: "http:url.com", type: "post", data: { USER_ID: userid }, async: false, // set async = false }
My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).
Output of test.php
[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]
jQuery script:
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
alert(data);
},
processResults: function(data) {
return {
results: $.map(data.suggestions, function(obj) {
return {
id: obj.key, text: obj.value
}
})
};
}
}
});
I have been searching and checking all other solutions. It it not working for me. I'm stuck.
Update: jQuery script so far
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
placeholder: "Voer uw postcode in..",
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
return {
ajax_call: 'addressZipcodeCheck_BE',
zipcode: '1200'
};
},
processResults: function(data) {
alert(data);
correctedData = JSON.parse(data)[0]suggestions;
alert(correctedData);
return {
results: $.map(correctedData, function(obj) {
return {
id: obj.key,
text: obj.value
}
})
};
}
}
});
Here is a working fiddle for your example.
I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.
Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.
Run this code in your JQuery enabled browser console and you will undestand.
var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;
Also check this answer to see how a proper response should look like.
Updated answer:
Sending additional data to back-end:
$('#billing_postcode_gemeente').DataTable(
{
......
"processing" : true,
"serverSide" : true,
"ajax" : {
url : url,
dataType : 'json',
cache : false,
type : 'GET',
data : function(d) {
// Retrieve dynamic parameters
var dt_params = $('#billing_postcode_gemeente').data(
'dt_params');
// Add dynamic parameters to the data object sent to the server
if (dt_params) {
$.extend(d, dt_params);
}
}
},
});
Here dt_params is your additional parameter (the zipcode
that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.
There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code) pair to the dt_params key in your request JSON:
function filterDatatableByZipCode() {
$('#billing_postcode_gemeente').data('dt_params', {
ajax_call: 'addressZipcodeCheck_BE',
zip_code : $('#some_imput_box').val()
});
$('#billing_postcode_gemeente').DataTable().destroy();
initDatatable();
}
Try this way
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return data.items;
},
cache: true
},
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
I am developing one website where i insert data through ajax in Json format to php page then after decoding it send to mysql database,but if my string contains < > || & ' " characters then my web page gives php error.so how should i proceed further. It doesn't allow for inserting some special characters ..
var obj = {"comment": commentText, "postID": postID};
var commentData = 'commentData=' + JSON.stringify(obj);
$.ajax({
type: "POST",
url: addNewCommentsUrl,
datatype: 'json',
data: commentData,
cache: false,
beforeSend: function() {
// $(document.body).off('click','.postComment');
},
success: function(result) {
commentBox.val("");
commentHolder.append(result);
// jQuery("#all-posts").masonry('reloadItems');
jQuery('#all-posts').masonry('layout');
var count = parseInt(parent.find("#commentContainer").text());
parent.find("#commentContainer").html(++count);
// $(document.body).on('click','.postComment');
}
});// end of ajax
at php side
$recievedData = $_POST['commentData'];
$recieveddatajson = json_decode($recievedData);
$lastCommentID = $recieveddatajson->{'commentID'};
$parentPostID = $recieveddatajson->{'postID'};
Okay, I see what you are doing. You don't need to do that. Here's a cut down version of your problem, showing you how to achieve ajax post:
test.php
<?php
// Handle Post
if (count($_POST))
{
echo "You posted\r\n";
print_r($_POST);
exit();
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "test.php",
data: { "comment": "hello world", "postID": 1234 },
// data: { "comment": commentText, "postID": postID },
success: function(result) {
alert("Server Said:\r\n" + result);
}
});
});
</script>
Outputs:
So when the request occurs, data fields and their values are available in php like this:
$comment = isset($_POST['comment']) ? $_POST['comment'] : '';
$postID = isset($_POST['postID']) ? $_POST['postID'] : '';
Hope this helps.
I am using the Kendo UI Grid. Basically, what I want to do is bind the grid on remote data which are sent on json format and be able to edit it.
The Grid receive the data and display it as I want. However, when I want to edit a cell, the request received in the php file is null, and the type sent is "create" while I would like it to be an "update".
Here is the code used:
-the javascript contains the grid declaration
$(document).ready(function() {
var dataSource = new kendo.data.DataSource({
batch: true,
transport: {
read: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=read"
},
update: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=update"
},
create: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=create"
},
destroy: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=destroy"
}
},
schema: {
data: function(result) {
return result.Result || result.data;
},
model: {
id: "bbmindex",
fields: {
totalvente: {type: "number"}
}
},
total: function(result) {
return result.totalData || result.PageSize || result.length || 0;
}
}
});
var param = {
columns: [
{
field: "naturetravaux", title: "nature travaux"
},
{
field: "totalvente", title: "total vente"
}
],
selectable: 'multiplerows',
editable: true,
toolbar: ["create", "save", "cancel", "destroy"],
dataSource: dataSource
};
$("#grid").kendoGrid(param);
});
-the php script send the data to the dataSource
<?php
header('Content-Type: application/json');
$request = json_decode(file_get_contents('php://input'));
$type = $_GET['type'];
$result = null;
if ($type == 'create') {
some code
} else if ($type == 'read') {
some code which send the data
} else if ($type == 'update') {
some code
}
echo json_encode($result);
?>
any idea about what is wrong here?
Any help would be much appreciated,
thank you in Advance
Martin
If your server receives a create is because the idof the edited record is 0, null or undefined. Please check that you get from the server a field called bbmindex and is not 0
You expect the request to be posted as JSON however the Kendo DataSource doesn't do that by default. You need to use the parameterMap option and make it return JSON:
parameterMap: function(data, type) {
return kendo.stringify(data);
}
i want to save data in database by a button click.here is my code,in Firefox it do not work it show empty alert and data do not saved in table.
$("#Save").click(function () {
var price = $("#price").val();
var agent_1_id= $("#agent_1_id").val();
var type = $("#type").val();
$.post("ajax_files/myDeals.php",
{
price: price,
agent_1_id: agent_1_id,type:type
},
function(data) {
alert(data);
});
});
click event fires and this function calls. Here is code on myDeals.php to save in table..
$price = $_REQUEST['price'];
$agent_1_id = $_REQUEST['agent_1_id'];
$type = $_REQUEST['type'];
mysql_query('insert query here');
echo "Saved Successfully ";//this is not alerted?
Try the sample sending the data as an object:
function end_incident() {
$.ajax({
type: "POST",
url: "http://www.example.co.uk/erc/end_incident.php",
data: { name: "Daniel", phone: "01234123456" },
success: function(msg){
alert('Success!');
}
});
};