How to get JSON vars from PHP script - php

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)

Related

Ajax request dont send $_POST propertly

Im trying to develop an android app using php, jquery, mysql and phonegap.
Phonegap environment don't let me use php, but I can locate it in to my server and I request data from database with ajax.
I can do simple queries, but when I use a var taken from $_POST, it doesn't works, exactly way isset($_POST['any_var']) returns false, but if I do isset($_POST) returns true, so I think I have an incorrect dataString.
I'm new in this kind of develop any clue in helpful.
<script>
$(document).ready(function()
{
$("#login").click(function(){
var nombre=$("#nombre").val();
var pass=$("#pass").val();
var dataString= "nombre="+nombre+"&pass="+pass+"&login=true";
if($.trim(nombre).length>0 & $.trim(pass).length>0){
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").val('Conectando...');
},
success: function(data){
return data;
},
error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown);}
});
var url="https://crm.inter-web.es/app/json.php";
$.getJSON(url, function(track){
console.log(track);
$(".list").append("<li>Nombre "+track['nombre']+"</li>");
$(".list").append("<li>Pass "+track['pass']+"</li>");
});
}return false;
});
});
</script>
PHP code:
<?php
//server code
include "db.php";
if (isset($_POST['login'])) {
$q=mysqli_query($con,"select nombre, pass from usuarios where nombre='".$_POST['nombre']."'");
$datos=mysqli_fetch_all($q, MYSQLI_ASSOC);
$num=mysqli_num_rows($q);
$json=json_encode($datos);
echo $json;
}else{
$q=mysqli_query($con,"select * from clientes where id_cliente='62' ");
$datos=mysqli_fetch_array($q, MYSQLI_ASSOC);
$num=mysqli_num_rows($q);
// var_dump($datos);
// for ($i=0; $i < $num ; $i++) {
// echo $datos[$i][0]."<br>";
// }
$json=json_encode($datos);
// mkdir("./json/");
// $fp=fopen("json/json.json", "w+");
// fwrite($fp,$json);
echo $json;
}
?>
Instead trying to format a "dataString"... I suggest you to use an object:
dataObject = {
nombre: $("#nombre").val(),
pass: $("#pass").val(),
login: true,
}
And in the ajax:
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataObject,
// ...
success: function(data){
// return data; // That line does nothing.
console.log(data);
},
Finally, I did this with GET in stead of POST, my first code was redundant, I did 2 request to the server:
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").val('Conectando...');
},
success: function(data){
return data;
},
error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown);}
});
AND:
$.getJSON(url, function(track){
console.log(track);
$(".list").append("<li>Nombre "+track['nombre']+"</li>");
$(".list").append("<li>Pass "+track['pass']+"</li>");
});
I modify the url with the GET parameters in the second way ("https://url?name=name&pass=pass") and it Works fine.

Json unable to pass array to php

As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');

How handle errors in php script fired by Jquery.ajax?

I have php-script, firing with jquery ajax function. Somthing like this:
$("a.test").click (function () {
var new_id = $(this).attr("new_id");
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(){
alert('error');
}
});
return false;
});
Now, a have some errors in test.php, but I can't see them. Sript just runs and I have no feedback, only error alert (alert ('error')).
How can I get back errors, that I have in test.php to handle them?
If you echo the errors in test.php, you can simply do:
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(data){
alert('error:'+data);
}
});
return false;
});
Edit:
I usually do something like this. In test.php if you get an error, create an array with your error info and echo it json encoded:
$message=array('error' => 1,'message' => '<div class="alert alert-danger" role="alert">' . $login['message'] . '</div>' );
echo json_encode($message);
Now in your jquery you can retrive the error by:
success: function (data) {
alert (data);
},
error: function(data){
var obj = JSON.parse(data);
alert(obj.message);
}
When you have it in array like this you dont even need error: function(data) anymore, since you can simply:
success: function (data) {
var obj = JSON.parse(data);
if (obj.error) {
// do something
alert (obj.message);
}else{
// do something else
}
},
On test.php you could show errors using the code explained here: https://stackoverflow.com/a/21429652/6525724
And then on this page instead of alert('error') you could use alert(data).
Try this
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}

Ajax: I can't get data from PHP by using json_encode

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

Set Session variable using javascript

<script type="text/javascript">
function checkQuery()
{
var val = form1.proDown.options[form1.proDown.options.selectedIndex].value;
var txt = form1.proDown.options[form1.proDown.options.selectedIndex].text;
//alert(val+' | '+txt);
<?php $_SESSION['value1']= ?> = txt; <?php ; ?>
}
</script>
I have this code and it does not Work?
Any One have solution for accessing javascript variable into $_SESSION[].
I think you should use xhr(Ajax) to store your data into php session. Following is a simple example to do this
jQuery.ajax({
url: 'storesession.php',
type: 'POST',
data: {
txt: txt,
},
dataType : 'json',
success: function(data, textStatus, xhr) {
console.log(data); // do with data e.g success message
},
error: function(xhr, textStatus, errorThrown) {
console.log(textStatus.reponseText);
}
});
storesession.php
$_SESSION['value1'] = $_POST['txt'];

Categories