I'm sending JSON to my server via jQuery's ajax method.
Here's my jquery, and im pretty sure this is fine:
function stuffs() {
this.fname = document.getElementById("fname").value;
this.lname = document.getElementById("lname").value;
this.email = document.getElementById("email").value;
}
$(function() {
function ajaxhelper(data){
//console.log(JSON.stringify(data));
//this returns "{"fname":"mike","lname":"smith","email":"a#a.a"}" which is what i expect
$.ajax({
url: 'postdb.php',
type: 'POST',
data: {data : JSON.stringify(data)},
success: function(data) {
console.log(JSON.stringify(data));
console.log("Success");
},
error: function(e) {
console.log(e);
}
});
}
$("form").on('submit', function(e){
e.preventDefault();
var data = new stuffs();
ajaxhelper(data);
//window.location = "postdb.php";
});
});
</script>
I get back an 500 server error. Here's my php code. (yes i'm only sending it an fname that i've preloading into my database, $con is valid i just didnt share the code to connect to my database)
$obj = json_decode($_POST['data']);
$sql = "SELECT * FROM testtable WHERE fname = \"$obj->{'fname'}\"";
$query = $con->query($sql);
I think my sql is incorrect due to the quotes? This is where im stuck.
Try using $obj->fname instead of $obj->{'fname'}.
Here is the correct syntax for your SQL Statement
$sql = "SELECT * FROM testtable WHERE fname = '".$obj->fname."'";
Related
I'm trying to check if a field is just present into db before submit a form.
So I add the keyup event to that field to get data from db with ajax.
So where I have the form I add this code:
$(document).ready(function (){
$("#matricola").keyup(function () {
$.ajax({
type:"get",
url: "getMatricolaAjax.php",
data: {'type':'user', 'matricola':$("#matricola").val()},
dataType: "text",
success: function(result){
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ result +" già presente!!");
},
error: function(){
console.log("KO");
}
});
});
});
And this is my getMatricolaAjax.php:
<script src='js/jquery-2.1.4.js' type="text/javascript"></script>
<?php
require_once 'config.php';
require_once FUNCTION_PATH.'/dbFunction.php';
if($_GET['type'] == "user"){
$queryMatricolaMatch = 'select * from user where matricola = "'.$_GET['matricola'].'"';
}else{
$queryMatricolaMatch = 'select * from 150ore where matricola = "'.$_GET['matricola'].'"';
}
echo $queryMatricolaMatch;
$conn = dbConnect($USERDB, $PASSWORDDB, $NAMEDB);
$matricola = dbQueryGetResult($queryMatricolaMatch);
dbDisconnect($conn);
echo $matricola;
It works for half, beacause in result I obtain all html code from getMatricolaAjax.php..
Why??
How can I get only matricola??
Comment or remove dataType: "text" and try again.
$.ajax({
type:"get",
url: "getMatricolaAjax.php",
data: {'type':'user', 'matricola':$("#matricola").val()},
// dataType: "text",
success: function(result){
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ result +" già presente!!");
},
or else you can use json_encode() in PHP to get data as JSON object array.
You should use POST to check for value in database before submitting a form.
$(document).ready(function (){
$("#matricola").keyup(function (e) {
var thevalue = $(this).val();
$.post('getMatricolaAjax.php',{'type':'user','matricola':thevalue},
function(data) {
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ data +" già presente!!");
});
});
});
And the php file
<?php
require_once 'config.php';
require_once FUNCTION_PATH.'/dbFunction.php';
$conn = dbConnect($USERDB, $PASSWORDDB, $NAMEDB);
if($conn->real_escape_string($_POST['type']) == "user"){
$queryMatricolaMatch = 'select * from user where matricola = "'.$conn->real_escape_string($_POST['matricola']).'"';
}else{
$queryMatricolaMatch = 'select * from 150ore where matricola = "'.$conn->real_escape_string($_POST['matricola']).'"';
}
$matricola = dbQueryGetResult($queryMatricolaMatch);
dbDisconnect($conn);
echo $matricola;
This should work, but I have no idea what dbQueryGetResult is supposed to do so you should post it too.
Note:If you use PDO edit remove 'real_escape_string' function and use other methods of sanitization
I have a form that has a select option , So I am trying to update the form/table with some content from database when I select a type in the select option ,
SO for that I did an ajax call something like this.
$("#selectPlantilla").on("change",function(){
var descripcion = $(this).val();
//alert(descripcion);
var url="http://index.php";
var posting = $.post(url, {
im_descripcion: descripcion,
}).done(function (data) {
alert(data);
});
});
And then I validated the call in php on the same inde.php page like this
if(isset($_POST['im_descripcion']))
{
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
$result = mysql_fetch_array($result);
print_r($result);
}
The problem I am facing is in the alert window it return the whole page instead of just the $result that I have printed , So can any one help me out how I can channelize it properly , I have use the values from the array $result to update in the form using JQuery .
Thanks in Advance
For returning PHP array data in Ajax, JSON will make your life the simplest.
$result = mysql_fetch_array($result);
echo(json_encode($result));
This will return the array in a format that is easily usable by JavaScript. Try this to see its content:
alert(JSON.stringify(data));
With JSON, you should be able to fetch data or iterate through it in JavaScript
Try this
In Javascript
<script type="text/javascript">
var $ =jQuery.noConflict();
$(document).ready(function(){
$('.dropdown_class').on('change', function() {
var m_val = this.value;
var datastring = "im_descripcion="+m_val;
$.ajax({
type: "POST",
url: "lunchbox_planner.php",
data: datastring,
cache: false,
success: function(result) {
var v = $.parseJSON(result);
var l = v.length;
for(var i=0;i<l;i++){
var sh_d = "<div class='coco3'>"+v[i]+"</div>";
$('.mon_tea').append(sh_d);
}
}
});
});
});
</script>
<div class="mon_tea">
In PHP
<?php
if(isset($_POST['im_descripcion'])) {
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
while($row_sh = mysql_fetch_array($result)){
$all_incr[] = $row_sh['col_name'];
}
echo json_encode($all_incr);
}
?>
I'm making an AJAX call to a fairly simple PHP function. The response should be a JSON object to be manipulated, but my response is always an empty object.
Relevant Code:
index.html's AJAX Call:
$( function() {
$('#dates').on('submit', function (e) {
var start_time = new Date().getTime();
e.preventDefault();
var submitData = $('#dates').serialize();
console.log(submitData);
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
dataType: 'json',
beforeSend: function(){
$('#loading').show();
},
success: function(data) {
console.log(data);
$('#loading').hide();
},
error:function(xhr, desc, err){
alert('You tried to send an AJAX request, but something went wrong.\n Please Contact the NASR WebDev Team');
console.log(xhr);
console.log("Details: " + desc +"\nError: "+ err);
}
});
});
});
inflow.php's array creation and echo:
<?php
$msqlStart = $_POST['start_date'];
$msqlEnd = $_POST['end_date'];
$inflowQuery=
"SELECT
COUNT,
QUEUE_ID,
QUEUE_GROUP,
INFLOW_DATE,
LINE_OF_BUSINESS
FROM
ticket_inflow.inflow
WHERE
ROUTE_STATUS = 'Inflow'
AND inflow_date between ? and ?";
$connect = new mysqli($host, $user, $password, $database);
if ($connect->connect_error){
die("Failed to Connect:.".$connect->connect_errno.": ".$connect->connect_error);
}
if(!($statment = $connect->prepare($inflowQuery))){
die('Error in Preparation Error Number:%d Error: %s');
}
if(!$statment->bind_param('ss', $msqlStart, $msqlEnd)){
die ('Error in Binding');
}
if(!$statment->execute()){
die('Error In Execution');
}
$statment->bind_result($inflowCount, $inflowQueue, $inflowQG, $inflowDate, $inflowLOB);
$a_json = array();
$jsonRow = array();
While($statment->fetch()){
$UID = 0;
$jsonRow['UID'] = $UID++;
$jsonRow['count'] = utf8_encode($inflowCount);
$jsonRow['inflow_date'] = utf8_encode($inflowDate);
$jsonRow['queue'] = utf8_encode($inflowQueue);
$jsonRow['queue_group'] = utf8_encode($inflowQG);
$jsonRow['lob'] = utf8_encode($inflowLOB);
array_push($a_json, $jsonRow);
}
$jsonReturn = json_encode($a_json);
echo $jsonReturn;
?>
If I go directly to inflow.php and pass it parameter's identical to what the page passes it, I get what appears to be a nice JSON object, however when I look at the response Chrome Developer's Tools I get:
[]
And nothing more.
You are sending form data, not json;
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
//contentType: "application/json",<-- remove this
dataType: 'json',
I am trying to pass a variable from my ajax to my php script. I can't see to get it to work. It keeps on giving me NULL when I do a var_dump on the variable.
JQUERY:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: id
});
LinkUpload(id);
function LinkUpload(id){
$("#link-upload").dialog();
}
});
});
</script>
PHP:
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM xcart_slideshow_slides where slideid='$id'")or die(mysql_error());
$sli = mysql_fetch_array($query);
$slide_id = $sli['slideid'];
$link = $sli['link'];
var_dump($id);
I need the $id variable to post so I can dynamically change the dialog box when the click function is activated.
EDIT:
So I have changed some of my coding:
Jquery:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.post(
"slide-show-link.php",
{ id: id },
function(data,status){alert("Data: " + data + "\nStatus: " + status); }
);
// alert(id);
LinkUpload(id);
});
function LinkUpload(id){
$("#link-upload").dialog();
}
});
I wanted to see if the data was in fact being passed so I threw an alert in the .post. This is the error I'm getting now:
I have tried passing plain text and echoing it back on the page but it fails. It is just not passing.
Try this -
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: { id : id }
});
Okay so here is my ajax request:
$("#scoreForm").submit(function(e){
e.preventDefault();
var nickName = $('#nickName').val();
var gameScore = parseInt($('#gameScore').text());
var result = { 'result' : '{ "nick":"'+nickName+'", "score":'+gameScore+' }' };
//var result = { "nick":nickName, "score":gameScore };
$.ajax({
url: "http://localhost:8888/snake/addScore.php",
type: "POST",
data: result,
//dataType: "jsonp",
success: function(data){
alert("siker");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("bukta " + textStatus);
//console.log(data);
}
});
return false;
});
and my php process code:
$json_decoded = json_decode($_POST['result'],true);
//$nick = $_GET['nick'];
//$score = $_GET['score'];
$mysqli = new mysqli("localhost", "root", "root", "snake",8889);
//$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$nick."', ".$score.")");
$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded['nick']."', ".$json_decoded['score'].")");
echo "true";
Now i got the data inserted into the database, but ajax still firing error event. i read that if i set the dataType to jsonp it will go trough , but then i get parse error, how do i get past that?
Wehn you access the $_POST variables in your php script, you need to refer to them the way they are packaged with the JSON object:
$_POST['nick']
$_POST['score']
If you want to refer to the items as $_POST['result'] and use your json decoding approach, youll need to package it this way:
var result = { result : { "nick":nickName, "score":gameScore } };