how to make interaction client server with javascript calling php functions? - javascript

I have been trying to make multiple tables viewed and be editable from the site to the server in my site.
I tried to use jquery ajax and it seems like fail
is there other way or my code was just bad?
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".setitlive").click(function() { setitlive(1); });
});
function setitlive(value1) {
var id=value1;
jQuery.ajax({
type: "POST",
url: 'C:\Users\user\Desktop\interactionclientserverwithphpandjavascript.php',
data: {functionname: 'setitlive', arguments: [id]};
}
</script>`
Interaction Client Server PHP code:
<?php
header('Content-Type: application/json');
$id = $_POST['arguments'][0];
switch($_POST["functionname"]){
case 'setitlive':
public function setitlivee( $id )
{
$result = \IPS\Db::i()->update( 'cms_custom_database_26', array(
'field_113' => 'live' ), array( 'primary_id_field="'.$id.'"' ) );
header("Refresh:0");
}
break;
}
?>
HTML Header:
<form method="POST">
button
<li class="ipsButton ipsButton_medium ipsButton_importantipsButton_fullWidth12">
<a title='{lang="accept"}' name="setitlive" id="setitlive" type="submit" onclick=" setitlive(); ">
{lang="accept"}
</a>
</li>

To start with, a window path isn't a URL. Your web server probably doesn't know how to find a file on your desktop unless you have a crazy configuration.
Put the target file in root of your project directory where your other php files are and then call it just by the file name and maybe a sub directory.
Once you've done that, if there's any further problems, please post it as a new question.
Let's say your php files are all in c:\www. Put that file in that directly and then...
url : 'interactionclientserverwithphpandjavascript.php',

Related

JQuery to submit PHP not executing

After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.

PHP script as form action: give server side effents

I have a working PHP script running quite long (5 minutes at maximum). I want to inform to user after each step ("task 1 of 10 done").
I know, this is an old problem and I tried to solve it with server side events.
On the HTML side there is a form with my PHP script as the action:
<form action="my_script.php"><input type="submit" value="Submit!"/></form>
One requirement is, that the hole HTML page works (and calls my_script.php by submitting the form) without any scripting. The "live status reports" form the PHP script are intended to be an additional feature, but the page should completly work without it.
This is how I tried to do it: On the client side I added an onsubmit() event to the form tag calling a JavaScript function:
var source = new EventSource("my_script.php");
source.onmessage = function(event)
{
// display data in a div
};
On the server side the PHP should send some messages to the calling HTML page (while doing its tasks) and after all tasks are done build a new HTML pages with all output.
I tried to do that like this:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$output_stream = '';
// do something here. If a taks is done call send_to_output('something done');
function send_to_output($message)
{
global $output_stream;
echo "data: {$message}\n\n";
flush();
$output_stream .= $message;
}
header('Content-Type: text/html');
header('Cache-Control: no-cache');
echo "Everything is finished";
echo $output_stream;
But that doesn't work.
After some testing, I think that there are two problems:
The browser can't cope with the header 'Content-Type: text/event-stream' and offers to download the file.
The form action (<form action="my_script.php">) and the JavaScript event (var source = new EventSource("my_script.php");) seem each to open an own thread of the PHP script, so that there are two instances of this script running on the server.
How can I solve those problems?
To accomplish this in the olden days, your form would submit directly to my_script.php which would direct the browser to load the content from that URL. my_script.php would first echo enough HTML for the browser to render the whole page, then flush its output buffers to ensure the client received it all. Part of that page data would be a JS global function -- something like update_status, that will receive the status events and update the UI. Then, on the same request, it would start the processing.
At various points during the processing, the script would echo something like:
<script type="text/javascript">update_status('15%');</script>
and flush it to the client. The client would run these script tags as they came in, call the relevant function, and update the UI.
Today we have WebSockets. That is by far the best way to do it, providing your users have a capable browser.
You could also poll the server on a setInterval, but that would require splitting execution off into a different process (so as not to hang the browser or waste a web server worker) and adding an endpoint to the backend to expose the status of each process.
I would just do this with standard ajax polling.
In this example i am just writing to a text file from the long running script, and loading it directly in the poll.
You would probably write to a db etc:
<html><head></head>
<body>
<form action="long.php" method="post" id="myform">
<input type="submit" value="submit "/>
</form>
<div id="progress">
</div>
<div id="result">
</div>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="application/javascript">
$(function(){
var checkid ='';
$('#myform').submit(function(ev){
ev.preventDefault();
var fm = $(this);
$.ajax({
type: "POST",
url: fm.attr('action'),
data: "",
success: function(data){
clearInterval(checkid);
$('#result').html(data);
}
});
checkid = setInterval(function(){
$.get('progress.txt', function(data){
$('#progress').html(data);
});
},1000);
})
});
</script>
</body>
</html>
//long.php
for($i=1;$i<10;$i++){
sleep(2);
file_put_contents('progress.txt', "done {$i} iterations", LOCK_EX);
}
echo 'all done';
There are quite a lot of solutions or workarounds for problems like this. This is surely not the place to discuss which is general the best one. The intention of my question was just: How to solve that problem with Server Side Events?
Inspired by user574632 I've found now a quick and dirty solution:
My long running PHP scripts puts all messages into a file:
function send_to_output($message)
{
global $output_stream;
$output_stream .= $message;
file_put_contents('progress.txt',$output_stream);
}
Another PHP script sends all contents of this file to the client:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$file_content = file_get_contents('progress.txt');
echo "data: {$file_content}\n\n";
flush();
?>
In the HTML I simply had to change to file name of var source = new EventSource("name.php").
This seems to work but it is no real smooth and nice looking solution.

How to call YII model from javascript plugin

I use ckeditor as an inline editor and added a button to save the content using AJAX. Everything works if I link to a php file which does the job for me. Anyhow, I'm using YII and I want to do this save work in a controller or in a file that uses my app settings.
So in my javascript plugin I call:
$.post("index.php/pagina/update?id=1", {
dataType: "text json",
data : editor.getData(),
success : alert('Opgeslagen!'),
} );
In my paginaController in the actionUpdate I got:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$model->content = 'werkt';
$model->save();
}
Does anyone know what I'm doing wrong here?
I think you'd have to pass the url Yii style, so that it accepts a parameter that is called id.
var url = '<?php echo Yii::app()->createUrl(array("pagina/update", "id" => $model->id)); ?>';
$.post(url , { // rest of code
Also, you could use a Yii ajax function here that looks something like this:
<?php echo CHtml::ajax(array(
'url'=>'js:url',
'data'=> "js: info",
'type'=>'post',
'dataType'=>'json',
));
?>

call function from js file inside php page

I have a file like "my_js_stuff.js" which is looking like this :
function my_js_function()
{
jQuery.ajax({
url: my_ajax_script.ajaxurl,
data: ({action : 'get_my_comments'}),
success: function() {
//Do stuff here
}
});
This file is included in my
<header>like this: <script type="text/javascript" src="my_js_stuff.js"></script>
I want to call the function from "my_js_stuff.js" inside my php page, and I'm thinking to call it like this:
<?php
<script type="text/javascript>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
?>
Is this the correct way to call the function from the js file ?
Thank you !
Is this the correct way to call the function from the js file ?
my_js_function() is certainly the correct way to call it.
But, to pass the function so the event can call it later, you'll want to skip the calling parenthesis:
$('.some-class').on('click', my_js_function);
With them, it'll be called immediately and its return value will instead be passed to the event binding.
Also note that the <script> shouldn't be inside a <?php ... ?> block unless it's in a string being echoed.
<?php
# ...
?>
<script>
$('.some-class').on('click', my_js_function);
</script>
<?php
# ...
?>
You could do that, but I'm not sure that's what you actually want to do. Javascript is executed on the client-side, whereas PHP is executed on the server. Your Ajax function makes a request (client-to-server) and fetches content from the server, such as dynamic content generated from a PHP file.
If what you're describing is really what you want to do, you need to echo your script snippet and enclose it in quotes.
<?php
echo '<script type="text/javascript">/*js content*/</script>';
?>
You're confusing the technologies. Your JS is for the client side (browser) and the PHP is for the server side (business logic).
You cannot call a JS function from inside PHP.
However, assuming you want to communicate JS > PHP, you need to include the JS on your page.
<script type="text/javascript?>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
and your URL needs to match the PHP endpoint:
url: my_ajax_script.ajaxurl, // This should be the path of your PHP file
Inside the php file you can get all the info as if it were a normal request:
<?php
echo $_GET['action'];
?>
This will return the $_GET['action'] var to your JS success function:
success: function(data) {
alert('Received: ' + data);
}
Hopefully you can use this information to build what you need.

Ajax and rewrite engine

I have a problem with ajax and rewrite engin. I made a site, where I use this load more script:
http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html
Everything works fine on users profile page (I am getting posts from users feedback), when the url looks like this: example.com/user.php?u=ExampleUser
but I have this in .htaccess:
RewriteRule ^u/(.*) user.php?u=$1 [L]
So if I type something like example.com/u/ExampleUser I get the username like:
$username = $_GET['u'];
But in this way when I click on the load more it doesn't load more posts from the user, it just starts to lead the site itself to the div box (like it is an iframe...).
Please help me, it is necessary.
Here is my script, which should load more info from MySQL database($id is userid from DB):
$(function() {
// More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: 'lastmsg='+ID+'&user='+<? echo $id; ?>,
cache: false,
success: function(html) {
$("#container").append(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
Not knowing the entire context of your code, it looks like when the ajax call is made, the final url is something along the lines of domain.tld/u/ajax_more.php.
I get around this issue by maintaining a list of constants in the javascript object.
For example, I have a paths.php file that contains this:
<?php
header("Content-Type: text/javascript");
echo "
myNamespace.paths = {
RELATIVE_FOLDER: '<?=RELATIVE_FOLDER?>',
// add more as required...
}
";
?>
This is included in the page just like a regular script (with script tags), and from that point forward, myNamespace.paths will contain your constants, as returned by the server.
In my case, if the URL was "http://www.example.org/path/to/my/dev/env", I would have RELATIVE_FOLDER set to /path/to/my/dev/env/ on the server-side, which would then be included into the paths object.
Later, in your ajax calls:
$.ajax({
type: "POST",
url: myNamespace.paths.RELATIVE_FOLDER + "ajax_more.php",
// ... everything else
});
I notice you have no problem with directly injecting PHP into your scripts. This is not necessarily a bad thing, but it does make it harder for you to minify your js. This is the reason why I went with a separate file to store the constants, instead of directly injecting it into the javascript itself with <?= ... ?> tags.

Categories