Data not returning from ajax POST - javascript

I use this jQuery function to get data through Ajax:
function addContentPrt(cid){
$.ajax({
url: "<?=parseLink('addContent.php')?>",
type: "POST",
cache: true,
dataType:'json',
data: {id: cid},
success: function(returnedData){
console.log(returnedData);
},
error: function (xhr, tst, err) {
console.log(err);
}
});
}
and on the receiving end:
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo $r['title'];
echo $id;
?>
the echo $id does return to ajax, but not $r['title'], with that it goes null in console. If I add some dummy text like hello world, I get a synthax error SyntaxError: Unexpected token h {stack: (...), message: "Unexpected token h"}
What could be the cause of this and what could I do to fix it?

<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo json_encode('id' => $id, 'title' => $r['title']);
?>
and in your ajax success:
success: function(returnedData){
console.log(JSON.parse(returnedData));
},

In the ajax, you specified the datatype as json which is the format expecting from the server, So in order to get a result, you need to return the json result from the server. Either by using json_encode($r) where $r can be any array.

return json_encode($r); then you can read variable $r in sucess

Related

Call page PHP with Ajax

I have some difficulties to call PHP script with:
$("#tata").click(function(){
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
});
});
But my alert is empty... I am sure that the URL is correct, because if I add in my PHP file HTML code it appear on my alert!
I am sure that my PHP code works
PHP file:
echo "lalalala";
$getData = new mod_visitor();
$writeData = new writeData();
$urlPart1 = $_SERVER['HTTP_HOST'];
$urlPart2 = $_SERVER['REQUEST_URI'];
$pageEnCours = $urlPart1 .= $urlPart2;
$getData->get_ip();
$getData->LookupIP($GLOBALS['domain']);
$getData->ValidateIP($GLOBALS['domain']);
if ($GLOBALS['domain'] && $pageEnCours != preg_match("#localhost/joomla/$#", $pageEnCours)) {
$GLOBALS['domain'] = trim($GLOBALS['domain']);
if ($getData->ValidateIP($GLOBALS['domain'])) {
echo "cc";
$result = $getData->LookupIP($GLOBALS['domain']);
$writeData->write_domain($result);
} else {
echo "erreur";
$writeData->write_error();
};
} else {
echo "je ne rentre pas dans la boucle";
};
echo $pageEnCours;
echo $GLOBALS['domain'];
Parse the dataType to 'json'
Add dataType: 'json' to the javascript
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
dataType: 'json',
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
And echo back as JSON in your php
<?php
echo json_encode('lalala');
?>
If you want to return multiple items, you can return them as an array
<?php
$return = array(
'pageEnCours' => $urlPart1 . $urlPart2,
'domain' => $GLOBALS['domain']
);
echo json_encode($return);
?>
And get the items client-side
success: function(data) {
console.log(data.pageEnCours, data.domain);
}

Unable to parse response using ajax

So I have a js file that posts a JSON object using $.ajax, and then my php script takes that JSON object and does stuff to it, however, i can't get a json response back from the php script (the success callback function never runs).
register_script.js:
$.ajax({
method: "post",
dataType: "json",
url: "http://localhost/login/webservices/register2.php",
data: {
reg_username: username,
email: email,
reg_password: password,
confirm_password: confirm_pass
},
success: function (data) {
alert("hello?");
//alert(data.status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
});
register2.php:
if (isset($_POST['reg_username'], $_POST['email'], $_POST['reg_password'], $_POST['confirm_password'])) {
$username = $_POST['reg_username']; //$_POST['from html']
$email = $_POST['email'];
$password = hash('md5', ($_POST['reg_password']));
$confirm_password2 = hash('md5', ($_POST['confirm_password']));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username','$email','$password')";
if ($password == $confirm_password2) {
$response = sqlsrv_query($conn, $sql);
if ($response) {
$data = array(
"username" => $username,
"email" => $email,
"password" => $password,
"confirmPass" => $confirm_password2,
"status" => "Registered",
);
echo "Registered \n";
}
}
}
//...
//some other validations
//...
echo json_encode($data);
I have a feeling the way i am handling the json object is incorrect. any help would be really appreciated.
you should not
echo
anything other than json_encode when working with ajax dataType : json you have
echo "Registered \n";
before
echo json_encode
remove that and it should work
EDIT:
when you set the dataType : "json" in your ajax call then the response is expected to be in json when the call is finished, and any text other than json encoded string in response will result in an error. if you still need to debug and see what route the script is taking, you can add another index in $data (i assume that $data is an array), so it would be like
if($registered){
$data['debug_logs'] .='Registration successfull----';
}
if($emailSent){
$data['debug_logs'].='Email sent for registration-----';
}
echo json_encode($data);
and then in your ajax success function you can use it like
success:function(data){
console.log(data.debug_logs);
}
hope it clears your confusion.
Please remove echo "Registered \n"; the line from your code when you echo "Register"; the Ajax request return this back to the browser, and your actual data echo json_encode($data); never return back to the browser.

Does ajax need contentType to send to php ? if so why error?

I been trying to figure this one out but i don't seem to find the error but in my script
My script
$('#Bshift').click(function(){
var isValid=false;
isValid = validateForm();
if(isValid)
{
var ArrId= <?php echo json_encode($arrId ); ?>;
var ArrQty= <?php echo json_encode($arrQty ); ?>;
var counter= <?php echo json_encode($i ); ?>;
var productId;
var productQty;
for (i = 0; i < counter; i++) {
productQty = ArrQty[i];
productId= ArrId[i];
var pLocal= document.getElementById(productId).value;
var prodData = 'pLocal=' + pLocal+ '&proId='+productId;
$.ajax ({
url: 'shiftSave.php',
type: 'POST',
data: prodData,
dataType: 'json',
contentType: "application/json; charset=utf-8", // this is where have the error
});
}
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = 'pettyCash=' + pettyCash+ '&comment='+comment;
$.ajax ({
url: 'shiftSave.php',
type: 'POST',
data: prodData1,
dataType: 'json',
contentType: "application/json; charset=utf-8 ", // Error here too
}).done(function(data){
alert("Data Saved. Shift Started.");
document.getElementById("register").reset();
document.getElementById("Bshift").disabled = true;
document.getElementById("StartingB").disabled = true;
}).fail(function(error){
alert("Data error");
});
}
});
Everytime i put the ContentType the script goes to done but if I take it off then my sql on my php executes and gives me a responce
Php code shiftSave.php
<?php
include "connection.php";
session_start();
$data=array();
$location="";
if (isset($_SESSION['location'])) {
$location=$_SESSION['location'];
}
if (isset($_SESSION['eId'])) {
$empId=$_SESSION['eId'];
}
if(#$_POST['pLocal']) {
$proQty = $_POST['pLocal'];
$proid = $_POST['proId'];
try {
$sql = "UPDATE location_product SET productQty='".$proQty."' WHERE productId='".$proid."' and productLocation='".$location."'";
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
echo "Record updated successfully!";
//$data["secion"]=$stmt. " this ";
if ( !$stmt) {
$data["match"]=false;
} else {
//echo "Error updating record: " . $conn->error;
echo "Record updated successfully!";
$data["match"]=true;
}
echo json_encode($data);
} catch (Exception $e) {
$data["match"]=false;
echo json_encode($data);
}
}
if (#$_POST['pettyCash']) {
$pettyCashIn=$_POST['pettyCash'];
$comment= $_POST['comment'];
try {
$sql = "INSERT INTO `customer_service_experts`.`shift` ( `empId`, `pettyCashIn`, `note`) VALUES ( '$empId', '$pettyCashIn', '$comment')";
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
if ( !$stmt) {
$data["match"]=false;
} else {
echo "Record updated successfully!";
$data["match"]=true;
}
echo json_encode($data);
} catch (Exception $e) {
$data["match"]=false;
echo json_encode($data);
}
}
?>
when i execute without the contentType it goes true but it fails and gives me Data error (the alert that i used on the function fail), but if I use the contentType it goes to the function .done and goes trough but the query does not execute.
You also need to stringify the data you send like so
data: JSON.stringify(prodData1),
You could make a helper function which you can use everywhere you want to do a JSON POST
function jsonPost(url, data, success, fail) {
return $.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: success,
error: fail
});
}
Does ajax need contentType to send to php ?
And you have a contentType: "application/json; charset=utf-8", which sends data in request payload but if you omit it/remove it from ajax then by default contentType for jquery ajax is application/x-www-form-urlencoded; charset=UTF-8.
Lets see both of them here:
A request with Content-Type: application/json may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
And if you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded (It is default for jquery ajax) or Content-Type: multipart/form-data your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
So if you send the data in request payload which can be sent via Content-Type: application/json you just can't take those posted values with php supergloabals like $_POST.
You need to fetch it yourself in raw format with file_get_contents('php://input').
Firstly remove the content-type option. Let jQuery use the default.
Second,
change:
var pLocal= document.getElementById(productId).value;
var prodData = 'pLocal=' + pLocal+ '&proId='+productId;
to:
var pLocal= document.getElementById(productId).value;
var prodData = { pLocal: pLocal, proId: productId };
and:
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = 'pettyCash=' + pettyCash+ '&comment='+comment;
to:
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = { pettyCash: pettyCash, comment: comment };

JavaScript ajax post command error for localhost

I am new to Ajax & JavaScript. But i am stuck with this error. I am making post request using Ajax.
var sentdata = {"name":"gourav", "email":"email"};
var sentd = JSON.stringify(sentdata);
this.url = "http://localhost/Working/board.php";
$.ajax({
type: "POST",
url: $(this).url,
data: sentd,
contentType: "application/json",
//dataType : "json",
success: function (response) {
alert(response.message);
console.log( "Done with success: ");
},
error: function (xhr, thrownError) {
alert(thrownError);
}
});
I am calling this request to simple code where i am not even checking the $_POST variable and just trying to write some data in mysql table.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true);
// selecting database
mysql_select_db(DB_DATABASE, $con);
if(1)
{
$tb_name = "tb_appuser";
$name = "name1";
$email="email1";
$deviceId="0";
$platform="1";
$query = sprintf("INSERT INTO %s (user_name, email, device_regid, platform_type) VALUES ('%s', '%s', '%s', '%d')" , $tb_name, $name, $email, $deviceId, $platform);
echo "$query\n";
$res = mysql_query($query);
}
I already tested this board.php code and verified it is inserting the data in table.
But when i am doing this via $ajax i am getting "The page at localhost says: undefined" and nothing got written in my database also.
url: this.url, not $(this).url.
$(this) does not have a property called "url" in your context I think.

conflict with typeahead, php and jquery 1.10.2

I have the following code in JavaScript:
$('input#search_user').typeahead({
source: function(query, process) {
$.ajax({
url: 'modulos/search_user.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(data);
}
});
}
});
And the following code in my PHP file:
if (isset($_POST['query'])) {
$query = $_POST['query'];
$sql = mysql_query ("SELECT nombre FROM users_r WHERE nombre LIKE '%{$query}%'",$link);
}
$data = array();
while ($row = mysql_fetch_object($sql))
{
$data[] = $row['nombre'];
}
echo json_encode( $data );
mysql_close($link);
But with jQuery 1.10.2 it throws the following error:
Uncaught Error: one of local, prefetch, or remote is required
What should I do about this?
now works with the next code
javascript
$(document).ready(function ()
{
$("input[name='search_user']").typeahead({
name: 'nombre',
remote: 'modulos/search_user.php?query=%QUERY'
});
}); // $(document).ready(function ()
php file
$query = $_GET['query'];
$sql = mysql_query ("SELECT nombre FROM users_r WHERE nombre LIKE '%{$query}%'",$link);
$data = array();
while ($row = mysql_fetch_assoc($sql))
{
$data[] = $row['nombre'];
}
mysql_close($link);
echo json_encode( $data );
my problem was the each method, for get column work with mysql_fetch_assoc but no with mysql_fetch_object

Categories