I'm doing some assignment for school, and I'm stuck at passing array from js to php.
I have to say I'm not some expert and I'm still learning. I can't figure out what am I missing. Hope someone will help me.
I try like this.
if(bets.length > 0) {
$.ajax({
url: "mybet.php",
method: "POST",
data: { bets : JSON.stringify( bets ) },
success: function(res) {
console.log(res);
}
});
}
and php file
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($bets);
}
bets is an array in js.. and I want if I click on button proceed to collect that array and pass to php so I can work with it. I'm getting undefined index for bets on line $bets = json_decode($_POST['bets']);
print_r($_POST) is empty
You are not sending a 'proceedBet' variable in your ajax request, either you send that variable by changing the data like this:
if(bets.length > 0) {
$.ajax({
url: "mybet.php",
method: "POST",
data: { bets : JSON.stringify( bets ), proceedBet: 'Some Value' },
success: function(res) {
console.log(res);
}
});
}
Or you have to change your condition to check if the bets exist like so:
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($_POST['bets']); // use print_r to check the data in the array
// User::redirect("ticket.php");
}
Hi here is an example I made for you:
first the html part is a simple modal to display data from request.php if the data I send from my js array is okay:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" id="btnDisplayModal" >
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal" >×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<br>
<div id="add-takeout-messages">
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
the javascript part is an ajax call which display data inside the modal when the request is done:
$(document).ready(function() {
var formData = {id:"1",name:"stan",lastname:"chacon",color:"blue"};
function _ajaxMessage(formData){
return $.ajax({
url: "request.php",
type: 'POST',
data:{data:JSON.stringify(formData)},
dataType: 'json'
})
}
$("#btnDisplayModal").on('click', function(){
_ajaxMessage(formData)
.done(function(response){
console.log(JSON.stringify(response));
$('#add-takeout-messages').empty();
$.each(response.messages,function(index,value){
console.log(index,value);
$('#add-takeout-messages').append('<div class="alert alert-success">' +
'<button type="button" class="close" data-dismiss="alert">×</button>' +
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> From: '+ value.from + '<br>' + ' msg: ' + value.msg +
'</div>')
})
$("#myModal").modal();
})
})
})
The request.php file is simple like the request file you are already using, so I guess the problem you have is your array, maybe it has an invalid format and thats why it goes empty.
if (isset($_POST["data"])) {
$data = json_decode($_POST["data"],true);
if ($data["name"] == "stan") {
$array = [
"status"=>"success",
"messages"=> [
array('date' => "2019-04-11", 'msg'=>'Love you', 'from'=>'Annie' ),
array('date' => "2019-04-10", 'msg'=>'Have a nice day', 'from'=>'Annie' )
]
];
echo json_encode($array);
}
}
check your array ant let us know if that was the problem =)
Hiope it helps
Simple working example you can change the logic if needed.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
let bets = [1,2,3]; // This must come dynamically.
if(bets.length > 0) {
$.ajax({url: "server.php", method: "POST", data: { bets : JSON.stringify( bets) }, success: function(result){
$("#div1").html(result);
}});
}
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Send Ajax Request</button>
</body>
</html>
Server side
<?php
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($_POST['bets']);
}
Related
I have problem with hiding modal in bootstrap 4.
In my tmp function I have to close modal after that I need use method update_table(url)
HTML and JS
<div class="modal" id="Modal" tabindex="-1" role="dialog"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script type="text/javascript">
function abrir_modal(url) {
$('#Modal').load(url, function () {
$(this).modal('show');
});
return false;
}
function tmp(url) {
$('#Modal').on('shown.bs.modal', function (e) {
$("#Modal").modal('hide');
})
update_table(url);
}
function update_table(url) {
$.ajax({
type: "GET",
url: url
})
.done(function () {
refresh_table();
});
}
function refresh_table() {
$.ajax({
type: "GET",
url: "{% url 'Project:Task_Schedule_TableView' %}"
})
.done(function (response) {
$("#_appendHere").load("{% url 'Project:Task_Schedule_TableView' %}" + "#_appendHere");
});
};
function hide_modal() {
console.log($('#Modal').modal('name'))
$('#Modal').modal('hide');
console.log(33)
return false;
}
</script>
I don't know what is wrong but when I try use the hide_modal function instead of the tmp function, modal is hidden.
This is simple code for Bootstrap 4 Modal Pop Up which hide the pop up.
You can check this..
$('#Modal').modal('show');
function tmp(url) {
$("#Modal").modal('hide');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<div class="modal" id="Modal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
When the pop up is shown call this function from browser console.. tmp('http://test/test'); it will hide the pop up. It same as Bootstrap 3
Step 1. Remove these lines from your code
$('#Modal').on('shown.bs.modal', function (e) {
$("#Modal").modal('hide');
})
Step 2. put the hide_modal function top of all code.
Then it will be appeared properly.
I am pretty new to web programming specially javascript and other front end logic. I am seeing this weird error where my code works perfectly fine on latest version of Firefox on Windows 10 but does not work on latest version of chrome on Windows 10.
Basically I have a form which consists of two multi select drop down and two buttons. For both these buttons, I send ajax POST request in their click listener with checkbox params to python flask server which in turn creates a file on the server then in success of my POST ajax, I send get request to download the file that I just created. In Firefox and chrome both, my POST calls are going and files are being generated correctly, however get request is not sent by chrome to download the file but firefox is sending correct get request to get the file.
Another weird thing is, chrome does download a file upon get request which it is sending somewhere but it is not reaching my server. I do not see get request in my flask server log from chrome but it does show up for firefox. In both cases files are downloaded but chrome downloads wrong file from some wrong place.
I also tried adding delay on server thinking, file is still being generated when POST request is returned but that also didn't change chrome behaviour.
Below is the snippet of my code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" type="image/x-icon" href="static/images/main.png">
<title>Link Curation - Curated Results</title>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="static/js/materialize.js"></script>
<script src="static/js/init.js"></script>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="static/css/materialize.css" type="text/css" rel="stylesheet" media="screen"/>
<link href="static/css/style.css" type="text/css" rel="stylesheet" media="screen"/>
<script>
$(document).ready(function(){
$('#progress').hide();
$('select').material_select();
// Download jsonlines
$("#jlines").click(function(e){
// Required for non-chrome browser
e.preventDefault()
var tags = $('#museums').val();
var codes = $('#codes').val();
var userObj = new Object();
userObj.data = {"tags":tags,"codes":codes,"type":"jlines"};
json_data = JSON.stringify(userObj);
console.log(json_data);
var sv = '{{server}}'.concat("/download");
$.ajax({
method: 'POST',
url: sv,
data: json_data,
contentType: 'application/json',
beforeSend: function(){
$('#progress').show();
document.getElementById("jlines").disabled = true;
console.log("downloading...")
},
success: function(data){
console.log("File Created!");
$('#progress').hide();
document.getElementById("jlines").disabled = false;
window.location.href = "/download?type=jlines";
},
error: function(xhr){
console.log('Request Status: ' + xhr.status + ' \nStatus Text: ' + xhr.statusText + ' \nResponse Text: ' + xhr.responseText);
Materialize.toast("Something went wrong. Please try again!",5000);
$('#progress').hide();
document.getElementById("jlines").disabled = false;
}
});
});
// Download triples
$("#triples").click(function(e){
// Required for non-chrome browser
e.preventDefault()
var tags = $('#museums').val();
var codes = $('#codes').val();
var userObj = new Object();
userObj.data = {"tags":tags,"type":"triples"};
json_data = JSON.stringify(userObj);
console.log(json_data);
var sv = '{{server}}'.concat("/download");
$.ajax({
method: 'POST',
url: sv,
data: json_data,
contentType: 'application/json',
beforeSend: function(){
$('#progress').show();
document.getElementById("triples").disabled = true;
console.log("downloading...")
},
success: function(data){
console.log("File Created!");
$('#progress').hide();
document.getElementById("triples").disabled = false;
window.location.href = "/download?type=triples";
},
error: function(xhr){
console.log('Request Status: ' + xhr.status + ' \nStatus Text: ' + xhr.statusText + ' \nResponse Text: ' + xhr.responseText);
Materialize.toast("Something went wrong. Please try again!",5000);
$('#progress').hide();
document.getElementById("triples").disabled = false;
}
});
});
});
</script>
<style>
#body {
min-height: calc(100vh - 10px);
}
</style>
</head>
<body>
<div>{% include 'header.html' %}</div>
<div id="body">
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<div class="row center">
<br><br>
<h5> Download the curated results (Tip: Select ulan to download all data!) </h5>
<br><br>
<div class="header col s12 m4">
<select multiple id="museums" >
<option value="" disabled selected>Choose museum(s)</option>
{% for tag in keys %}
<option value={{tag}}>{{tag}}</option>
{% endfor %}
</select>
</div>
<div class="header col s12 m4">
<select multiple id="codes">
<option value="" disabled selected>Choose pair status(s)</option>
<option value="3">Match</option>
<option value="4">Unmatch</option>
<option value="5">Not Sure</option>
</select>
</div>
<div class="header col s12 m4">
<form name ="download_data">
<div id="progress" class="preloader-wrapper small active">
<div class="spinner-layer spinner-green-only">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
<button id = "jlines" type="submit" class="btn" >Jsonlines</button>
<button id = "triples" type="submit" class="btn" >Triples</button>
</form>
</div>
</div>
</div>
</div>
<div class="section no-pad-bot">
<div class="container">
<div class="row center">
<h5>Curated results from all museums will show up below. You can sort them based on the status or URI or even search based on museum.</h5>
<br><br>
<iframe class="header col s12 light" src="datatable" style="border:0" height="1000" ></iframe>
</div>
</div>
</div>
</div>
<div>{% include 'footer.html' %}</div>
</body>
</html>
Thanks for the help.
Nilay
var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
$(document).ready(function() {
var $loader = $("#btn"),
$insertion=$("#insertionPoint");
$loader.click(function() {
$.ajax({
url:quoteUrl ,
dataType: 'json',
success:function(data){
var quote=data.quoteText;
$insertion.replaceWith('<p>'+quote+'</p>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Random quote Machine</h1>
<div id="insertionPoint">
<p>Quotes come here</p>
</div>
<button id="btn">Next Quote</button>
Task:To gain a quote from forimastic.com's Api
Result: Nothing is Happening
Additional:How can I add codes to make it to gain random quotes if this works?
I got it to work by using jsonp and its callback, following the manual from the API's website.
And I even made it prettier :D
var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=parseQuote&lang=en';
$(document).ready(function() {
$("#btn").click(function() {
$.ajax({
url:quoteUrl ,
crossDomain: true,
jsonpCallback: 'parseQuote',
dataType: 'jsonp',
success:function(data){
$("#insertionPoint>#quote").html(data.quoteText);
$("#insertionPoint>#author").html(data.quoteAuthor);
}
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<h1>Random quote Machine</h1>
<blockquote id="insertionPoint">
<span id="quote">Quotes come here</span>
<footer id="author">Author comes here</footer>
</blockquote>
<button class="btn btn-info" id="btn">Next Quote</button>
You should change #insertionPoint's html instead of replacing it, otherwise the function will no further work since this element will no longer exist.
Replace
$insertion.replaceWith('<p>'+quote+'</p>');
with
$insertion.html('<p>' + quote + '</p>');
i don't know why $.ajax never called on my code ?
i use xampp as localhost
jquery called ok , so when i click on the button , the text below it changed .. but $.ajax part never execute ?
my page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script type="text/javascript" src="layout/js/jquery-1.12.4.min.js">
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
my js :
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
and my moremore.php :
<div class="alert alert-success"> alerts alerts by ajax </div>
1) Look for console.log errors or errors in network header
2) Make sure you .php script where you are requesting the ajax, has major headers to allow access control.
3) Sometimes, the headers doesn't allow to make you request.
4) When making request, keep your console opened (F12) and enable Log XMLhttpRequest
Try adding these headers to you moremore.php
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
header("Access-Control-Allow-Origin: http://localhost");
Also to give it a try, check the ajax request with the ajax header, add this too in your moremore.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo '<div class="alert alert-success"> alerts alerts by ajax </div>';
} else {
echo 'no ajax';
}
This will give you an idea if ajax request is working fine or not.
New ajax js:
$(document).ready(function() {
$('#btn').click(function() {
var ID = $(this).attr('id');
$(this).html("Loading ... ");
$.ajax({
type: "POST",
url: "http://localhost/my_projects/testing/moremore.php",
data: {
id: ID
},
cache: false,
xhrFields: {
withCredentials: true
},
dataType: html,
success: function(html) {
$('.container').append(html);
$('#btn').html("done");
},
error: function() {
alert("Something went wrong");
$("#btn").html("hmmmm, it was called... ");
}
});
});
});
Do leave comments for more help!
I tested your code, and it pretty much works as is. The only thing that I changed was the ajax url from absolute http://localhost/my_projects/testing/moremore.php to relative moremore.php and I threw in the official jQuery CDN in case yours was borked.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="http://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script>
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
moremore.php:
<div class="alert alert-success"> alerts alerts by ajax </div>
Results in this expected output after a couple clicks:
Try to wrap anonymous function, and change selector document to '#btn'
(function($) {
$('#btn').on('click',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
})(jQuery);
i know that this question is a bit childish but i am unable to find the correct solution to this problem...
i am using jquery and ajax call to user search functionality in website with php returning json objects...
when i search users using php file, if the json return is only one array, the jquery prints it on the screen, but when multiple results are returned, i don't know to print them out....
here are the results returned from the php:
{"search":"10
junaid
saleem
junaid#yahoo.com
"}{"search":"13
zzz
aaa
zzz#yahoo.com
"}
and here is the jquery webpage:
<?php
session_start();
require("secure_scripts/getusers.php");
require("secure_scripts/getdp.php");
require("secure_scripts/getusersinfo.php");
if(!isset($_SESSION['id'])){
header("location: index.php");
}else{
$zxcv_lgn = base64_encode($_SESSION['id']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome <?php echo getusers("first_name"); ?> | Addressbook.com</title>
<script src="jquery.js" type="text/javascript" ></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
$(document).ready(function(){
$("#search_button").click(function(){
$("#search_button").click(function(){ $("#console_loader").hide(); });
$("#console_loader").fadeIn("slow").html("<img src='images/ajax-loader.gif' id='ajax-loader' />");
var send = $("#search").val();
$.ajax({
type: "POST",
url: "secure_scripts/search_users.php",
data: {search: send},
dataType: "json",
success: function(msg){
$("#ajax-loader").fadeOut("slow", function(){
$("#console_loader img").remove();
$("#console_loader").fadeIn("slow").html(msg.search);
});
}
});
});
});
</script>
</head>
<body>
<div id="header">
<p><img src="images/header_logo.png" /><span>AddressBook™</span></p>
</div>
<div id="wrapper" align="center">
<div id="main">
<div id="content">
<div id="top_nav">
<div class="userinfo"><span class="user_title">Welcome <?php echo getusers("first_name")." ".getusers("last_name"); ?></span></div>
<div class="search">
<form onsubmit="return false" id="search_form">
<input type="text" name="search" class="search_box" id="search" placeholder="Type in to search...">
<input type="button" id="search_button" class="sea" name="search_submit"value="search">
</form>
</div>
</div>
<div id="left_nav">
<div id="dp"><img src="<?php echo getdp(); ?>"></div>
<div class="left_nav_links">Profile</div>
<div class="left_nav_links">Contacts</div>
<div class="left_nav_links">Settings</div>
<div class="left_nav_links">privacy</div>
<div class="left_nav_links">logout</div>
</div>
<div id="console">
<div id="console_top_nav">Your Contacts:</div>
<div id="console_content">
<div id="console_loader" style="display: none;"></div>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="links"><ul><li>Home</li><li>About</li><li>Contact</li></ul></div>
<div id="copyrights">© 2014 Addressbook.com All Rights Reserved</div>
</div>
</div>
</body>
</html>
whenevery only one object is returned from php, like:
{"search":"13
zzz
aaa
zzz#yahoo.com
"}
it works perfectly, but not with multiple json objects....
thanks in advance!
You need to use jQuery's .each() method, like this:
$(document).ready(function(){
$("#search_button").click(function(){
$("#search_button").click(function(){ $("#console_loader").hide(); });
$("#console_loader").fadeIn("slow").html("<img src='images/ajax-loader.gif' id='ajax-loader' />");
var send = $("#search").val();
$.ajax({
type: "POST",
url: "secure_scripts/search_users.php",
data: {search: send},
dataType: "json",
success: function (msg) {
$.each(function (index, item) {
$("#ajax-loader").fadeOut("slow", function () {
$("#console_loader img").remove();
$("#console_loader").fadeIn("slow").html(item.search);
});
});
}
});
});
});
When your json is received, it is more than likely an array of objects
[{"search":"10
junaid
saleem
junaid#yahoo.com
"}{"search":"13
zzz
aaa
zzz#yahoo.com
"}]
Therefore, by using $.each() to loop through the collection and return the value (index, item) you can get the object's value by referencing it like so:
$("#console_loader").fadeIn("slow").html(item.search);
since json is returning a JavaScript object literal.
Something like this should work:
$.ajax({
type: "POST",
url: "secure_scripts/search_users.php",
data: {search: send},
dataType: "json",
success: function(msg){
$.each(function() {
$("#ajax-loader").fadeOut("slow", function(){
$("#console_loader img").remove();
$("#console_loader").fadeIn("slow").html(msg.search);
});
});
}
});
We're adding $.each() method to the success function in order to run it for each JSON object that gets returned, not just the first.
Here's the jQuery.each() doc for further reading.
edited for clarity