i got this script, which i found in the web:
<script type="text/javascript">
$(document).ready(
function () {
$('a.closeEl').bind('click', toggleContent);
$('div.groupWrapper').Sortable(
{
accept: 'groupItem',
helperclass: 'sortHelper',
activeclass : 'sortableactive',
hoverclass : 'sortablehover',
handle: 'div.itemHeader',
tolerance: 'pointer',
onChange : function(ser)
{
},
onStart : function()
{
$.iAutoscroller.start(this, document.getElementsByTagName('body'));
},
onStop : function()
{
$.iAutoscroller.stop();
}
}
);
}
);
var toggleContent = function(e)
{
var targetContent = $('div.itemContent', this.parentNode.parentNode);
if (targetContent.css('display') == 'none') {
targetContent.slideDown(300);
$(this).html('[-]');
} else {
targetContent.slideUp(300);
$(this).html('[+]');
}
return false;
};
function serialize(s)
{
serial = $.SortSerialize(s);
alert(serial.hash);
};
</script>
<div class="serializer">
<a href="#" onClick="serialize(); return false;" >serialize all lists</a>
</div>
<script language="JavaScript" type="text/javascript">var client_id = 1;</script>
at the bottom of the script is the "function serialize", which is called by clicking on the link below. Can someone tell me, how can i send the variable "serial.hash" to a php-file to save it in mysql-database?
many thanks, maschek
Yes as Yacoby says $.post() or jQuery.post
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Use Ajax to send request to a PHP script which submits the data to a database. The JQuery documents contain a lot of examples. If you use a HTTP GET request, be warned there is a limit on the amount of data you can pass. This is browser dependant. I would recommend using jQuery.post as the method of sending data.
All the PHP script has to do is read the variables either from $_GET or $_POST (whichever method you use), sanitize them and submit them to the database.
Actually, it seems very simple now:
$.post("test.php",{'func':'serial'},function(data){
alert(data);
});
Related
Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.
What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)
<form>
<input type="text" id="user"/>
<input type="button" value="Submit" onClick="post();" />
</form>
<div id="result"> </div>
<script type="text/javascript">
function post()
{
var username = $('#user').val();
$.post('battlephp.php',
{postuser:user}
)
}
</script>
Its a simple Ajax code.. It should take username and display the Php code!
But don't know why its not running?? Actually I am learning...so I cant rectify the error or fault??
I am running ii on localhost.. so is there any problem with using:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
display the Php code
No, it shouldn't.
First, you've changed your mind about the variable name you are using (user, username) half way through your script, so you are going to throw a reference error.
Second, you haven't provided a function (the third argument) to $.post, so you aren't doing anything (such as displaying it) with the returned data.
Third, the server should execute the PHP and return its output. You shouldn't get the actual PHP code.
function post() {
var username = $('#user').val();
$.post(
'battlephp.php',
{postuser:username}, // Be consistent about your variable names
function (data) {
alert(data);
}
);
}
Instead
document.ready()
you can use
jQuery(function($){...});
Try to do this:
<script>
$(document).ready(function() {
function post() {
var username = $('#user').val();
$.ajax({
type : 'post',
url : 'batttlephp.php',
data : {
postuser : user
},
success : function(data) {
alert(data);
},
error : function(data) {
alert(data);
}
});
});
});
</script>
if you're doing a ajax request then is good also handle success and error...
Also I suggest to you "to start the document".
Try the code above and let us know if worked
Trying to pass a variable to a PHP file then get the output of that file.
Page1.html:
<h2 id="test"></h2>
<script>
var data2;
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
data2 = data;});
document.getElementById("test").innerHTML = data2;
</script>
textandemail.php:
$variable = $_POST["txt"];
$variable2 = $_POST["email"];
echo $variable;
echo $variable2;
Hopefully this describes the desired idea. I will be doing much more in the PHP file but in the end echoing out a response that I want the JavaScript to read and implement into the html page.
The $.post() function is asynchronous. It finishes some time LATER. You need to put the assignment of the results from that function into the success handler, not after the function itself because as you have it now, the line document.getElementById("test").innerHTML = data2; is occurring BEFORE the ajax function has finished and thus it won't work.
This is how you can do it:
<h2 id="test"></h2>
<script>
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
// any code that uses the ajax results in data must be here
// in this function or called from within this function
document.getElementById("test").innerHTML = data;
}
);
</script>
Or, since you have jQuery, you can do it like this:
<h2 id="test"></h2>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
// any code that uses the ajax results in data must be here
// in this function or called from within this function
$("#test").html(data);
}
);
</script>
Your post call is asynchronous, you have access to the data2 variable only once the process is done, so you should do your ....innerHTML ... in the callback function, when the data is available, not before.
There are plenty of good examples of this on any js sites. On the jQuery doc you have a good example.
Since you are useing jQuery, you could replace your innerHTML call too.
you should use ajax function to make communication between php and javascript
function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){
var xmlhttp
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}
catch(e){
try{xmlhttp=new XMLHttpRequest()}
catch(e){
alert("Your Browser Does Not Support AJAX")}}}
err=""
if (GP==undefined) err="GP "
if (URL==undefined) err +="URL "
if (PARAMETERS==undefined) err+="PARAMETERS"
if (err!=""){alert("Missing Identifier(s)\n\n"+err);return false;}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if (RESPONSEFUNCTION=="") return false;
eval(RESPONSEFUNCTION(xmlhttp.responseText))
}
}
if (GP=="GET"){
URL+="?"+PARAMETERS
xmlhttp.open("GET",URL,true)
xmlhttp.send(null)
}
if (GP="POST"){
PARAMETERS=encodeURI(PARAMETERS)
xmlhttp.open("POST",URL,true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.setRequestHeader("Content-length",PARAMETERS.length)
xmlhttp.setRequestHeader("Connection", "close")
xmlhttp.send(PARAMETERS)
the call functions put it inside the javascript page
Ajax_Send("POST","users.php",data,e)
where data is the data you send to the php page and e is the function you pass the output of php page to it
I'd like to know how can I use a jquery variable in a sql query?
Here is my jquery that is in my php file:
?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(function(){
jQuery('#event_form_field-<?php echo $event_id; ?>').click(function() {
var bradio = jQuery("input[type=radio]:checked").val();
alert(bradio);
}) });</script> <?php
I want to use the bradio variable in a sql query (on the Having clause, for example Having answer='$bradio'.
But i don't know how to passe the jquery variable in php.
Can you please explain me how can I do this?
Thanks.
You can use AJAX to pass the variable to a PHP script. That PHP script can also return data to the JavaScript AJAX call, for instance you can output error or success in your PHP file so the JavaScript code can alert the user as to what happened (in my example this response is saved in the serverResponse variable):
jQuery(function ($) {
$('#event_form_field-<?php echo $event_id; ?>').click(function() {
$.get('path/to/server-side.php', { 'bradio' : $("input[type=radio]:checked").val()}, function (serverResponse) {
//the server request has been made and has come back successfully
});
});
});
Some documentation:
$.get(): http://api.jquery.com/jquery.get