simple jquery fetch from mysql - php

I am trying to use jQuery with MYSQL and I wrote something like this :
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function example_ajax_request() {
$('#example-placeholder').html('<p>Loading results ... <img src="ajax-loader.gif" /></p>');
$('#example-placeholder').load("loadres.php");
}
</script>
</head>
<body>
<div id="query">
<select name="show" id="box" >
<option value="0">Select A Test</option>
<option value="All">--All--</option>
<option value="M1">Model1</option>
</select>
<input type="button" onclick="example_ajax_request()" value="Click Me!" />
</div>
<div id="example-placeholder">
<p>Placeholding text</p>
</div></body>
</html>
Basically I want to pass parameters to the loadres.php file. But unable to figure out the exact way to do.
Any help is appreciated.
Thanks.

You should use the $.ajax() method from jQuery. you can pass data to the url and have a callback at the end.
$.ajax({
url: 'loader.php',
data: 'somedata',
type: 'GET',
success: function(data){
$('#example-placeholder').text(data);
}
});
This will do the trick. This method also provides far more flexibility. You can have different functions such as error functions and complete functions.

$('#example-placeholder').load("loadres.php?show=" + $('#box option:selected').val());
This will use jquery to get the selected value from the drop down list and append it to the URL as a querystring parameter, which you can access in the loadres.php page.

similar to saif-bechan's post you can use ajax with post and data can hold an object to pass multiple parameters
$.ajax({
type:"POST",
url: loadres.php,
data: {
foo:'bar',
selected:$('#selector').val()
},
dataType: 'json',
error: function(data) {
//error code here
},
success: function(data) {
//success code here
}
});
I will also note that is is better to put your click event in jquery context not in the html
so in script somewhere use
$('#button_id').click(function(){
//call to ajax
};

Related

PHP not capture $_POST data send by ajax jquery on same page

I am using ajax to post data on the same page and trying to echo posted data with php with following script.
$('button').click(function(){
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function(){},
success: function(data){alert(data)},
error: function(err) {alert(err.responseText);}
})
})
and php script is :
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
my html is:
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
My problem is php does not echo posted data on page, but when i post form data on another php file which is same php script; php is able to echo posted data and ajax is alert that. please help me to resolve this issue. thanks
It's difficult to tell without seeing your entire PHP page as one listing, but from your description it sounds like your issue is either because of the way you are declaring your .click() event or the way you are posting to the page. The former is more likely.
The $.ajax() request will use an XMLHttpRequest object to POST to your PHP script. The PHP script should then take those values and generate the return string from the combination of the plain text in the script and the inserted echo'd values. This should then be received by the success method's callback function and alerted to your page as a blob of HTML text in the alert box.
Indeed, this is exactly what happens if I use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function() {},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err.responseText);
}
});
});
});
</script>
</head>
<body>
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
</body>
</html>
However, if I comment out the lines for $(document).ready(function(){ and its corresponding end });, then nothing happens when I click.
So, try wrapping your .click() event definition in a $(document).ready().

ajax with Jquery can't make working in wordpress

I am writing a plugin for a wordpress, where I use jquery for AJAX.
Following code doesn't work. I expect to show the content in results div when I type in input box.
Here is the code I use for ajax request. It is located on my theme header file.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
//alert("sjsjs");
$("#se").keypress(function(e){
// e.preventDefault();
var search_val=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_string:search_val
},
success:function(data){
$('#results').append(response);
}
});
});
});
</script>
html content in template file
<form name="nn" action="" method="post"></br></br>
<input id ="se" type="text" name="test" width="20" />
<input type="submit" id="clicksubmit" value="Submit" />
</form>
<div id="results">val is:
</div>
Here is the code in plugin file
function wpay_search() {
//global $wpdb; // this is how you get access to the database
$whatever = $_POST['search_val'];
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
add_action('wp_ajax_wpay_search', 'wpay_search');
add_action('wp_ajax_nopriv_wpay_search', 'wpay_search');
I am new to wordpress plugin writing. Can anybody tell that where I have done the mistake?
Well one thing that obviously jumps out to me is this...
success:function(data){
$('#results').append(response);
}
Should be...
success:function(data){
$('#results').append(data);
}
Because you have no variable called response, you passed the function data as a variable, so you have to use that.
Also, you're passing search_string as a paremeter, when infact in your php file, the $_POST is looking for search_val.
So you need to send search_val as parameter and give your JavaScript search_val variable another variable name in the JavaScript, just for less confusion. In this case I made it search.
action:'wpay_search',
search_val:search
So overall it should look something like this...
$("#se").keypress(function(e){
e.preventDefault();
var search=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_val:search
},
success:function(data){
$('#results').append(data);
}
});
});

retrieve value from database when onchange in dropdownbox by jquery

This is my html code
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
and my database table is like this
courseId courseName courseCredits
1 Diploma in Computing 5
So my request is, if i change the value in the 'select' the 'courseCredits' value should appear in the textbox. for this how can i write jquery code?
"Ajax with Jquery" is what your are looking for. It will work like this:
the user chooses an option from the select box
you submit via Javascript the chosen option to a PHP script
the php script fetches the data from the database
the php script returns the result as json encoded data
there is a callback function in your javascript code. This js code will manipulate the HTML in whatever way you want, e.g. "add the option to your select box"
There are tons of tutorials on how to do Ajax requests in detail, e.g. http://openenergymonitor.org/emon/node/107
Check out one of those tutorials - eventually you will want to update your question so that it becomes a bit more specific? :-)
it is good practice to seperate you html from scripts so i would like to change :
<select name="course" id="course" onchange="valuesOfAll(this.value)">
to
<select name="course" id="course" >
then my script will be following (hoping you add reference of latest jquery )
<script>
$(document).ready(function(){
//bind change event once DOM is ready
$('#course').change(function(){});
getResult($(this).val());
});
function getResult(selectedValue){
//call ajax method to get data from database
$.ajax({
type: "POST",
url: url,//this should be replace by your server side method
data: "{'value': '"+ selectedValue +"'}", //this is parameter name , make sure parameter name is sure as of your sever side method
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (Result) {
alert(Result.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
use $.post.. (ajax or get)... i am using post here....go through the docs if you want to read more about jquery post..
javascript
function valuesofAll(val){
$.post('test.php',{data:val},function(result){
$('#course_credits').val(result.coursecredit)
}, "json"); //expect response as json..
}
test.php
$data=$_POST['data']; //this is the value posted
//make you query in db get result..
$courseCredits= $row; //db returned courseCreadit value
echo json_encode(array('coursecredit'=>$courseCreadits)); //send response as json
this will helps you .....
<script>
function valuesOfAll(value)
{
var base_url="http://.../../hello.php";
var ip=new Object();
ip.course=value;
var inputParam=JSON.stringify(ip);
var module="getcourseCredits"
$.ajax({
type: "POST",
url: base_url,
data: {coursevalue:inputParam,module :module},
dataType: "json",
success: function(msg)
{
$("#course_credits").val(msg.credit);
}
});
}
</script>
<body>
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
</body>
In your PHP file
<?php
if(isset($_POST['module']))
{
if($_POST['module']=='getcourseCredits')
{
$val=json_decode($_POST['coursevalue'],true);
$courseval=$val['course'];
// do the connectivity and query here and finally echo the result as json format that is the response to the ajax call
.
.
.
.
}
}
?>

jQuery PHP passing values within functions vs live clicking?

I'm trying to pass some values through onclick which to me is so much faster. But I need to use some kind of "live" clicking and I was looking into .on() or .delegate(). However, if I do any of those, passing those values within followme() seems a little harder to get. Is there some kind of method that I'm not seeing?
<div class='btn btn-mini follow-btn'
data-status='follow'
onclick="followme(<?php echo $_SESSION['user_auth'].','.$randId;?>)">
Follow
</div>
function followme(iduser_follower,iduser_following)
{
$.ajax({
url: '../follow.php',
type: 'post',
data: 'iduser_follower='+iduser_follower+'&iduser_following='+iduser_following+'&unfollow=1',
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text('Follow');
}
});
}
As you can see, its easier to just pass values from PHP to jQuery... Is there another way?
You can assign more data values, and you know what use is logged in, all you need is to pass who to follow:
<div class='btn btn-mini follow-btn'
data-status='follow'
data-who='<?php echo $randId; ?>'
id='followBTN'>
Follow
</div>
<script>
$('#followBTN').on('click', function(){
$.ajax({
url: '../follow.php',
type: 'post',
data: {
iduser_following: $(this).attr('data-who')
},
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text(data.text);
}
});
});
</script>
You can process $_SESSION['user_auth'] and the status directly from PHP, there is no need for you to pass them in jQuery. Make sure document is ready when you insert on click event.
just use the jquery 'on' event. Attach a new attribute called data-session to the div and then retrieve it using .attr method. You have the example bellow to show you an alert with the data, you just have to substitute it with your code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '#follow-me-button', function(){
alert($(this).attr('data-session'));
})
})
</script>
</head>
<body>
<div id="follow-me-button" class='btn btn-mini follow-btn' data-status='follow' data-session ="MY-SESSION-DATA-FROM-PHP">
Follow
</div>
</body>
</html>

jQuery Ajax post for newbie

First let me say I'm new to Ajax. I've been reading articles from jquery.com and some tutorials but I didn't figured it out yet how this works on what I'm trying to achieve.
I am trying to get the weather for a searched city using Google's Weather API XML, without page refresh.
I managed to retrieve the Weather XML and parse the data but everytime I search for a different place, the page reloads since my weather widget is under a tab.
This is what I have in my HTML:
<script type="text/javascript">
$(document).ready(function(){
// FOR THE TAB
$('.tab_btn').live('click', function (e) {
$('.tab_content').fadeIn();
});
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
aysnc:false,
success:function(result){
$(".wedata").html(result);
}});
});
});
</script>
<style>.tab_content{display:none;}</style>
</head><body>
<input type="button" value="Show Content" class="tab_btn">
<div class="tab_content">
<h2>Weather</h2>
<form id="searchform" onKeyPress="return submitenter(this,event)" method="get"/>
<input type="search" placeholder="City" name="city">
<input type="hidden" placeholder="Language" name="lang">
<input type="submit" value="search" class="submit" style="width:100px">
</form>
<div id="weather" class="wedata">
</div>
</div>
And here is the actual demo I'm working on: http://downloadlive.org.
Now, if I add action="weather.php" on the search form I get the results, but I get redirected to weather.php which is logical. Without the action="weather.php", everytime I search my index which I'm on, adds up /?city=CITY+NAME which shouldn't. This should be added to weather.php, get the results and then retrieve them back into my index, if that makes sense?
This is my php code for weather.php: http://pastebin.com/aidXCeQg
which can be viewed here: http://downloadlive.org/weather.php
Can someone please help me out with this please?
Thanks alot
You just need to return false; from the click event handler. This will prevent the default action from occuring - in this case, submitting the form. Also, remove the async: false setting. You almost never want synchronous ajax requests.
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});
Alternately you can pass a parameter name to the callback and then use event.preventDefault() to accomplish the same result as above:
$(".submit").click(function(e){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
e.preventDefault();
});
You need to send the form data with the POST. It's super-easy to do this using .serialize().
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
data: $(this.form).serialize(),
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});

Categories