php jquery iterate php array in success function - php

I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.

In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});

change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,

You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";

Related

How to get ajax json loop response in javascript

I am using ajax call for sending value to php file and get response back into first page,(work fine), but when i am getting the result in loop form this response nothing will be return on first page.
My first page:
$.ajax({
url: "action.php",
method: "post",
data: {
'trader': selected_trader
},
dataType: 'JSON',
success: function (response) {
$('#date').html(response['date']);
$('#symbol').html(response['symbol']);
$('#status').html(response['status']);
$('#alert').html(response['alert']);
$('#company_name').html(response['company_name']);
}
})
My 2nd page:
if (isset($_POST['trader'])) {
$trader = $_POST['trader'];
$sql = "Select * from current_trader where status='$trader' ";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$data["date"] = date('Y:m:d', strtotime($row['date']));
$data["symbol"] = $row['symbol'];
$data["company_name"] = $row['company_name'];
$data["alert"] = $row['alert'];
$data["status"] = $row['status'];
echo json_encode($data);
}
}

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

How to Retrieve Values Resulting From AJAX Live Search?

Below is a jQuery function that retrieves 2 textbox values and posts them to another file ("Student Search Results.php"), where a live search is run using the values.
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {
query: Search_Data
},
cache: false,
success: function() {
alert('The values were sent');
}
});
});
</script>
Below is the PHP script on the search page ("Student Search Results.php") that makes use of these values.
<?php
include "Connection.php";
if(isset($_POST['query'])){
$searchData = explode('?????', $_POST['query']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
echo $query;
?>
How would I be able to take variables from the PHP script (such as $result) to the first page, so I can create a result table? Simply including the PHP file does not work, as the file is only included once.
Thank you for your time.
Best option is to serialize to JSON using json_encode
I think best you can do is,
success: function(result) {
alert(result);
}
and Student Search Results.php print result in tabular format.
P.S. : Please follow proper file naming convention
use a proper URL, and send the data (and stop using camelcase for everything) :
$(".search").on('keyup', function() {
var data = {
team_name : $('#TeamName').val(),
teacher : $('#Teacher').val()
}
$.ajax({
type: "POST",
url: "student_search_results.php",
data: data,
cache: false
}).done(function(result) {
console.log(result);
});
});
And in PHP, you have to actually get the result into an array and json_encode it :
<?php
include "Connection.php";
$team_name = !empty( $_POST['team_name'] ) ? $_POST['team_name'] : null;
$teacher = !empty( $_POST['teacher'] ) ? $_POST['teacher'] : null;
if ($team_name && $teacher) {
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
?>
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = "Team_Name="+'Team_Name'&Teacher='+Teacher;
$.ajax({
type: "POST",
url: "Student_Search_Results.php",
data: Search_Data,
cache: false,
success: function(result) {
$('$output').html(result);
}
});
});
</script>
Here is output div
<div id="output"></div>
On Student_Search_Results.php page get
$tname = $_POST['Team_Name'];
$teacher = $_POST['Teacher'];
//your search query & print data

workout with the php returned array to jquery

my this php code is working for the $.ajax call which is below this code
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
//$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[]=$row['imgurl'];
}
}
echo $imgurl;
jquery code
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#main-content').html(data);
}
});
});
});
it outputs just Array written at the #main-content div how to work with that array which are basically image paths
Why you create array from mysql result ? your code can be simpler like this:
<?php
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
if(mysql_num_rows($result) > 0)
{
//Fetch rows
while($row = mysql_fetch_array($result))
{
echo $row['imgurl'];
}
}
?>
Try you page from the browser directly. Using JSON can help here:
echo json_encode($imgurl);
and using getJSON instead of plain ajax:
$.getJSON('thegamer.php', {send_text:text}, function(data) { … });

Parsing values in JSON

I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.

Categories