I have this part of ajax code on my windows8
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
$('#next_Button').click(function(){
var text = document.getElementById("textbox");
var query = text.value;
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'http://192.168.92.131/search2/info.php',
data: { query : query }
})
.done(function(data){
$('#response').html(data);
alert("sent query");
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>
and php code on my virtual Ubuntu machine
echo $_POST['query'];
IP address is correct and it's always fixed. But ajax always says 'posting failed'. when I put html code on server and just set url :'search2/info.php'
it works. but when it's remote server with http:// ipaddress / search2 / phpname it doesn't work. By the way my php code is in var/www/html/search2 hosted on apache.
Is this problem from ajax ? even when I click on this complete url it shows server page! but ajax can't use this direct url to .php !
Ajax has a cross domain protection, to prevent loading from domain others than then one you browse to.
This is a security feature.
I suggest you read about it a bit here:
jQuery AJAX cross domain
And there are many other questions on the subject.
I 'm really glad to find it myself !!
I 'v open .html by double click (it was really wrong and I never noticed) and now I understand open it on localhost or 127.0.0.1 !it works properly .
before , alert shows it works but there were no answer from server ...
And also it printed whole page!! see , I had lots of comments after the tag
so it echo all of comments :)
Related
I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓
So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})
Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?
I have the following div in my html
<div class="result">loading</div>
And my javascript is as follows.
$(document).ready(function() {
$.ajax({
accept: 'application/rss+xml',
url: 'http://www.madhyamam.com/taxonomy/term/19/rss.xml',
success: function(data) {
$('.result').html(data);
}
});
});
But for some reasons.. it doesnt seems to work.
In jsfiddle
XML returned(firebug):
XML Parsing Error: no element found Location:
moz-nullprincipal:{9ec69805-af82-4f95-979a-f8e68d415124} Line Number
1, Column 1:
^
Solution
*I bye-passed the problem using yahoo pipe. And it worked fine.*
You can't make Ajax requests to URLs that have not the same domain, port and protocol as the current page. The Same Origin Policy forbids it.
The most common workaround is having a server-side script that pulls the content, and serves it through Ajax.
As Pekka mentioned, we guess your problem is that Ajax cannot make request on other domain URLs. You have to use server-side script for that.
Example of small php server-side script for testing (from Jquery Minime Feed library):
<?php
header('Content-type: text/xml; charset=utf-8');
$url = htmlspecialchars($_GET['url']);
echo file_get_contents('http://'.$url,0);
?>
Then you can call something like
$.ajax({
accept: 'application/rss+xml',
url: 'http://youserver/getfeed.php?url=http://www.madhyamam.com/taxonomy/term/19/rss.xml',
});
However, it seems you want to show rss feed in your page. I went to same issue and ended using Jquery Minime Feed library, which help you doing the job:
$('#test1').minimeFeed('http://index.hu/24ora/rss/');
Automatically use server-side script if needed, and produce quite nice output. See demo here
First at all sorry for my poor english, but i might that you can understand what i mean.
I need to get the url redirected by a server, for example
http://exam.ple/get/23456 turns to -> http://exam.ple/full_url/content?id=34567
im trying to do that in ajax, but is weird, the thing only works when the shorten url is loaded by the browser, when i try to access that url in ajax, i get the google homepage as result.
Im not interested in the content of the page, just the url, and the cross-domain policies aren't the problem.
Maybe would be easyer using a php proxy but im trying to avoid server side codes
Note: the shorten links are protected from scraping by robots.txt
Thanks in advance.
EDIT
I didn't post any codes cause nothing worked at all, i've tryed many ways,
$.ajax({
url: "http://exam.ple/get/23456",
...
});
var request = new air.URLRequest("http://exam.ple/get/23456");
var loader = new air.URLLoader();
loader.addEventListener(air.Event.COMPLETE,completeHandler);
loader.load(request);
}
function completeHandler(event){
var dataXML = event.target.data;
air.trace(dataXML);
}
Also trought
var req = new XMLHttpRequest();
req.onreadystatechange = function() { ..........
But as i said, the response is always the same, the google homepage.
And no, dont want to redirect the user to anywhere, just need the url data to work with it.
It would be good if you post your code. However, here are some tips:
1) Try using non-full url in your ajax call
$.ajax({
url: "/get/23456",
...
});
2) Do you need to redirect on the client? if so, you can use:
location.href = "/full_url/content?id=34567";
Hope this helps. If not, please post your code and explain it a little bit so we can help you better. Cheers