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

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);

Related

Passing sql string variable into javascript function

I am trying to pass a string from a query into a javascript function.
An integer will pass into the function but string will not.
echo "<a href='#' onclick='delete_game({$title});'
class='btn'>Delete</a>";
<script type='text/javascript'>
function delete_game(title){
var answer = confirm('Really?');
if(answer){
window.location = 'delete.php?id=' + title;
}
}
</script>
I expected the javascript function to be executed, but instead nothing happens.
Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.
In your HTML, you can do something like
I'm assuming that you are using Blade.
Delete Game
Then in your javascript, you do this using jQuery:
function deleteGame(title){
var answer = confirm('Really?');
if(answer){
$.ajax({
url : "your-php-file.php",
type : 'post',
data : {
title : title
}
})
.done(function(msg){
$("#result").html(msg);
})
.fail(function(error){
console.log(error);
});
}
}
In your PHP you process receiving the data from post $_POST
$title = $_POST['title'];
You can understand better the Ajax function of jQuery here.
A few things:
I would change window.location to window.location.href
Change your echo to:
echo "Delete";
Check if $title is set
var_dump($title);
If you'd like to make it a bit cleaner and are prepared to use jQuery:
Delete
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
var title = $(this).data('title');
var answer = confirm('Really?');
if (answer){
window.location.href = 'delete.php?id=' + title;
}
});
</script>

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'

Understanding AJAX php script for clue game practice

I'm trying to understand the relationship between a PHP script I'd like to run to keep track of progress and the front end work that has taken place. Its 2 clues in a game practice. Once the clue is inputted correctly everything occurs as below and I want to add a script that sends to MYSQL.
I'm working on the script now, but I'm trying to figure out at what point I'd introduce this. Is there anything I'd need within my PHP to distinguish it as AJAX. As in to run it in the background? Do I just "include" it as I would part of another larger PHP script?
The script in my mind will send a 1 if correct or 0 if still wrong. This way I can easily determine without having to deal with clues. The clues are irrelevant in my thinking, but what is your opinion on this?
// =====clue 1====================////////////////// clue 1 **************
//**********************************========================
$(document).on('click', '.btn-clue', function(){
if($i!=1){
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueTwo: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
});
} else {
$("#mySecondDiv").remove();
var mySecondDiv = $('<div id="mySecondDiv"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongOne').append(mySecondDiv);
}
}
});
// =====clue 2====================////////////////// clue 2*********=========
$(document).on('click', '.btn-clueTwo', function(){
if($i!=1){
//checking if textbox has desired value (1 in this case),
//in your application you would be passing the textbox value to
//ajax here and making the check at server side
var $two = $('#twoClueShow');
var x = $("#clueTwoInput").find('input[type=text]').val();
if(x == 'C' || x == 'CS') {
// if answer correct you should load data from ajax
// and append it to a container
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
} else {
$("#mySecondDivClueTwo").remove();
var mySecondDivClueTwo = $('<div id="mySecondDivClueTwo"><img src="images/check-x-mark.png" /></div>') .show('slow');
$('#clueWrongTwo').append(mySecondDivClueTwo);
}
}
});
Above is where I've been able to get. Now here is where I'm getting confused. I now want to send to the database that the answer has been answered correctly through AJAX, correct? Would I just include_once my php script in the commented area.
I was thinking of creating a script that filled a 1 if correct and 0 if not correct to make life easier. Let this do the work as I don't need to reintroduce the inputs or re use. This way once the page has reloaded I could simply not output the inputs again and use this info to determine what is displayed and where they are at in the clue game. Basically saving progress.
Is there something specific to use when building my normal PHP. I guess that and where to "include" it is where I'm confused.
MY button for reference
<div id="clueOneInput">
<input type="text" id="clue1" class="clue-text form-control" placeholder="Enter Clue 1 here and check"/>
</div>
<input type="button" id="clue1Input"class="btn btn-primary btn-clue" value="Check">
Update :
// =====clue 1====================////////////////// clue 1**********************************************************************========================
$(document).on('click', '.btn-clue', function(){
if($i!=1){
//checking if textbox has desired value (1 in this case),
//in your application you would be passing the textbox value to ajax here and making the check at server side
var $one = $('#oneClueShow');
var x = $("#clueOneInput").find('input[type=text]').val();
if(x == 'd' || x == 'dr')
{
//if answer correct you should load data from ajax and append it to a container
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueOne: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongOne").hide();
$("#mySecondDiv").remove();
$("#clueOne").remove();
$("#clue1Input").remove();
$one.show();
$("#clueOneInputCorrect").slideDown('slow').show();
$i++;
});
}
else
{
$("#mySecondDiv").remove();
var mySecondDiv = $('<div id="mySecondDiv"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongOne').append(mySecondDiv);
}
}
});
// =====clue 2====================////////////////// clue 2**********************************************************************========================
$(document).on('click', '.btn-clueTwo', function(){
if($i!=1){
var $two = $('#twoClueShow');
var x = $("#clueTwoInput").find('input[type=text]').val();
if(x == 'CS' || x == 'CSU')
{
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueTwo: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
});
}
else
{
$("#mySecondDivClueTwo").remove();
var mySecondDivClueTwo=$('<div id="mySecondDivClueTwo"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongTwo').append(mySecondDivClueTwo);
}
}
});
In your Jquery
$.ajax({
type: "POST",
url: "yourScriptToUpdateDB.php",
data: { clue: "Wrong", user: "JoeBob" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongOne").hide();
});

jquery code snippet on load

I'm working with this code snippet plugin : http://www.steamdev.com/snippet/ for my blog
but the plugin doesn't work on page load.
It only works at first page refresh.
I load my content in a specific div with jquery.ajax request and i'm trying this :
$(window).on("load", function(){
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
I also tried to trigger the load event but i don't know if it is correct..
Another question : i build my html with php string like this example:
$string = '<pre class="cplus">
#include <iostream>
int main()
{
//c++ code
}
</pre>
<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
echo $string; // ajax -> success
but the PHP snippet shows empty (the c++ is ok). Any other way (or plugin) to show php code snippet on my page?
Thank you.
SOLVED:
The problem isn't the plugin or Iserni suggestions.. i had a problem in page load (ajax)..
This is how i load the pages:
function pageload(hash) {
if(hash == '' || hash == '#php')
{
getHomePage();
}
if(hash)
{
getPage();
}
}
function getHomePage() {
var hdata = 'page=' + encodeURIComponent("#php");
//alert(hdata);
$.ajax({
url: "homeloader.php",
type: "GET",
data: hdata,
cache: false,
success: function (hhtml) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
});
}
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
//alert(data);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(html);
$('#body').fadeIn('slow');
}
});
}
$(document).ready(function() {
// content
$.history.init(pageload);
$('a[href=' + window.location.hash + ']').addClass('selected');
$('a[rel=ajax]').click(function () {
var hash = this.href;
hash = hash.replace(/^.*#/, '');
$.history.load(hash);
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
$('#body').hide();
$('.loading').show();
getPage();
return false;
});
// ..... other code for menus, tooltips,etc.
I know this is experimental , i have made a mix of various tutorials but now it works..
comments are much appreciated..
Thanks to all.
The PHP snippet seems empty because the browser believes it's a sort of HTML tag.
Instead of
$string = '<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
you need to do:
// CODE ONLY
$string = '<?php
function foo()
{
// PHP code
}
?>';
// HTMLIZE CODE
$string = '<pre class="php">'.HTMLEntities($string).'</pre>';
As for the jQuery, it is probably due to where you put the jQuery code: try putting it at the bottom of the page, like this:
....
<!-- The page ended here -->
<!-- You need jQuery included before, of course -->
<script type="text/javascript">
(function($){ // This wraps jQuery in a safe private scope
$(document).ready(function(){ // This delays until DOM is ready
// Here, the snippets must be already loaded. If they are not,
// $("pre.cplus") will return an empty wrapper and nothing will happen.
// So, here we should invoke whatever function it is that loads the snippets,
// e.g. $("#reloadbutton").click();
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
})(jQuery); // This way, the code works anywhere. But it's faster at BODY end
</script>
</body>
Update
I think you could save and simplify some code by merging the two page loading functions (it's called the DRY principle - Don't Repeat Yourself):
function getAnyPage(url, what) {
$('.loading').show(); // I think it makes more sense here
$.ajax({
url: url,
type: "GET",
data: 'page=' + encodeURIComponent(what),
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
// Here you ought to allow for the case of an error (hiding .loading, etc.)
});
}
You can then change the calls to getPage, or reimplement them as wrappers:
function getHomePage(){ return getAnyPage('homeloader.php', "#php"); }
function getPage() { return getAnyPage('loader.php', document.location.hash); }
ok for the first issue I would suggest to
see what your JS error console saying
ensure correspondent js plugin file is loaded
and use the following code when you are using ajax (the key thing is "success" event function):
$.ajax({
url: 'your_url',
success: function(data) {
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
}
});
for the second issue lserni answered clearly
you need to use to jquery on load function like so:
$(function(){
RunMeOnLoad();
});

Javascript + Load AJAX function on page load + Pass Javascript vars to PHP

I have again a little problem with a javascript (i am a real noob regardin that). This time I would like to load an AJAX function on page load in order to save some javascript variables to php sessions. I figured out thats the best way to pass javascript vars to php. If there is a better way (besides cookies), dont hesitate to let me know :)
For now I would like to:
-pass javascript variables to an external php page on page load
-save variables in php
-use the php variables without pagereload
Here is my script so far:
$(document).ready(function () {
function save_visitor_details() {
$(function() {
var visitor_country = geoip_country_name();
var visitor_region = geoip_region_name();
var visitor_lat = geoip_latitude();
var visitor_lon = geoip_longitude();
var visitor_city = geoip_city();
var visitor_zip = geoip_postal_code();
var dataString = 'visitor_country='+ visitor_country +'&visitor_region='+ visitor_region +'&visitor_lat='+ visitor_lat +'&visitor_lon='+ visitor_lon +'&visitor_city='+ visitor_city +'&visitor_zip='+ visitor_zip;
$.ajax({
type: "POST",
url: "inc/visitor_details.php",
data: dataString,
success: function(res) {
alert ("saved");
//$('#result').html(res);<-- should contain variables from inc/visitor_details.php
});
}
});
return false;
}
});
Thanks in advance!
Edit: I changed it a little and got it to work by adding the javascript variables into a hidden form, submit the form with the ajax script above and save variables into php session array at the backend php file.Thanks any1 for your time!!!
I don't really understand what is the question here. But here are a few advices.
rather than serializing the data yourself, you should rather let jQuery do that for you:
$.post('inc/visitor_details.php', {country: geoip_country_name() /* stuff */}, function(data) {
alert('ok!'); alert(data);
});
be aware that, by passing data to your server using Javascript, users can send whatever data they want, including fake data. So handle it with care.
Then entire process may looks like this:
/* javascript */
$(document).ready(function() {
function save_visitor_details() {
$.post('inc/visitor_details.php', {
country: geoip_country_name(),
region: geoip_region_name(),
lat: geoip_latitude(),
lon: geoip_longitude(),
city: geoip_city(),
zip: geoip_postal_code()
}, function(data) {
/* do whatever you want here */
alert(data);
}, 'json');
}
save_visitor_details();
});
/* PHP */
<?php
$keys = array('country', 'region', 'lat', 'lon', 'city', 'zip');
$output = array();
foreach($keys as $key) {
do_some_stuff($_POST[$key]);
$output[$key] = $_POST[$key];
}
header('Content-type: text/plain; charset=utf-8');
echo json_encode($output);
?>
JavaScript:
var http = createRequestObject() ;
function createRequestObject(){
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
obj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(str){
http.open('get', str);
http.onreadystatechange = handleResponse;
http.send(null);
}
sendReq("someurl?var=yourvar");
Php:
$var = $_GET['var']; // use some security here.

Categories