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']+"')");
}
}
?>
Related
While using jquery $.ajax or $.post, to submit a value (say uid {user id}) how can I define a callback function to retrieve multiple values from the php script and retrieve values from my mysql table say(user details, corresponding to the uid) and store them in vars, using the default datatype:datatype???
Can anyone please show me both the jquery and php scripts please. And yes the database is runninga mySQL 5.5.24 and PHP version is 5.3
instead of using $.ajax you can also use this...
var id=$("#id").val();
$.getJSON('script.php', {id:id}, function(json) {
var id=json.id;
var name=json.name;
var email=json.email;
});
}
in your php scrip..
<?php
mysql_connect($host,$dbuser,$dbpass);
mysql_select_db($db_name);
$id=$_GET['id'];
$query="select * from tbl_name where id='$id'";
$rs=mysql_query($query);
$row=mysql_fetch_assoc($rs);
$id=$row['id'];
$name=$row['name'];
$email=$row['email'];
$data=array("id"=>$id,"name"=>$name,"email"=>$email);
echo json_encode($data);
?>
The best way to do this would be to send it back to javascript as a json object.... so for your user example
// assuming post containing a username, using pseudo code for db access
$row = $db->fetchAssoc("select * from users where username = '".dbEscape($_POST["username"]."'");
header("Content Type: application/json");
echo json_encode($row);
ajax code will be like follows
$.ajax({
type: "POST",
url: "your_page.php",
data: { param1: "val1", param2: "val2" }
}).done(function( data) {
// do your callback operation
});
get values from your_page.php like below
$_POST["param1"] , $_POST["param2"]
if you want to know more then click here
I think this will solve your problem.
<script type="text/javascript">
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data contains the data we get from serverside
{
}
});
</script>
dataType: json..so jason will return multiple values. from you php script
echo json_encode($array_of_val);
$.ajax({
type: "POST",
dataType:"html",
url: "ajax_page.php",
data:"params1="$params1"¶ms2="+$params2,
}).done(function(value) {
// write your callback operation
});
you can get your data on ajax_page.php using an post method like
$_POST['params1'];
and
$_POST['params2'];
$query= select statement
$items=array();
while ($row = mysql_fetch_object($rs)) {
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);
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
});
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...
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); });
}
I have jQuery Ajax request that sends data to a PHP page that then insert a record into MySQL.
With my current setup, this all works fine.
However, as part of the PHP script, i use mysql_insert_id() to retreive the ID of the last record.
I need the Ajax Success function to return this ID value as a javascript variable.
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = array('LastID' => mysql_insert_id());
$LastID = json_encode($LastID);
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "json",
success: function(data) {
var LastID = data;
alert(LastID);
}
});
I've read of using PHP's json_encode to create a JSON object and then pass that back, but i've had no luck.
How can i return this value?
just use
echo $LastId;
to send a response.
If you pass only one value you dont need JSON:
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = mysql_insert_id();
echo $LastID;
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "text",
success: function(data) {
var LastID = data;
alert(LastID);
}
});
with JSON:
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$jsonArray= array('LastID' => mysql_insert_id()); //*1 value is named LastID
echo json_encode($jsonArray);
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "json",
success: function(data) {
var LastID = data["LastID"];//use the same name as above (*1)
alert(LastID);
}
});
Maybe it is because your LastID is in array so the resulting object would be a JS array.
If you just need the ID don't use JSON encode and just pass the ID in Javascript.
So in PHP:
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = mysql_insert_id();
echo $LastID;
}