hey i have a problem submitting my data via jquery and back:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
});
so,
ONE of those if-conditions must be true, because of:
checkAvailability.php:
if(isset($_POST['data'])) {
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
require 'AvailabilityChecker.php';
$config = array(etc..);
$availabilityChecker = new AvailabilityChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
preg_match( '/(\d+(\.\d+)?)/', $data['x'] , $m);
$x = $m[0];
if($availabilityChecker->check_availability($x)) {
echo json_encode(array("error" => "is ok", "result"=>1));
} else {
echo json_encode(array("error" => "not ok", "result"=>0));
}
}
data.result have to be 1 OR 0.
anybody can tell me why there is no alert-message? greetings!
UPDATE:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
now i get first the fail-1 alert and than the fail-2 alert, so both if-conditions are false, why?
You need to specify the dataType, otherwise jquery will instead try to guess what you are trying to do. In this case it is incorrectly guessing text/html rather than application/json.
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: 'json',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
You should also properly set the content-type header in php, before you echo the json.
header('Content-type: application/json');
You can get away with doing either-or, but i'd suggest doing both.
a solution can be
success: function(d) {
data = jQuery.parseJSON(d);
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
this becouse $.ajax will no decode the result text from the page for you.
what the php code is doin in fact is to print a json string to the stream.
Note that the the output passed to success can be any sort of text (also xml code on simply text)
You need to set the correct content type header in your php file:
header('Content-Type: application/json');
//snip
echo json_encode(array("error" => "is ok", "result"=>1));
Related
So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")
Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this
If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}
hey there i have this script´s:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: "json",
data: 'username=' + $(this).data('id'),
success: function(data) {
if (result == 1) {
$("#select-err").text(data.error ? data.error : "");
}
else {
$("#select-err").text(data.error ? data.error : "");
}
}
});
in checkAvailability.php:
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo json_encode(array("error" => "is ok"));
$result = 1;
} else {
echo json_encode(array("error" => "Wrong chose"));
$result = 0;
}
while testing i found out that this is not the correct way to check if a php-clause is true or false, so i need your help...could anyone show me how to check this via jquery? greetings and thanks!
UPDATE:
i changed to:
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo 1;
} else {
echo 0;
}
and:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: "json",
data: 'username=' + $(this).data('id'),
success: function(data){
if(data == 1){
$("#select-err").text(data.error ? data.error : "is ok");
}
else{
$("#select-err").text(data.error ? data.error : "not ok");
}
}
});
it works, BUT:
if data == 1, on my page "1" is displayed, why and how can i fix this?
Instead of doing this
if (result == 1) {
do this
if (data.result == 1) {
inside your success callback javascript file.
Then in your PHP file instead of these:
echo json_encode(array("error" => "is ok"));
echo json_encode(array("error" => "Wrong chose"));
do these instead:
echo json_encode(array("error" => "is ok", "result"=>1));
echo json_encode(array("error" => "Wrong chose", "result"=>0));
What I did is I included result as a property in the JSON coming from AJAX call. So instead of only having the error property you also have the result property in the JSON.
in php change to this
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo json_encode(array("error" => "is ok" , "result"=>1));
} else {
echo json_encode(array("error" => "Wrong chose" , "result"=>0));
}
and in jquery
check as
if(data.result==1){
// do the same
}else{
}
Don't echo json_encode(array("error" => "is ok")); in php in if-else statement, just echo result in both cases.
In you ajax it on success callback, it will return everything that is on ur php page i.e. result which may be 1 or 0. SO check if data==1 or data==0 instead of result.
I am trying to send some data using php and jquery ajax using json datatype method.
Here is my code:
$("#username").on("keyup change keypress", function () {
var username = $("#username").val();
$.ajax
({
type: "POST", // method send from ajax to server
url: window.location.protocol + '//' + window.location.host + '/' + "admin/admins/user_exists",
data: {
username: username
},// Specifies data to be sent to the server
cache: false, // A Boolean value indicating whether the browser should cache the requested pages. Default is true
contentType: "application/json",
dataType: 'json', // The data type expected of the server response.
success: function (response_data_from_server) {
for (var key in response_data_from_server)
var result = response_data_from_server[key] + ""; // JSON parser
if (result == 'true') {
console.log("---------------- in true");
$("#username_alert").text("ERROR");
$('#username_alert').removeClass("alert-success");
$("#username_alert").css("visibility", "visible");
}
else {
if (result == 'false') {
console.log("---------------- in false");
$("#username_alert").text("NO ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').addClass("alert-success");
}
else {
if (result == 'empty') {
console.log("---------------- in empty");
$("#username_alert").text("ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').removeClass("alert-success");
}
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and it always goes to an error function. The error that I receive is the following:
parsererror SyntaxError: Unexpected token {}
My url location is correct and is indeed returning the correct json format. Here is my php code:
public function user_exists()
{
$username = $this->input->post("username");
$is_exists = "false";
$this->load->database();
if ($username != "")
{
$rows = $this->db->query("
SELECT * FROM `admins` WHERE `username` = '" . $username . "'
")->num_rows();
if ($rows > 0)
{
$is_exists = "true";
}
else
{
$is_exists = "false";
}
}
else
{
$is_exists = "empty";
}
$arr = array ('result' => $is_exists );
$response = json_encode($arr);
echo $response;
}
I've debugged it million times, the firebug sees the response as correct and expected json, however the client side seems to refuse to get it as a json respone, for what I believe.
Will appreciate any help!
...
header('Content-type: application/json');
echo $response;
Maybe you could use "header('Content-type: application/json');" before "echo"
Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];
I'm just trying to spit the elements of an array into seperate input fields on a form via jquery's AJAX.
Heres my javascript code:
$('#based').change(function() {
if ($(this).val().length > 0)
{
$.ajax({
type: "POST",
url: "ajax.php",
data: "id="+$(this).val(),
success: function(data){
if (data != 'error')
{
$('#keyword').val(data[2]);
$('#keyword_slug').val(data[3]);
}
}
});
}
});
Heres my PHP code for 'ajax.php':
$sql = mysql_query("select * from `keywords` where `id`='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_num_rows($sql) == 0)
{
echo 'error';
}
else
{
while ($row = mysql_fetch_assoc($sql))
{
foreach ($row as $k => $v)
$data[] = $v;
}
echo json_encode($data);
}
Its not working. What do I do here? I've looked into serializeArray but can't get anything to work properly.
I think you need dataType: 'json' if you are expecting JSON back.
Otherwise jQuery has to guess, and if you are not sending the Content Type application/json, it may guess wrong.