Pass Json array into different html divs - php

I want to use the first 3 result of my Json array in 3 different divs.
The array returned from ajax.php look like this:
'{"res":["106"],"base":["190220"]}'
So I want the first value "res":["106"] in the div id: Response1 and "base":["190220"] in the div id : Response2.
My knowledge of this is only 1% so I need some help from you guys :)
html and ajax:
<!DOCTYPE html>
<html>
<form id="resource">
<input type="number" id="base" name="base" placeholder="Base ID" value="170143" />
<input type="number" id="lot" name="lot" placeholder="Lot ID" value="110"/>
</form>
<div id="response1"></div>
<div id="response2"></div>
<div id="response3"></div>
<script src="../vendor/jquery/jquery.min.js"></script>
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'ajax.php',
dataType: 'html',
type: 'post',
data: $(this).serialize(),
success: function( data ){
$('#response1').html( data );
console.log( data );
}
});
e.preventDefault();
}
$('#resource').change( processForm );
})(jQuery);
</script>
</body>
</html>
Here my ajax.php file:
<?php
require_once('background.php');
if(isset($_POST['base']) and isset($_POST['lot'])){
$base = $_POST['base'];
$lot = $_POST['lot'];
$baseSql = "SELECT * FROM QBS_ABL_VMSCHRP1_SIM where WORKORDER_BASE_ID = '".$base."' AND WORKORDER_LOT_ID = '".$lot."'";
$baseSTH = $pdo->prepare($baseSql);
$baseSTH->execute();
while($row = $baseSTH->fetch(PDO::FETCH_ASSOC)){
$resArray['res'][] = $row['RESOURCE_ID'];
$resArray['base'][] = $row['WORKORDER_BASE_ID'];
}
if(isset($resArray)){
json_encode($resArray);
}
}
?>

Solved it by changing this:
(function($){
function processForm( e ){
$.ajax({
url: 'ajax.php',
dataType: 'json',
type: 'post',
data: $(this).serialize(),
success: function( data, textStatus ){
res = (data['res']);
base = (data['base']);
$('#response1').html( res );
$('#response2').html( base );
//console.log( data );
}
});
e.preventDefault();
}
$('#resource').change( processForm );
})(jQuery);

Related

define a string as POST request using AJAX in the same page onclick

for the PHP is just simple check:
All in the same page named **
page.php
if(isset($_POST['XYZ']){
echo "WORKING";
}
then for my HTML:
<h1 id='XYZ'>CLICK ME</h1>
now at the same page i'm trying to do the AJAX POST request like this
$('#XYZ').click(function(){
var XYZ = 'XYZ';
$.post('page.php',{
XYZ: XYZ
})
})
and the request didn't work, How do i just pass the $_POST data? I removed success function since i didn't think it is useful in this case.
What i want is when i click on the <h1> the echo appears.
try this:
var my_string = 'xyz';
$.ajax({
url: 'ajax.php',
type: 'post',
data: { "action":my_string},
dataType: "json",
success: function(response) {
if(response['state'] == 'ok'){
console.log("ok");
}
}
});
ajax.php
<?php echo $_POST['action']; ?>
<head>
<script>
var my_string = 'xyz';
$.ajax({
method: 'POST',
url: './giveposts',
dataType: "text",
contentType: "application/json; charset=utf-8",
data:my_string,
success: function(data) {
{
$("#test").html(data);
}
}
});
</head>
</script>
<body>
<div id="test>
/*echo
</div>
</body>

json ajax update HTML element not working

I am trying to get a HTML element to update from an ajax quire to a PHP file but it's not working.
My code is below
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<script>
var json = (function () {
var json = null;
$.ajax({
url: "test.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
json = data.test;
$('#demo').text(json.test1);
}
});
return json;
})();
</script>
<p id="demo"></p>
</body>
</html>
PHP code
<?php
header("Content-Type: application/json");
$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';
echo json_encode($test);
//echo nothing after this //not even html
?>
can someone please help, thank you
Your php script sending a JSON object and you can access its property like this:
$.ajax({
url: "test.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
$('#demo').text(data.test1);
}
});
the Javascript is the problem. You should bind the function that makes the AJAX query to a DOM event, such as a button click.
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "test.php",
dataType: "json",
data: { name: $("#name").val()},
success:function(data){
$("#demo").text(data.test1);
}
});
});
});
</script>
<input type="text" id="name" placeholder="Enter your name">
<button id="submit">Submit</button>
<p id="demo"></p>
On PHP side, you can read the input:
<?php
header("Content-Type: application/json");
$test = [
'test1'=>1, 'test2'=>2, 'test3'=>3, 'name'=>$_POST['name']
];
echo json_encode($test);
exit;

can i fetch and populate different fields using function(data) jquery?

i want to populate two fields when some one fill up card no.
<input type="text" id="name" name="name" class="form-control" Value="<?php echo $grow['name']; ?>">
<input type="text" id="address" name="address" class="form-control" Value="<?php echo $grow['address']; ?>">
but this code populate field one by one. can any one suggest be better code for populating two fields from database. Thank you
jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k=$(this).val();
var q="name";
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q='+q,
cache: false,
success: function(data)
{
if(data){
$("#name").val(data);
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
$("#address").val(data);
}
}
});
}else
$("#name").val("");
$("#address").val("");
}
});
});
});
</script>
getresult.php
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select * from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
echo $row[$q];
?>
Try to extract both name and address from database and json them
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select address,name from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
$result = array(
'name'=>$row['name'],
'address'=>$row['address']);
echo json_encode($result);
After that parse them via jquery
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
var parsedData = jQuery.parseJSON(data);
$("#name").val(parsedData.name);
$("#address").val(parsedData.address);
}
}
});
Javascript Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k = $(this).val();
var q = "name";
$.ajax({
type: 'POST',
url: "getresult.php",
data: 'k='+k,
cache: false,
success: function(data)
{
var jsonArr = $.parseJSON(data);
if(typeof response =='object')
{
$("#name").val(jsonArr.name);
$("#address").val(jsonArr.address);
}
else
{
$("#name").val("");
$("#address").val("");
}
}
});
});
});
</script>
PHP Code:
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k = $_POST['k'];
$sql = mysql_query("select * from inward where krishi='$k'");
$row = mysql_fetch_assoc($sql);
echo json_encode(array('name' => $row['name'], 'address' => $row['address']);
?>

submit with php array

My objective with this code is when an user click in edit button, is sent this all=<?php echo $arr; ?> to the page edit.php .
This code simply does nothing (no ajax call in firebug).
<?php
$arr = array("one", "two", "three")
?>
<div id="content">
<input class="edit" type="submit" value="Edit" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".edit").submit(function () {
$.ajax({
url: "edit.php",
type: "post",
dataType: "html",
data: "<?php echo json_encode( $arr ); ?>",
success: function (data) {
$('#ad').html(data);
}
});
});
});
</script>
Edit As #MilanJaric showed, you do need to operate on the click of the submit button. In addition, however, you should prevent the default action of the click as well. End Edit
You need to echo the data json_encoded and wrapped in quotes:
<div id="content">
<input class="edit" type="submit" value="Edit" />
</div>
<script type="text/javascript">
$( function()
{
$( '.edit' ).click( function( e )
{
$.ajax( {
url: 'edit.php;,
type: 'post',
dataType: 'html',
data: '<?php echo json_encode( $arr ); ?>',
/* It's hard to tell based on your code, but if you wanted a var at the server named "all" use this instead of the above line:
data: {
all: '<?php echo json_encode( $arr ); ?>'
},
*/
success: function( data )
{
$( '#ad' ).html( data );
}
} );
e.preventDefault();
} );
} );
</script>
IMO, however, it gets real ugly to echo PHP inside your JS especially if you have to do a lot of it, so when the need arises, I use an IIFE to inject PHP data into the code as a JS var. This allows me to isolate all PHP echoing within the parens of the invocation of the IIFE:
<?php
$arr = array("one", "two", "three")
?>
<div id="content">
<input class="edit" type="submit" value="Edit" />
</div>
<script type="text/javascript">
( function( arr )
{
$( function()
{
$( '.edit' ).click( function( e )
{
$.ajax( {
url: 'edit.php;,
type: 'post',
dataType: 'html',
data: arr,
/* It's hard to tell based on your code, but if you wanted a var at the server named "all" use this instead of the above line:
data: {
all: arr
},
*/
success: function( data )
{
$( '#ad' ).html( data );
}
} );
e.preventDefault();
} );
} );
}(
'<?php echo json_encode( $arr ); ?>'
) );
</script>
In addition to what the other folks pointed out regarding the need to json_encode() your $arr, the jQuery documentation for .submit() points out the following:
The submit event is sent to an element when the user is attempting to
submit a form. It can only be attached to <form> elements.
So I believe the reason the AJAX isn't even being submitted is that your <input> element is not within a <form> element. Try the following:
<?php
$arr = array("one", "two", "three");
?>
<form id="content">
<input class="edit" type="submit" value="Edit" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$(".edit").submit(function () {
$.ajax({
url: "edit.php",
type: "post",
dataType: "html",
data: "all=<?php echo json_encode($arr); ?>",
success: function (data) {
$('#ad').html(data);
}
});
});
});
</script>
The JavaScript submit event only occurs on a <form> not on individual <input>s.
You need the following HTML:
<div id="content">
<form id="whatever">
<input class="edit" type="submit" value="Edit" />
</form>
</div>
And in the JavaScript change:
$( '.edit' ).submit( function()
to
$( '#whatever' ).submit( function()
<script type="text/javascript">
$(document).ready(function () {
$(".edit").click(function () {
$.ajax({
url: "edit.php",
type: "post",
dataType: "html",
data: "all=<?php echo $arr; ?>",
success: function (data) {
$('#ad').html(data);
}
});
});
});
</script>
Use a json_encode to encode php array to json string
http://php.net/manual/en/function.json-encode.php
You're echoing an Array, which will make PHP echo something like Array(), in stead of the true values.
Try var_dump($arr); to dump the array, and eventually try serialising the array, easier to retrieve its state later.
If the ajax call does work with static data, then this is where you should start looking.

jQuery + Ajax form submission, PHP doesn't get any data

I am trying to submit a form that only has a radiobutton group with name=radiob. This is the script I am using for submitting data:
<script type="text/javascript">
$(function() {
$("#myForm").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "index.php?p1=<?php echo $_GET['p1']; ?>",
data: dataString,
success: function() {
$("#ppm").fadeOut("slow");
$("#ppmPlugin").load('?p1=<?php echo $_GET['p1'];?>&result=true');
}
});
return false;
});
});
</script>
But this is what I get in my PHP script:
$_POST array - empty
Array ( )
$_GET array
Array ( [p1] => xxx [result] => true )
But if I alert(dataString); I get radiob=2, that is, the value depending on the radiobutton selected..
How do I fix this problem?
I've tested your code and it works fine. Perhaps you have some kind of redirect in index.php?p1=xxx.
P.S. Tested with this code:
<?php $_GET['p1'] = 1; ?>
<form id="myForm">
<input type="radio" name="radiob" value="1" />
<input type="radio" name="radiob" value="2" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#myForm").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "index.php?p1=<?php echo $_GET['p1']; ?>",
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
And in index.php I have
<?php var_dump($_GET, $_POST); ?>

Categories