Ajax separate data which came from mysql - javascript

I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});

jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);

instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax

Related

How to use AJAX to call php file from javascript file

I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct

ajax jquery errors on json return value from php script

I'm having problems with this ajax/jquery programming.
I've tried many different things but nothing has worked.
Ajax posts selItem to ajaxsql.php, this works!
The sql query in ajaxsql.php works, cause it outputs this if i call the script directly in the browser: [{"forumname":"SDE forum","user":"michael","txt":"Jeg hedder Michael!"}]
The problem is that the ajax function shows an alert box with Error[object Object]
forum.php script:
<script type="text/javascript">
function ForumChat(selItem) {
$.ajax({
type: "POST",
url: 'ajaxsql.php',
data: { selectedItem : selItem.value },
dataType: "json",
success: function(data) {
alert(data);
$('#txtarea').html(data);
},
error: function(data) {
alert('Error' + data);
}
});
}
</script>
ajaxsql.php script:
<?php
if(!isset($_SESSION))
{
session_start();
}
include('class.php');
//$sel = $_POST['selectedItem'];
$sel = "SDE forum";
$sql = " SELECT * FROM forum WHERE user = '".$_SESSION['currentuser']."' AND forumname = '".$sel."' ";
$result = mysqli_query($_SESSION['con'], $sql);
while($row = mysqli_fetch_array($result))
{
$forumname = $row['forumname'];
$user = $row['user'];
$txt = $row['text'];
$return[] = array("forumname" =>$forumname, "user" =>$user, "txt" =>$txt);
}
echo json_encode($return);
?>
because ajaxsql.php returns object ..
what you can do in your ajax is
success: function(response) {
$('#txtarea').html('');
$.each(response.data, function(){
console.log(this);
$('#txtarea').append(data);
});
},

jQuery PHP Mysql jSon show the data on loop

I have jQuery Ajax Autosuggest using jSon.
Now I have problem when showing the data. The data get from mysql data using PHP (looping data) but when get the result, it always show 1 row.
Here is my js code:
$.ajax(
{
type: "GET",
data: post_string,
dataType: "json",
cache: false,
url: 'search.php',
success: function(data)
{
full_name = data[0].full_name;
username = data[0].username;
$("#divResult").show();
$(".display_box").html(username);
}
});
and the search.php
$getSearchWord = mysqli_real_escape_string($con, $_GET['searchword']);
$json = array();
$searchQuery = mysqli_query($con, "SELECT * FROM tb_users WHERE username LIKE '%$getSearchWord%' OR full_name LIKE '%$getSearchWord%' LIMIT 5");
while($searchFetchData = mysqli_fetch_array($searchQuery))
{
$json[] = array(
'username' => $searchFetchData['username'],
'full_name' => $searchFetchData['full_name']
);
}
echo json_encode($json);
and html div to display
<div id="divResult">
<div class="display_box"></div>
</div>
Json
To clear out the field, call this before the Ajax request:
$("#divResul").hide(200);
$(".display_box").html('');
You can try to run all returned array before putting it in your .display_box. Get the length of array returned from search.php then run it in a loop.
success: function(data){
$("#divResult").show(200);
var n = data.length;
for(var x = 0; x < n; x++){
$(".display_box").append(data[x].full_name);
$(".display_box").append(data[x].username);
}
}
No Json
OR without using json. From your search.php:
$table = '<table>';
$getSearchWord = mysqli_real_escape_string($con, $_GET['searchword']);
$json = array();
$searchQuery = mysqli_query($con, "SELECT * FROM tb_users WHERE username LIKE '%$getSearchWord%' OR full_name LIKE '%$getSearchWord%' LIMIT 5");
while($searchFetchData = mysqli_fetch_array($searchQuery))
$table .= '<tr>
<td>'.$searchFetchData['username'].'</td>
<td>'.$searchFetchData['full_name'].'</td>
</tr>';
}
$table .= '</table>';
echo $table; /* RETURN THIS TO YOUR AJAX REQUEST */
Then on your Ajax request:
$.ajax(
{
type: "GET",
data: post_string,
url: 'search.php',
success: function(data)
{
$("#divResult").show(200);
$(".display_box").html(data);
}
});
In ajax send data like this, it may work for you
$.ajax(
{
type: "GET",
data : { searchword: "keyword"},
dataType: "json",
cache: false,
url: 'search.php',
success: function(data)
{
full_name = data[0].full_name;
username = data[0].username;
$("#divResult").show();
$(".display_box").html(username);
}
});
Please try this in your success callback. All you need is to iterate with a $.each() and append to the div.
success: function(data)
{
$.each(data,function(index,value) {
full_name = value[0].full_name;
username = value[0].username;
$(".display_box").append(username . '<br/>');
})
$("#divResult").show();
}

How to pass multiple variables from a php file to ajax and use them?

I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console

how to retrieve echo data from php to jquery 1 by 1

I have a JQuery on click that sends a php query to MySql and then I want to send the data back 1 by 1 on JQuery.
But I only know how to send back results from php to JQuery as a whole.
my current JQuery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
alert(data);
}
});
});
});
my current php:
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['UserID'];;
echo $row['EmailAddr'];
}
?>
the outputs are both UserID and EmailAddr, I don't know how to just display either the UserID or EmailAddr out only
I tried alert(data[0]), but it only displayed one letter of the result.. Any ideas on how to do this?
UPDATE: After sean's help i have the current updated code
Jquery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
PHP
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
In your php, save the results to an array -
<?php
include 'dbAuthen.php';
$array = array(); // create a blank array
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// add each result to the array
$array[] = array('UserID'=> $row['UserID'], 'EmailAddr'=> $row['EmailAddr']);
}
echo json_encode($array); // json_encode() the array
?>
Then in your js/ajax you can loop through each value
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
// loop through each returned value
$.each(data, function(){
//alert each result, this is just an example as alert() for each result is not a great idea
alert("UserID:"+ this.UserID + " EmailAddr:" + this.EmailAddr);
});
}
});
});
});
jquery
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
php
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>

Categories