JQuery/AJAX - How To? Better Outcome? - php

DataPull.php:
CASE "CityList":
echo "<select style='width:132px;height:243px;' size='17' id='CityListA' name='CityListA' onChange='SubCityList(this.value);'>";
$result = $db-> query("SELECT region_id,region_name FROM dwrel_region ORDER BY region_name");
while ($row = $db-> fetch_assoc($result)){
echo "<option value='".$row["region_id"]."'>".$row["region_name"]."</option> \n";
}
echo "</select>";
break;
JavaScript:
function CityList(){
try{var xmlhttp=new XMLHttpRequest();}catch (e){try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}catch (e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch (e){return false;}}}
xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200){getEl("CityList").innerHTML=xmlhttp.responseText;}}
eMsg = "DataPull.php?get=CityList";
xmlhttp.open("GET",eMsg);
xmlhttp.send();
}
It works just fine for me. Was reading around JQuery/AJAX and surprised you could do it via $(function(){}); part.. but I don't or can't begin to understand where and how to put it together "as is" with the code I have above. Hopefully someone out there is kind enough to guide me to the right direction using AJAX, pulling and output results.
Was trying to understand how to be able to use this, even reading mentioned the use of JSON? (I think) or data "as is", something.. Oh I don't know.. Anyways, hopefully someone could help me put this together and then I could understand it even better.
Thanks!
EDIT:
After weeks from this post, learned a new way to do this:
in CSS:
.LoaderIcon {width:100%;height:100%;background:url('./images/Loading.gif') no-repeat center center;}
in JQuery:
$.ajax({
beforeSend: function(){ $('#SOMEID').addClass('LoaderIcon'); },
url: "SOME PARAMETER",
success:function(data){
$('#SOMEID').removeClass('LoaderIcon');
$('#SOMEID').html(data)
}
This has been working like charm for me, hopefully it would benefit others :)
});

Try this
function CityList(){
$("#YOUR_SPINNING_DIV_ID").html('<img src="PATH_TO_SPINNINGANIM_GIF"');
$.ajax({
url: "DataPull.php?get=CityList",
success: function(data ){
$("#CityList").html(data );
$("#YOUR_SPINNING_DIV_ID").html("");
}
});
}
and then call this function on any event that you are observing like button clicks or window onload. If you are doing it on windown onload then Jquery equivalient will be
$(document).ready(function() {
$.ajax({
url: "DataPull.php?get=CityList",
success: function(data ){
$("#CityList").html(data );
}
});
)};

Something like this in your jQuery(document).ready()
$.ajax({
type:'GET',
url:'DataPull.php',
data:'get=CityList',
success:function(msg){
alert('Success!\n\n+'+msg);
},
error:function(msg){
alert('Error!\n\n'+msg);
}
});
Where msg is the echo from the given PHP file. Read more about it on the jQuery website.

Related

Wordpress jQuery initialize widgets.php area

Hey guys I'm having a huge problem initializing jQuery on the backend of WordPress (widgets.php). I'm building a widget to display some select options that can only be accessed through SOAP, so I had to ajaxify it using admin-ajax.php. Everything works perfectly on the front-end but when it comes to the backend it breaks completely.
function widget_inject() {
echo "<script>
jQuery(document).ready(function($) {
var ajaxurl = '".admin_url('admin-ajax.php')."';
var list_target_id = 'list-target'; //first select list ID
var list_select_id = 'list-select'; //second select list ID
var initial_target_html = '<option value=\"\">Please select category...</option>';
$('#'+list_target_id).html(initial_target_html);
$('#'+list_select_id).change(function(e) {
var selectvalue = $(this).val();
$('#'+list_target_id).html('<option value=\"\">Loading...</option>');
if (selectvalue == \"\") {
$('#'+list_target_id).html(initial_target_html);
} else {
$.ajax({url: ajaxurl,
data: {
action: 'parentcatajax1',
parentCat: selectvalue
},
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + \" \"+ thrownError);
}});
}
});
});</script>";
}
add_action('admin_enqueue_scripts','widget_inject');
^This is what I'm trying. I've tried admin-init, admin-head, admin-footer none of them seem to work.
& yeah I have...
add_action('wp_ajax_nopriv_parentcatajax1', 'parentCatCallback1');
add_action('wp_ajax_parentcatajax1', 'parentCatCallback1');
for my ajax function; it works perfectly on the front end.
I'm at a stand still for a client & can't figure out what to do.
Any suggestions? Thanks in advance!
Your printing your jQuery before wordpress has initialized jQuery. Wp_enqueue scripts is not the point where it starts printing the scripts onto the page. The below will clear your jQuery not defined error, let me know if there are more errors after this.
function widget_inject() {
echo "<script>
jQuery(document).ready(function($) {
alert('ready');//re-enter your code here
})(jQuery);
</script>";
}
add_action('admin_print_scripts','widget_inject', 100);//hook= 'admin_print_scripts'

Ajax not working in chrome. Can anyone save me?

I have this code on my page...
the jQuery
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
This is the get_posts.php
<?php
include('dbconnect.php');
session_start();
$uid= $_SESSION['uid'];
$get_ids=mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($get_ids)){
$id=$row['id'];
$sm=$row['message'];
}
$get_lpid=mysql_query("SELECT * FROM users WHERE uid='$uid'");
while($row_o = mysql_fetch_array($get_lpid)){
$l_pid=$row_o['lastviewed'];
}
if($id!=$l_pid){
$insert=mysql_query("UPDATE users SET lastviewed='$id' WHERE uid='$uid' ");
if($insert){?>
<div class='media'><img src='img/profile_pictures/thumbs/thumb_13718921232_119055628287843_1500172795_n.jpg' class='img-circle post-circle pull-left'><div class='media-heading'><a href='#'>Pratik Sonar</a><div class='pull-right'><small>12.00PM</small></div></strong></div><div class='media-body'><?php echo $sm ?></div></div>
<?php } else{
}
}
else{
}?>
This technique seems to work on every browser except chrome. I have tested ie, safari, firefox and opera all are working. Can anyone enlighten me on this thing? Is there something I don't know or am I missing?
Try to wrap your code into this function:
$(document).ready(function() { ... });
Like:
$(document).ready(function() {
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
});
You're probably better off using setTimeout() too.
Now the code runs when the DOM is fully loaded.
Why are you using window.setInterval?
It's simply setInterval(), without any parent.
Try
$(document).ready(function() {
setInterval(function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});
},10);
});
Thank You guys for all your concerns. Well at last the bug got fixed by this chunk of code. I guess setTimeout gain gains victory over setInterval
$(document).ready(function() {
window.setTimeout(function(){
$.ajax({
type: "GET",
url: "php/get_posts.php",
}).done(function( data ) {
$('.post-container').prepend(data);
});
},10);
});

Do php query with ajax

I'd like to do a sql query with ajax so I don't need to reload the page / load a new page.
So basicly I need to call a php page with ajax. And it would be great if there could be a way to reload a count of amount of rows in a table too.
Edit: to make it more clear, it should be able to do something along the lines of when you click the Like button on Facebook.
Thanks
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("your_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">here are your contents</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
You don't want to query using ajax, you want to get new data using ajax, which is a fundamental difference.
You should just, using ajax, request a php page with perhaps some parameters, which in turn executes the query and returns the data in a format you can handle (most likely: json).
If you allow queries to be executed using ajax, how are you going to prevent a malicious user from sending drop table users, instead of select * from news where id = 123?
You won't do a sql query with ajax, what you need to do is call an external php page (one where your query is) in the background using ajax. Here is a link that explains how to do it with jquery: http://api.jquery.com/jQuery.ajax/
"Facebook Like" button in Agile Toolkit (PHP UI Library):
$likes = get_like_count();
$view = $this->add('View');
$button = $view->add('Button')->setLabel('Like');
$view->add('Text')->set($likes);
if($button->isClicked()){
increate_like_count();
$view->js()->reload()->execute();
}
p.s. no additional JS or HTML code needed.
function onClick(){
$.post(
"path/to/file", //Ajax file ajax_file.php
{ value : value ,insiId : insiId }, // parameters if you want send
//function that is called when server returns a value.
function(data){
if(data){
$("#row_"+data.id).show(); //display div rows
}
},"json"
);
}
<div id="myDiv">here are your contents</div>
<button type="button" onclick="onClick()">Change Content</button>
Here the ajax code that you can call to the server side php file and get the out put and do what you want
You are wrong, who says that he is submitting the whole query who is telling that he is not filtering? U can do all this easy with the jquery load function, you load a php file like that $('#BOX').load('urfile.php?param=...');.
Have fun,
i hope that was a little helpful for you, sry bcs of my bad english.
Possible solution: Ajax calls PHP scripts which make the query and return the new number
$.ajax({
async:true,
type:GET,
url:'<PHP_FILE>',
cache:false,
data:'<GET_PARAMETERS_SENT_TO_PHP_FILE>',
dataType:'json',
success: function(data){
$('<#HTML_TARGET>').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('<#HTML_TARGET>').html('<div class="ajax_error">'+errorThrown+'</div>');
}
});
Where
<PHP_FILE> is your php script which output must be encoded according to dataType. The available types (and the result passed as the first argument to your success callback) are: "xml", "html", "script", "json", "jsonp", "text".
<GET_PARAMETER_SENT_TO_PHP> is a comma separate list of value sent via GET (es. 'mode=ajax&mykey=myval')
<#HTML_TARGET> is the jquery selector
See jquery.ajax for more details.
For example:
<p>Votes:<span id="count_votes"></span></p>
<script type="text/javascript">
$.ajax({
async:true,
type:GET,
url:'votes.php',
cache:false,
dataType:'text',
data:'id=4'
success: function(data){
$('#count_votes').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('#count_votes').html(errorThrown);
}
});
</script>
If your looking for something like the facebook like btn. Then your PHP code should look something like this -
<?php
$topic_no = $_POST['topic'];
$topic_likes = update_Like_count($topic_no);
echo $topic_likes;
function update_Like_count($topic)
{
//update database by incrementing the likes by one and get new value
return $count;
}
?>
and the javascript/jquery ajax should be something like so -
<script>
$('#like-btn').click( function () {
$.post(
"like.php",
{ topic : value },
function(data)
{
if(data)
{
$("#like-btn span").append(data); //or append it to wherever you'd like to show it
}
else
{
echo "error";
}
},
"json"
);
});
</script>
Here is an example which uses a favorite jQuery plugin of mine, jQuery.tmpl(), and also the jQuery .text() function.
HTML and Javascript Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
<script id="UserTemplate" type="text/x-jquery-tmpl">
<li><b>Username: ${name}</b> Group ID: (${group_id})</li>
</script>
<button id="facebookBtn">Facebook Button</button>
<div id="UserCount"></div>
<ul id="userList"></ul>
<script>
function getData(group_id) {
$.ajax({
dataType: "json",
url: "test.php?group_id=" + group_id,
success: function( data ) {
var users = data.users;
/* Remove current set of movie template items */
$( "#userList" ).empty();
/* Render the template with the movies data and insert
the rendered HTML under the "movieList" element */
$( "#UserTemplate" ).tmpl( users )
.appendTo( "#userList" );
$( "#UserCount" ).text('Number of users: '+ data.count);
}
});
}
$( "#facebookBtn" ).click( function() {
getData("1");
});
</script>
</body>
</html>
PHP Code
<?php
//Perform a query using the data passed via ajax
$group_id = $_GET['group_id'];
$user_array = array(
array('name'=>'John','group_id'=>'1',),
array('name'=>'Bob','group_id'=>'1',),
array('name'=>'Dan','group_id'=>'1',),
);
$user_count = count($user_array);
echo json_encode(array('count'=>$user_count,'users'=>$user_array));
HTML:
//result div will display result
<div id="result"></div>
<input type="button" onclick="getcount();" value="Get Count"/>
JS:
//will make an ajax call to ustom_ajax.php
function getcount()
{
$.ajax({
type:"get",
url : "custom_ajax.php",
beforeSend: function() {
// add the spinner
$('<div></div>')
.attr('class', 'spinner')
.hide()
.appendTo("#result")
.fadeTo('slow', 0.6);
},
success : function (data) {
$("#result").html(data);
},
complete: function() {
// remove the spinner
$('.spinner').fadeOut('slow', function() {
$(this).remove();
});
}
});
}
custom_ajax.php:
//will perform server side function
//make a connection and then query
$query_txt = "SELECT count(*) FROM table ";
$result= mysql_query($query_txt) or die(mysql_error());
$total=mysql_num_rows($result) ;
$html= "Total result is $total";
echo $html; exit();

How do I send and receive vars with jquery and AJAX?

so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);

jQuery Ajax submission problems

Why doesn't the following pick up the form? All it does is just to do a normal PHP post without throwing any errors...
I'm using blockUi on this as well, hence block/unblock.
$(document).ready(function(){
$("input.update").click(function(){
var str = $(this).parent().serialize();
$(this).parent().parent().block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
$.ajax({
type: "POST",
url: "forms/update.php",
data: str,
success: function(){
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
}
});
return false;
});
});
This is my first attempt at using jQuery's Ajax functionality so please bear with me.
("input.update").click(function(){
should be
$("input.update").click(function(){
Since it seems you're only using the 'success' callback of post you could use the .post method, which is a bit easier on the eyes. Also you can put those block calls inside ajaxStart and ajaxStop. To me it's neater.
The $(this).parent().parent().block seemed wrong to me, I changed it to reference the same element that is used for unblocking. I'd also be checking the output of the PHP script, to make sure that whatever you are 'updating' actually is updated (just echo XML from PHP and you'll see it on your console log).
$(function() {
// Apply click handlers to anchors
$("input.update").click(function(e){
// Stop normal link click
e.preventDefault();
var str = $(this).parent().serialize();
// Send request
var action = "forms/update.php";
$.post(action, {data:str}, function(xml) {
console.log(xml);
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
})
});
// Adds a wait indicator to any Ajax requests
$(document.body).ajaxStart(function() {
$("div.edit_box").block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
}).ajaxStop(function() {
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
});
});

Categories