jQuery.ajax response data giving null - php

I am trying to insert data into a MySQL database using jQuery and AJAX. I have written the query parameters in my add.php file. I would like to show the form data immediatly beneath the form.
jQuery:
jQuery("#addStockInForm").submit(function(e){
e.preventDefault();
dataString = jQuery("#addStockInForm").serialize();
jQuery.ajax({
type: "POST",
url: "add.php",
data: dataString,
dataType: "json",
success: function(data) {
//$("div#showinstant").html(data);
alert(data);
}
});
});
add.php file
require 'foo.config.php';
if(isset($_POST['addStockIn'])) {
$query = "INSERT INTO stockin ( serialno, project_id, ...... etc. ) VALUES
(`:serialno, :project_id, ....... etc. )";
add-stockin.php file
<form class="form-horizontal" id="addStockInForm" method="post">
.....
</form>

you should return the data from your php code back to your frontend
require 'foo.config.php';
if(isset($_POST['addStockIn'])) {
$query = "INSERT INTO stockin ( serialno, project_id, ...... etc. ) VALUES
(`:serialno, :project_id, ....... etc. )";
...
...
echo yourdata

There is no return in add.php file. Though you are using dataType as 'json',
you should return the data in json format.
You should try something like this.
add.php
require 'foo.config.php';
if(isset($_POST['addStockIn'])) {
$query = "INSERT INTO stockin ( serialno, project_id, ...... etc. ) VALUES
(`:serialno, :project_id, ....... etc. )";
//extra code here
$output = array('res' => $data); //$data : form data to show in html file
$output = json_encode($output);
echo $output; exit;
jQuery:
jQuery("#addStockInForm").submit(function(e){
e.preventDefault();
dataString = jQuery("#addStockInForm").serialize();
jQuery.ajax({
type: "POST",
url: "add.php",
data: dataString,
dataType: "json",
success: function(data) {
//$("div#showinstant").html(data);
alert(data.res);
}
});
});

Main problem was in elsewhere... The Problem was in isset funciton parameter
if(isset($_POST['addStockIn'])) {
}
I have changed this to
if(isset($_POST['serialno'])) {
}
And it's working fine!
#LX7 was helped me to think differently, thanks dude...

Related

retrieve mysql result to jquery

My problem is that I can't retrieve the result of the mysql result via ajax, please help
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd')
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name'];
//array_push($final,$result);
//print_r($result);
echo json_encode($result);
Change PHP Code as below
$final = array();
$sql_courses = mysql_query("SELECT course_id, course_name FROM course") or die(mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
echo json_encode($row_courses);
change php code as below:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data: {
user_id: user_id
},
dataType: 'json',
success: function (msg) {
$('p').html(msg.course_name);
}
});
Its better to send it with a key value like this:
And its better to use console.log(variable); to check variable's content
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd');
console.log(msg);//You should check output of this in browser console
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg.cname);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name']; // this will have first_coures_name (an string)
$final['cname']=$result;
//print_r($result);
echo json_encode($final); //the output should be this {'cname':'first_course_name'}

How to return mutiple value using ajax in jQuery

JQUERY
$.ajax({
url: 'save.php',
type: 'POST',
success:function ()
var id = html.$id;
var name = html.$name;
alert(id);
alert(name);
});
SAVE.PHP
<?php
include("db.php");
$sql = "INSERT into test(Name)values('') ";
if (mysql_query($sql))
{
$id = mysql_insert_id();
echo $name = "Peter";
echo $id;
}
?>
How can retrieve specific data and store in a specific variable in my Jquery?
Please ignore my Name in php, because I just randomly assign variable to it
How to return two different data, and store them in 2 variable?
I know it is incorrect, please tell me the correct way of doing it
JS
$.ajax({
url : 'save.php',
type: 'POST',
dataType: 'JSON'
}).done(function(data) {
alert(data.id);
alert(data.name);
});
PHP
<?php
include("db.php");
$sql = "INSERT into test(Name)values('') ";
if (mysql_query($sql)) {
$arr = array(
"id" => mysql_insert_id(),
"name" => "Peter"
);
echo json_encode($arr);
}
?>
You can return the value as in JSON format in key-value pair. Since I do not have much knowledge over php, but if possible try to return any JSON or XML response from your php code:
$.ajax({
url: 'save.php',
type: 'POST',
success:function(response)
// here you can use response to display your value
});

AJAX and JSON with PDO MySQL

I'm trying to get data from an attribute, pass it through ajax into another page, and then insert into mysql.
Right now I have some div elements
<div data-categories="[{"name":"Gastropub","pluralName":"Gastropubs"},{"name":"Food","pluralName":"Food"}]">
Name
</div>
Breaking it down:
-----------------------
[
{"name":"Gastropub","pluralName":"Gastropubs"},
{"name":"Food","pluralName":"Food"},
{"name":"more","pluralName":"more"}
]
------------------------
data-categories is where I insert a json_encoded array and it pops that out. When I'm trying to do is figure out the best practice of using ajax to get that value maybe with
var cats = $('div').data('categories');
$.ajax(function(){
type:"POST",
url:"other.php",
data: "data="+cats,
success:function(data){
alert("success");
}
});
other.php
Now I'm trying to figure out how to save each value separately into my MySQL in this other.php, if I have a table with columns : name and pluralName (and maybe add more later on) in MySQL data
if(isset($_POST['data'])){
$insert = $dbh->prepare("INSERT INTO cats(name,pluralName) VALUES(?,?)");
}
How do I get those values from a set of json values and insert each value into the proper column? As you can see from the example above, I have more than 1 name and pluralName
Making an AJAX call would be like :
var data = $("div").attr("data-categories");
$.ajax({
type: "POST",
url: "other.php",
data: "data="+data,
function(data){
alert("success");
}
});
If you are getting the data in $_POST array then you can probably use :
<?php
$str = $_POST['data'];
$data = json_decode($str, true);
//print_r($data);
for($i=0;$i<count($data);$i++) {
$insert = "INSERT INTO cats(name,pluralName) VALUES('".$data[$i]['name']."','"+$data[$i]['pluralName']+"')";
//Insert in database
}
Try This:
Jquery
var dataStr = $("div").attr("data-categories");
$.ajax({
type: "POST",
url: "other.php",
data: {data:dataStr},
success:function(data){
alert("success");
}
});
PHP Code
<?php
if(isset($_POST['data']))
{
$data = $_POST['data'];
$jsonArray= json_decode($data, true);
for($i=0;$i<count($jsonArray);$i++) {
$insert = $dbh->prepare("INSERT INTO cats(name,pluralName) VALUES('".$jsonArray[$i]['name']."','"+$jsonArray[$i]['pluralName']+"')");
}
}
?>

How to correctly select and show (or insert) data from (in) MySQL database with AJAX call to PHP function?

So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}

$.ajax post empty data to server with jsonp

this below code could'nt send data to other server. i want to send "aaa-bbb-ccc" with $.ajax. but after post back userCode thats post empty data from $_POST. sorry for my english
jquery code :
<script type="text/javascript">
$(function(){
$.ajax({
url: "http://www.site.com/index.php",
type: "POST",
dataType: "jsonp",
data: {userCode: "aaa-bbb-ccc"}
}).done(function(data){
alert(data.message);
});
});
</script>
server index.php :
<?php
include_once ('./AFactory.class.php');
$database= new AFactory;
$db=new AFactory();
$link=$db->getDBO();
if ( $_POST['userCode'] == '')
{
$data['success']=false;
$data['message']='ERROR ...';
}
else {
$query=array('id'=>NULL,'userCode'=>$_POST['userCode']);
$sql=$db->insertQuery('`alachiq_takhmis`.`users`',$query);
if ( mysql_query($sql) )
{
$data['success']=true;
$data['message']=$_POST['userCode'];
}
else
{
$data['success']=false;
$data['message']=$_POST['userCode'];
}
}
echo $_GET['callback'] . '('. json_encode($data) . ')';
?>
post back:
({"success":false,"message":'ERROR ...'})
whats my code problem?
JSONP works by injecting a <script> element with a src attribute into a document.
That can only ever make a GET request.
$.ajax({
url: "http://www.site.com/index.php",
type: "GET",
dataType: "jsonp",
data: {userCode: "aaa-bbb-ccc"}
});

Categories