I'm trying to work out how to get the parameter from a URL with PHP.
So my code starts with a bit of ajax firing the php and an alert with the response:
$.ajax({
url: 'blog/assets/php/load-blog.php',
dataType: 'json',
success: function(data){
alert(data);
}
});
Then I have my php:
<?php
//==== CONNECTION VARIABLE
$con = new mysqli($host,$user,$pass,$database);
//==== GET URL PARAMETER
$urlParam = $_GET["date"];
//==== FETCH DATA
$result = $con->query("SELECT * FROM $table WHERE DATE = '$urlParam'");
//==== CREATE ARRAY
$blogArray = array();
while ($row = $result->fetch_row()) {
$blogArray[] = $row;
}
//==== ECHO AS JSON
echo json_encode($blogArray);
?>
The URL would look something like this:
http://www.mysite.com/blog/?date=2013-05-14
The issue in all of this is the URL parameter isn't being selected correctly but I don't know what I've done wrong.
Javascript
var date = '2013-05-14';
$.ajax({
type: "GET",
url: 'blog/assets/php/load-blog.php',
dataType: 'json',
data: { date: date }
success: function(data){
alert(data);
}
});
PHP
<?php
//==== CONNECTION VARIABLE
$con = new mysqli($host,$user,$pass,$database);
//==== GET URL PARAMETER
$urlParam = $_GET["date"];
//==== PREPARED STATEMENT
$stmt = $con->prepare("SELECT id,name FROM __TABLE_NAME__ WHERE date = ?");
$stmt->bind_param("s", $urlParam );
$stmt->execute();
$stmt->bind_result($id, $name);
//==== CREATE ARRAY
$blogArray = array();
//==== FETCH DATA
while ($stmt->fetch()) {
$blogArray[] = array(
'id' => $id,
'name' => $name
);
}
//==== CLOSE STATEMENT
$stmt->close();
//==== ECHO AS JSON
echo json_encode($blogArray);
?>
Related
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);
}
}
I would check if my JSON response (data) is empty
$.ajax ({
type : 'POST',
url : get.php,
dataType: 'json',
success : function(data) {
console.log(data.lenght);
}
});
GET.PHP
$query = "SELECT * FROM TABLE";
$stmt = $this->db->mysqli->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
$_assoc = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$_assoc = $row;
}
$stmt->close();
echo json_encode($_assoc);
JSON RESPONSE
{"foo":"6","bar":"3436","id":4,"code":""}
EMPTY JSON RESPONSE
[]
I tried with data.length but returned undefined.
UPDATE
I solved this way.
Object.keys(data).length
Thanks for yours downvote!
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'];
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']";
I am trying to retrieve information from my php file which contains the following code. My code contains the colums Email, FirstName, LastName, and State.
$query = 'SELECT * FROM users WHERE LOWER(Email) = :email';
$stmt = $dbh->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();
if ($stmt->rowCount() == 1) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$firstName = $row['FirstName'];
$lastName = $row['LastName'];
$state = $row['State'];
} echo json_encode($row);
My Ajax code is:
$.ajax({
datatype: 'json',
type: "POST",
url: 'json-data.php',
success: function(data) {
//called when successful
$('#firstname').append(data.FirstName);
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
When I type $('#firstname').append(data);, it shows me the following output:
{"FirstName":"Foo","LastName":"Bar","State":"Florida","Email":"foo#bar.com"}
How do I make it so I can get only the first name and append it to a div?
try with:
var obj = jQuery.parseJSON(data);
$('#firstname').append(OBJ.FirstName);