ajax
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#amount').val(data);
// $(".email_msg").addClass("red");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
Controller code
public function stb_info(){
$stb_no=$this->mso->alldata_stbno($this->input->post('stb_no'));
echo json_encode($stb_no);
}
i am getting out put
[{"sxb_no":"xxxxxx","mzo_name":"xx","cto_name":"xxxxx","area":"xxxxx","name_sxb_owr":"","mobile_no":"xxxxxx","email":"xxxxx#yahoo.com","amount":"xxx"}]
i need to know how to get each values ex:- if i want get email id what i should i do in jquery please help me i new to ajax
Most browsers support JSON.parse(), which is defined in ECMA-262 and is the recommended way. Its usage is simple (I will use your example JSON):
var json = '{"area":"xxxxx",...,"email":"xxxxx#yahoo.com","amount":"xxx"}';
var obj = JSON.parse(json);
Note that obj.email can't be used, because you are parsing an array.
Edit: Checking your comments you need to know that the data parameter is the JSON object, parse it first and then you can do:
$('#amount').val(obj[0].email);
Just add to $.ajax call parameter dataType:"json" and Jquery will parse it in success parameter automatically. Then use it data[0]['email'];
For example :
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#email').val(data[0]['email']);
//OR
var obj = JSON.parse(data);
$('#email').val(obj[0].email);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
Related
I am trying to get ajax response. But my code does not show anything in alert. Here is my ajax code. my form id is contact_form and my submit button id is submit_btn
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
var form= $("#contact_form").val();
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
dataType : 'json',
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
//console.log(textStatus, errorThrown);
}
});
e.preventDefault();
});
});
my email.php
<?php
echo "ok";
?>
I think that your problem is because you are trying to use the serialize method in a wrong way.
The .serialize() method will handle all the fields that are inside the selected target form. In the original code, You've used the .val() method to take the values of the form, but this will not work because that method is intended to be used with a single form element and can't handle the whole form.
Change your code in this way:
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
e.preventDefault();
var form = $("#contact_form");
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
I am having issues retrieving data from PHP by using Ajax. I am stuck and have been spending lots of time trying to find out where the problem is.
Here is my php code:
<?php //ajax/default_chart_numbers.php
require_once '../core/db_connection.php';
$lotto = new Lotto();
$ultimo_concurso=$lotto->ultimo_concurso('foo');
$ultimos_numeros_m=$lotto->ultimos_numeros('bar');
$R1m=$ultimos_numeros_m[1];
$R2m=$ultimos_numeros_m[2];
$R3m=$ultimos_numeros_m[3];
$R4m=$ultimos_numeros_m[4];
$R5m=$ultimos_numeros_m[5];
$R6m=$ultimos_numeros_m[6];
$R7m=$ultimos_numeros_m[7];
//preparing json
$json=array('y'=>$ultimo_concurso,'n1'=>$R1m,'n2'=>$R2m,'n3'=>$R3m,'n4'=>$R4m,'n5'=>$R5m,'n6'=>$R6m);
print json_encode($json,true);
?>
The output of the PHP file is:
{"y":"2745","n1":"1","n2":"13","n3":"19","n4":"29","n5":"41","n6":"46"}
And here is the jQuery code:
<script>
$(document).ready(function(){
/*Retriving data from PHP file*/
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (response, textS, xhr) {
alert("everything ok :)");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
},
complete: function(data){
y=data.y;
alert('The id number is '+ y);
}
});
});
</script>
When executing, the value is undefined. I mean, the alert i get is The id number is undefined.
What am i missing?
There's no true in json_encode, there is in json_decode to get an array, but now you're creating a string
change
print json_encode($json,true);
to
echo json_encode($json);
and the complete handler doesn't get the data, it has two arguments, the XHR object and the statuscode, the success handler gets the data
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
y=data.y;
alert('The id number is '+ y);
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
On PHP side, send the JSON with:
header('Content-Type: application/json');
echo json_encode($json);
Maybe log the incoming data to the console:
inside success: add an console.log(response)
inside complete: add an console.log(data.y)
This is missing:
https://api.jquery.com/jQuery.parseJSON/
try using:
result = $.parseJSON (data);
result.y has your value
I've got this script:
<script>
var request;
$("#foo").click(function(event){
request = $.ajax({
url: "/votesHandler.php",
type: "post",
data: "true"
});
request.done(function (response, textStatus, jqXHR){
alert("Voted!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
"Oops, something went wrong"
);
});
request.always(function () {
alert("Done.");
});
</script>
And what I'm trying to do is send "true" to the server when the #foo element is clicked. I've used AJAX only a few times before and each time it was with forms. The problem is that I need to receive this POST request in PHP (with $_POST['foo']) but this time the input is not the name of a text input. How do I send data into $_POST without a form?
You can specify the key of data when you send to your url.
$.ajax({
data: {foo: 'true'}
});
To retrieve it use
$_POST['foo']
Send it as:
data: 'foo_clicked=1',
or
data: 'foo_clicked=' + somevarname,
On the PHP side:
$recd = $_POST['foo_clicked'];
if ($recd == 1) {
//do what you need to do
}
try this:
$("#form").submit(function (e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
console.log(formURL); //your form action
$.ajax({
url: formURL,
type: "POST",
data: postData,
beforeSend: function () {
//do
},
success: function (data, textStatus, jqXHR) {
console.log('success data');
//whatever
},
error: function (jqXHR, textStatus, errorThrown) {
//if fails
console.log('fail');
}
});
e.preventDefault(); //STOP default action
});
I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)
I have used json_encode to encode two php arrays and now i have to read through ajax. Could anyone please let me know how to read those arrays through ajax request.
For example: i have a php file file1.php which has
echo json_encode($array1);
echo json_encode($array2);
Another file in which i read as follows:
For reading single encoded array i am reading like this
new Ajax.Request("file1.php",
{
method:'get',
asynchronous:false,
parameters: ({id: stopID, contains: tempContain}),
onSuccess:function(data){
var result=data.responseJSON;
var keys = Object.keys(result);
var values = Object.values(result);
for(var i = 0; i < keys.length; i++) {
infoString += keys[i]+":"+values[i];
}
});
You can use jquery, it will save you a lot of time ;) There are examples in this link:
http://api.jquery.com/jQuery.getJSON/
With jQuery Ajax
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});