show php json data into jquery ajax - javascript

I'm very new in this topic.I have a Json result something like this :
{
"span": " 1",
"numcard": "12",
"chan": " Yes",
"idle": "Yes",
"level": "idle ",
"call": "No ",
"name": ""
}
How can I show all the json data using a ajax .I currently have this code written up and although i am getting the data its not quite working the way i want it to be.
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$.each(data, function(key, val) {
$("#span").val(val.span);
$("#numcard").val(val.numcard);
$("#chan").val(val.chan);
$("#idle").val(val.idle);
$("#level").val(val.level);
$("#call").val(val.call);
$("#name").val(val.name);
});
}
}
});
});
<input id="span" name="span" value="" />
<input id="numcard" name="numcard" value="" />
<input id="chan" name="chan" value="" />
<input id="idle" name="idle" value="" />
<input id="level" name="level" value="" />
<input id="call" name="call" value="" />
<input id="name" name="name" value="" />
when I try to alert ,example alert(val.span) it keep showing undifined .Does anyone with experience in this topic and see if any problem about my code? Any help would be greatly appreciated.Thank you .

You are returning a single set of values so you do not need the each within your success handler. Try this:
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
In theory, you shouldn't need the data != "" check as your server side code should not be allowed to return an empty response for when the result of the request is 200 OK.

Try this:
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
});
});

should be
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}

Related

Shopify Trying to update a customer

I'm trying to create a view where my customer can update his personal info (like First Name, Last Name, email, ect) using Liquid/JS, but I have failed epicly.
The nearest point that I have reached is this post where they use a form and some AJAX to update but I'm getting code 500. This is the code that I'm using (based on that).
<form action="/a/custmeta" method="POST" id="custmeta">
<input type="text" name="customer[id]" value="{{ customer.id }}" />
<input type="text" name="customer[first_name]" value="{{ customer.first_name }}" placeholder="namespace1.key1" />
<input type="text" name="customer[last_name]" value="{{ customer.last_name }}" placeholder="namespace2.key2" />
<input type="submit" />
</form>
<script>
$('form#custmeta').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: $(this).serialize(),
url: '/admin/customers/#{{ customer.id }}.json',
success: function (data) {
var formValid = (data.status === 'OK');
if (formValid) {
var msgs = '';
for (var i=0;i<data.messages.length;i++) {
msgs += '-- ' + data.messages[i] + '\n';
}
if (msgs > '') {
alert('SUCCESS WITH MESSAGES:\n\n' + msgs);
}
else {
alert('SUCCESS!');
}
}
else {
alert('Status: ' + data.status + '\nMessage: ' + data.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('AJAX or Server 500 error occurred');
}
});
return false;
});
</script>
found this other post where you could do it using the API but dont know how to use it.
Any help?

selected checkboxes(dynamically created) values should be set to destination text field

For destination text field, based on the input, the auto suggestion will be displayed as checkboxes. I can select one or more values and my requirement is to get these selected values on the controller side, Once I click on the search button. How can I achieve this for dynamic checkboxes, please provide any suggestions.
jquery:
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
HTML:
<form method="post" id="searchForm" action="someAction/showStatistics" id="ems">
<label>Destination</label>
<input type="text" id="destinationName" name="destinationName" value="${someForm.destinationName}" class="field" />
<div class="dest"></div>
<input type="submit" class="button" value="search" />
</form>
Try this
$(document).ready(function () {
var dynamicCheckbox = [];
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
};
});
}
});
$('.button').on('click', function (event) {
event.preventDefault();
$('.dest input:checked').each(function() {
dynamicCheckbox.push($(this).attr('name'));
});
console.log(dynamicCheckbox);
});
});
Here in dynamicCheckbox you will get the names of the checked checkboxes.
Hope that's what you need!

Send checkbox values in Ajax

The following code is my original code. In the code, I tried to post value of an input for each checkbox which is checked.
<tbody class="myFormSaldo">
<tr>
<td> <input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$ref.'" onchange="enableList(this);" class="chb_group" /> </td>
<td> <input name="items['.$i.']" type="text" readonly value="'.$obj->items.'" /> </td>
<td> <input name="size['.$i.']" type="text" readonly value="'.$obj->size.'Kg" /> </td>
<td> <input name="quantity['.$i.']" type="text" readonly value="'.$obj->myquantity.'" /> </td>
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_size=$_POST['size'][$i];
The code above is working fine. It post the value of each inputs for each checkbox which were checked. For example; if there were three checkedbox which were checked and the form was submited, then it would post three arrays (3 loop) of : $product_name,$product_size,etc..
What I want now is to use Ajax. Like this:
var product_name= document.getElementById('product_name').value;
var product_size = document.getElementById('product_size').value;
$.ajax(
{
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: product_name='+product_name+'&product_size ='+product_size ,
cache: false,
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
But it doesn't count or find the checkbox
So my question now is how to do the same as the php do with foreach($_POST['checkbox'] as $i) in ajax?
I am just a beginner in all of these things.
Thank you for any help.
You are using your product_name as a string, not as a variable:
Try this:
data: 'product_name='+product_name+'&product_size='+product_size,
Or, as Ghost sad in comments, use formdata.
var dataString = $('form').serialize();
and later, in the ajax:
data: dataString,
...
Try this...
<script>
$.ajax({
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: "{'product_name':" + product_name + ", 'product_size':" + product_size+ "}",
cache: false,
dataType: "html"
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
</script>
Try this
Ajax is simplified check here
var data = $('form').serialize();
$.post( "../actions/selectReferenceOrder.php", { name: data}).done(function( data ) {
alert( "Data Loaded: " + data );
});
OR
$.post( "../actions/selectReferenceOrder.php", { product_name: product_name, product_size : product_size }).done(function( data ) {
alert( "Data Loaded: " + data );
});

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Ajax success: {return false;}

I want to return false from $.ajax when success is complete:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
return false;
}
});
This doesn't work. Is there a work around?
From your post I guess that you call a function that contains the $.ajax() and try to return false to that function. but you can't do that such way, because AJAX is asynchronous.
It's better to call a function from the ajax success function like following:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
var returned = true;
if(some_condition_not_satisfied) {
returned = false;
} else {
}
// call a function
calledFromAjaxSuccess(returned);
}
});
function calledFromAjaxSuccess(result) {
if(result) {
alert('TRUE');
} else {
alert('FALSE');
}
}
Maybe you could try something like this (values 1 and 0 should be changed to the ones that you use):
success: function(result){
if(result === '1'){
// do something
}
else
return false;
}
just use asunc false it can work fine i have implemented like that only
just try it
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
async: false, //=>>>>>>>>>>> here >>>>>>>>>>>
success: function(result) {
return false;
}
});
it is working fine try it once
<form action="yourpage" method="post" onsubmit="return matchpass();">
<div>
<label> Name</label>
<input type="text" name="name" id="name">
</div>
<div>
<label> Email ID</label>
<input type="email" name="email" id="email">
</div>
<div>
<label> Mobile No</label>
<input type="text" name="mob" maxlength="10" onkeyup="check_if_exists();" autocomplete="off" id="mob">
</div>
<div>
<button type="button" >Send</button>
</div>
<span id="err"></span>
<div>
<label> OTP</label>
<input type="password" name="otp" id="otp" maxlength="6" placeholder="****">
<span id="err2"></span>
</div>
<div>
<input type="reset" value="Reset" class="reset-btn">
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<input type="hidden" id="otpcheck"/>
<script>
function matchpass()
{
$.ajax({
type:"post",
url: "yourpage",
data:{ mobile:mob,otp:otp},
success:function(data)
{
if(data==1)
{
document.getElementById("otpcheck").value=1; //important
}else{
document.getElementById("err2").style.color = "red";
document.getElementById("err2").innerHTML = "invalid OTP Number ";
document.getElementById("otpcheck").value=0; //important
}
}
});
if(document.getElementById("otpcheck").value==0){
return false;
}
}
I face this problem. then i found the actual solution. use async : false, inside ajax call
function thisisavailavailusername(uname){
var dataString = 'username='+ uname.value;
var trueorfalse = false;
$.ajax({
type: "post",
url: "/BloodBook/checkavailableusername",
data: dataString,
cache: false,
async : false, //user this then everything ok
success: function(html){
if(html=="true"){
$('#validusername').html('Available');
trueorfalse = true;
}else{
$('#validusername').html('Not Available');
trueorfalse = false;
}
},
error: function() {
alert("Something Wrong...");
}
});
return trueorfalse;
}

Categories

Resources