Json with jquery - php

I just want to know how to get the json data in phtml file. Below is my php controller.
foreach($result AS $row) {
$arrValues[] = array("firstname"=>$row['firstname'],
"emailid"=>$row['emailid'],
"lastname"=>$row['lastname']);
}
header("Content-type: application/json", true);
echo json_encode(array('rows'=>$arrValues));
This is my phtml file.
var emailid=$(this).data('emailid');
//alert(emailid);
$.ajax({
url: 'http://localhost/feedback/public/index/email/',
type: 'POST',
data: {emaildata: emailid },
dataType: 'json',
success: function(data) {
var emailid = data[0];
var vname = data[1];
var vlaname=data[2];
var w = window.open('', 'Feedback', 'width=400,height=400,resizeable,scrollbars');
w.document.write("FirstName"+data[0]);
}
});
Im trying to write those values in apop up window.But it says object.Could you please help me how to get the json data and write that in to popwindow.

success: function(data) {
var emailid = data.rows[0].emailid;
var vname = data.rows[0].firstname;
var vlaname=data.rows[0].lastname;
var w = window.open('', 'Feedback', 'width=400,height=400,resizeable,scrollbars');
w.document.write("FirstName"+data.rows[0].firstname);
}

Related

Updating database table with AJAX on change

I'm trying to update a database column once an input field has changed.
however the code below just isn't doing it and am puzzled.
<script>
$("#addline1").change(function() {
var itemVal = $("#addline1").val();
var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
processChange(dataString);
});
function processChange(dataString){
$.ajax({
type: "POST",
url: "../inc/dataforms/test.php",
data: dataString,
complete: function(data) {
var Resp = data.responseText;
console.log(Resp);
}
});
};
</script>
companyid is already defined elsewhere on the page.
I've tried change, onchange...
My PHP code is:
mysqli_query($dbc,"UPDATE `comp_companies` SET `regoffice1` = '$_POST[addline1]'
WHERE `company_id` = '$_POST[companyid]'");
Saying unexpected token (
somewhere in here
$("#addline1").change(function() {
var itemVal = $.("#addline1").val();
var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
processChange(dataString)
});
I suggest you to use an object instead of a string... To pass the data, as the method used is POST.
(Assuming companyid is defined...)
<script>
$("#addline1").change(function() {
var itemVal = $("#addline1").val(); // Remove the extra dot that was here
// var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
// I suggest the following:
var dataObj = {companyid:companyid, addline1:itemVal};
processChange(dataObj);
});
function processChange(dataObj){
$.ajax({
type: "POST",
url: "../inc/dataforms/test.php",
data: dataObj,
dataType: "json", // If you expect a json as a response
complete: function(data) {
var Resp = data.responseText;
console.log(Resp);
});
});
});
</script>

pass arrays and variables from jquery to php at the same time

I want to pass arrays and other variables from jquery code to php using post request but I don't know how to pass arrays and variables at the same time.
I tried this code:
var new_location_name = "";
var new_location_id = "";
var old_location_name = [];
var selected_name = [];
var selected_id = [];
var user = '<?php echo $current_user ;?>';
$(document).ready(
$("#transfer").click(function(){
$.ajax({
type: "POST",
url: "update.php",
data: "username="+user+"&new_location_name="+new_location_name+"&new_location_id"+new_location_id+"&"+{ old_location_name : old_location_name }+"&"+{ selected_name : selected_name }+"&"+{ selected_id : selected_id },
});
return false;
});
});
Create an object, serialize it and send it:
var obj = {
key1: 'value1',
key2: ['one','two','three'],
key3: {
key3_0: 'value3_0'
}
}
var jsonData = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "update.php",
data: jsonData
});
JQuery Data:
data:
{
username: user,
new_location_name: new_location_name,
new_location_id: new_location_id,
old_location_name: old_location_name,
selected_name : selected_name,
selected_id : selected_id
}
In your PHP Script
<? $oldLocationName = $_REQUEST['old_location_name']; ?>
and so on.
You can pass multiple parameters as arrays or strings the same. The left hand side of the data is the value that the API is expecting as the parameter name.
var new_location_name = "";
var new_location_id = "";
var old_location_name = [];
var selected_name = [];
var selected_id = [];
var user = '<?php echo $current_user ;?>';
$(document).ready(
$("#transfer").click(function(){
$.ajax({
type: "POST",
url: "update.php",
data: {username: user,
new_location_name: new_location_name,
old_location_name: old_location_name
}
});
return false;
});
});
You can read more in this question: Pass Multiple Parameters to jQuery ajax call
Try this snippet
var array = [];
$.ajax({ url: 'update.php',
data: {'array' : array},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error) {
alert("Error");
}
});
First time Check file, this script must be in .php file, not .js file;

Posting text of div with ajax

I want to post the content of div(text) to a php page with ajax, i have already this script which post all the input fields of the three forms
.on('actionclicked.fu.wizard' , function(e, info){
if(info.step == 3 ) {
var dataString = $("#form1, #form2, #form3").serialize();
var mydiv = $('#mydiv').html();
$.ajax({
data: dataString + mydiv,
type: 'POST',
url: 'confirmation.php',
cache: false,
success: function(data) {
message : 'you request was submitted'
}
});
}
})
but i need to post also the text of the div in the php page i use
$mydiv =$_REQUEST['mydiv'];
I can echo all the other fields but nothing return for $mydiv.
Are you looking for something like this?
<div id="myDiv">
<h1>This is a page</h1>
</div>
$("#post").click(function(){
var htmlData = $("#myDiv").html();
$.post('postPage.php', {'html': htmlData },function(response){
//
});
`.on('actionclicked.fu.wizard' , function(e, info){
if(info.step == 3 ) {
var a = $("#form1").serialize();
var b = $("#form2").serialize();
var c = $("#form3").serialize();
var d = $(#mydiv).text();
data = {};
data['astring'] = a;
data['bstring'] = b;
data['cstring'] = c;
data['ddivtext'] = d;
$.ajax({
data: data,
type: 'POST',
dataType: "json",
url: 'confirmation.php',
cache: false,
success: function(data) {
message : 'you request was submitted'
}
});
}
})

Unable to show data in DIVs from MySQL

I am unable to display data in the set of DIVs from MySQL database.
The data is showing only in last DIV, below is my code:
$(document).ready(function (){
var n = 9;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('container').appendChild(div);
$.ajax({
url: 'myapi.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var Name = data[2]; //get id
//var vname = data[1]; //get name
$('#'+div.id).html(""+Name);
}
});
}
});
Add one more property when you make ajax request, async:false. Hope you get your result
$.ajax({
url: 'myapi.php', //the script to call to get data
data: "",
async:false , //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var Name = data[2]; //get id
//var vname = data[1]; //get name
$('#'+div.id).html(""+Name);
}
});
set ajax async:false
$(document).ready(function (){
var n = 9;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('container').appendChild(div);
$.ajax({
async: false,
url: 'myapi.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var Name = data[2]; //get id
//var vname = data[1]; //get name
$('#'+div.id).html(""+Name);
}
});
}
});
You can close your Ajax call in an anonymous function:
(function(div.id){
$.ajax({
url: 'myapi.php',
data: "",
dataType: 'json',
success: function(data)
{
var Name = data[2];
//var vname = data[1];
$('#'+div.id).html(""+Name);
}
});
})(div.id);
Because the Ajax call is async, the value of div.id has changed before the Ajax call returns Reference
If myapi.php always returns the same data and you want to display it in multiple divs
$(document).ready(function() {
$.ajax({
url: 'myapi.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var n = 9;
for (var i = 0; i < n; i++) {
var div = document.createElement('div');
div.className = "d5";
div.id = i + 1;
document.getElementById('container').appendChild(div);
var Name = data[2]; //get id
//var vname = data[1]; //get name
$('#' + div.id).html("" + Name);
}
}
});
});
If myapi.php returns different data for each request we might have multiple solutions
One of them is just setting the async attribute to false
The other one is passing the ID of the div to the server and return it with the response
$(document).ready(function() {
var n = 9;
for (var i = 0; i < n; i++) {
var div = document.createElement('div');
div.className = "d5";
div.id = i + 1;
document.getElementById('container').appendChild(div);
$.ajax({
url: 'myapi.php?id=' + div.id, //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var Name = data[2]; //get id
//var vname = data[1]; //get name
var divId = data[3];
$('#' + divId).html("" + Name);
}
});
}
});
The problem with you is that the div.id value is updated before you receive the response and the latest div get filled because the loop will be faster than the request
One more solution can be defining a function and pass the container id to it
function loadContentInto(divId) {
$.ajax({
url: 'myapi.php', //the script to call to get data
data: "",
async: false, //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var Name = data[2]; //get id
//var vname = data[1]; //get name
$('#' + divId).html("" + Name);
}
});
}
and call this method from your loop
for (var i = 0; i < n; i++) {
var div = document.createElement('div');
div.className = "d5";
div.id = i + 1;
document.getElementById('container').appendChild(div);
loadContentInto(div.id);
}
I hope that can help :)

Return all Records from Table with AJAX

I have a program that sends a user id through AJAX and to a php program that searches a table for all records that match that user id. The problem is that it's only returning one row and I need for it to return all the rows that match. Any ideas on how to do this?
MySQL statement in php:
$id=$_POST["id"];
$sql = mysql_query("SELECT * FROM crime_map WHERE user_id = '$id'");
while($row = mysql_fetch_assoc($sql))
$output[]=$row;
echo json_encode($output);
JS code:
function submitform() {
var id = document.getElementById('id').value;
var datastr = 'id=' + id;
alert(datastr);
$.ajax({
type: "POST",
url: 'api.php',
data: datastr,
dataType: 'json',
success: function(data){
var user_id = data[0];
alert(user_id);
}
})
}
function submitform() {
var id = document.getElementById('id').value;
var datastr = 'id=' + id;
//alert(datastr);
$.ajax({
type: "POST",
url: 'api.php',
data: datastr,
dataType: 'json',
success: function(data){
//var user_id = data[0];
//alert(user_id);
if(data.length > 0)
{
for(i=0; i<data.length; i++)
{
alert("User: " + data[i].user_id);
// here you have the user_id and any other fields from the table e.g. lat/long
}
}
}
})
}
Have a look at the Google Maps Polyline reference for how to plot the points:
http://code.google.com/apis/maps/documentation/javascript/reference.html#Polyline

Categories