Ajax request dont send $_POST propertly - php

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.

Related

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);
}

Return an array of data from PHP to jQuery

Building a website for my kid's bday which will allow his grandparents to log on and click through 15gigs worth of pics/vids from every day of the last two years. Can't seem to capture any data from my PHP program in jQuery however. AND I keep receiving an error that reads:
"Failed to load resource: net::ERR_EMPTY_RESPONSE (03:27:54:409 | error, network at public_html/pics/desi/desiPics.php".
I thought the procedure was relatively simple. Am I overcomplicating it somehow?
From desiPics.php:
<?php
$dir= glob('pics/desi/{*.jpg,*jpeg,*png,*gif}', GLOB_BRACE);
echo json_encode($dir);
?>
From jQuery:
var desiPics = [];
$.ajax({
type: 'POST',
url: 'pics/desi/desiPics.php',
cache: false,
async: true,
success: function(result){
if(result){
desiPics = eval(result);
alert(desiPics.length);
}else{
alert('error');
}
}
});
You have to parse the json that is returned into an object to use it in the method you are.
success: function(result){
result = JSON.parse(result);
if(result){
desiPics = result;
alert(desiPics.length);
}else{
alert('error');
}
}
Edit: I added the dataType "json" which will convert result to an object.
var desiPics = [];
$.ajax({
type: 'POST',
url: 'pics/desi/desiPics.php',
cache: false,
async: true,
dataType: "json",
success: function(result){
if(result){
desiPics = result;
alert(desiPics.length);
}else{
alert('error');
}
}
});

ajax link json datatype call

I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()

How to get JSON vars from PHP script

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)

Categories