It's been a while since I've played with jQuery, so I'm wondering what I'm missing here.
I've set up a php page that writes a test txt file when the jQuery calls it.
The txt file is being written, so jQuery is finding the php page, but then displays my error alert, not my success one, so something is not working.
My php:
$testfile=$_SERVER["DOCUMENT_ROOT"].'/test.txt';
$file5 = fopen ($testfile, "w");
fwrite($file5, 'testy');
fclose ($file5);
exit();
My jQuery:
var g = {
r: 1
};
$.ajax({
type: "POST",
url: "/test.php",
cache: false,
data: g,
success: function (data) {
alert('yay');
},
error: function (data) {
alert('nay');
}
});
Anything obvious I'm missing?
Thanks for taking a look.
I think the problem is on the url you are requesting. Its hard to tell without know the type of error or without knowing your folder structure or if you are using any PHP framework. Please, write details
Try this--
url: "test.php",
Related
I am trying to fetch the contents of an external XML URL, into the javascript's ajax script, but it simply won't accept it, due to CROSS domain issue. I have searched through google regarding this issue, but nothing good so far, everything I've read so far stated that I need to incorporate PHP as well, but with that, the page would take reload.
I simply want that when a user enters a number that number gets passed as an argument in the URL, then displays the XML content in the screen without reloading.
SO any help will be highly appreciated.
Here's my code so far.
<script>
function myFunction() {
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=1&query=bath.isbn%3D9781452110103",
dataType: "xml",
success: function(xml){
$(xml).find('record').each(function(){
var sTitle = $(this).find('datafield[tag="245"]').find('subfield[code="a"]').text();
var sAuthor = $(this).find('datafield[tag="100"]').find('subfield[code="a"]').text();
var sIsbn = $(this).find('datafield[tag="020"]').find('subfield[code="a"]').text();
$(".mypanel").html(text);
});
$("<li></li>").html(sTitle).appendTo("#dvContent ul");
$("<li></li>").html(sAuthor).appendTo("#dvContent ul");
$("<li></li>").html(sIsbn).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
</script>
I need to pass a Javascript array of objects to PHP. Found about 3 solutions on the internet, but none of them worked for me. The array looks like this (in Chrome dev console):
And my current AJAX call looks like this:
function consolidate() {
var studentsstring = JSON.stringify(students);
$.ajax({
type: "POST",
url: "writefile.php",
dataType: "json",
data: {students: students},
success: function(data) {
alert(data);
}
});
}
And the PHP file looks like this:
<?php
print($_POST['students']);
?>
Currently, when I hit the "consolidate" button, nothing happens. No alert is shown. Chrome dev reports no errors in the code.
Oh, I'm dumb. Too many hours of coding. The line should have been:
data: {students: studentsstring},
and now it works. Thanks all.
I have tried tons of thing to get json data from another url with jQuery. I have working code in php, but dont have any idea how to do it in jquery.
PHP:
$skin = rawurlencode($market_hash_name);
$skin2 = str_replace('%0A', '', $skin);
$link = "http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=".$skin2;
$json2 = file_get_contents($link);
$obj2 = json_decode($json2);
$mediumPrice = $obj2->median_price;
Example of jQuery that i have tried:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
});
Typically a easy way around that is to create a Proxy, that is just a fancy word for saying have something else send and receive the data between the end points.
This can be as simple as using ajax to a PHP file on your server, from that PHP file using CURL to your endpoint, back to the output through echoing the return of the CURL script.
That way you can get around the restrictions on JavaScript. You mention
I have working code in php
So it should be relatively trivial to pipe the ajax call through that code and back.
Ok so instead of doing this
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
Do this
$.ajax({
type: 'GET',
url: 'http://yoursever.com/proxy.php/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'json',
success: function (data) {
alert(data.median_price);
}
});
Then in proxy.php or whatever you chose to name it, use your working php code to make the call then simply return that data to the client through JSON as per normal AJAX. Then you are technically calling the remote sever using PHP and don't have the cross domain issue. But because you are using your sever as a Proxy you can still do it in real time.
I am tearing my hair out of this one. I am only trying to teach myself php to do this one thing. Write a json file.
My php is probably a giant pile of dung, and more, was all over me with a 412 error. But moving it into the getJSON fixed that. My ajax call is somehow failing to feed the php my data, or my php function is not creating the file appropriately. Either way, I have an empty file
I wrote what was supposed to be an awesome proof of concept prototype, but as it is, the php portion or ajax call may be "made of fail". >__< Read on brethren, I wrote a simple demo.
I know it's silly to read a json file and then save a json file, but let me off on this technicality. Instead of having test.json, I have a servlet that gives me the json. I just save it in the javascript as javaobject. No sweat. But I tested it out as shown below:
demo.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Demo</title>
<script type= "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="test1.js"></script>
</head>
<body>
<h1>Test1</h1>
</body>
</html>
test.json
{"herp":1,"derp":2,"supersuper":3,"derpderp":5}
test.js
var newData;
$(document).ready(function()
{
$.getJSON('test.json', function(data)
{
console.log('test1.js');
console.log(data.herp);
console.log(data.derp);
console.log(data.supersuper);
console.log(data.derpderp);
//alert('success');
newData = data;
console.log(newData);
$.ajax({
type: 'POST',
url: 'json.php',
dataType: 'json',
data: {"json":newData},
data: {"json":JSON.stringify(newData)},
success: function()
{
alert('Successful submission');
},
error: function(e)
{
alert("error" + e);
console.log(this,arguments);
}
});
});
});
json.php
<?php
$json = $_POST['json'];
$file = fopen('new_data.json', 'w+');
fwrite($file, $json);
fclose($file);
?>
I am running this on apache httpd. For example, I just fire up localhost/demo.html on chrome and I read the diagnostics. No matter what I do, new_data.json is empty. I even tried to just call the php file and have it write a file. No post. It didn't do anything. No matter what, when I check the apache server (or anywhere for that matter), there is no data being written to new_data.json. It's just not there.
[EDIT] I added in the ability to print an error message. There is something wrong with the php. It is returning an error and I am not quite sure what is going on, here is the message I am currently studying:
Object {url: "json.php", type: "POST", isLocal: false, global: true, processData: true…}[Object, "parsererror", SyntaxError]
Please, can someone tell me what the heck I am doing wrong? I have stared at this for hours. I am willing to give rep, and if need be, take a ding on my own reputation on this, but I wouldn't ask unless I got desperate.
References
PHP to file,
JSON Post to file,
Searched Overflow, and
RTM
Whatever is check() function do, hope it's error less
you should use json encode before echo in your php page like,
echo json_encode(array(check($_POST) ? 'true' : 'false'));
Also, trying to call ajax in getjson callback may solve your problem like,
var newData;
$(document).ready(function()
{
$.getJSON('test.json', function(data){
console.log('test1.js');
console.log(data.herp);
console.log(data.derp);
console.log(data.supersuper);
console.log(data.derpderp);
//alert('success');
newData = data;
console.log(newData);
$.ajax({
type: 'POST',
url: 'json.php',
dataType: 'json',
data: newData,
success: function()
{
alert('Successful submission');
}
});
});
});
I have a strange problem with Jquery Ajax with the following code.
Situation 1:
function leuk(decrease_id, user_id) {
$.ajax({
type: "POST",
url: 'http://schoolprove.nl/nieuw/index.php/leerlingen/checkvoortgang/',
data: 'decrease_id=' + decrease_id + '&user_id=' + user_id,
success: function (msg) {
$('#output').html(msg);
}
});
}
Situation 2
function leuk(decrease_id, user_id) {
$.ajax({
type: "POST",
url: '/nieuw/index.php/leerlingen/checkvoortgang/',
data: 'decrease_id=' + decrease_id + '&user_id=' + user_id,
success: function (msg) {
$('#output').html(msg);
}
});
}
The AJAX url works sometimes whith http:// and sometimes without. I build and error catch when a error occured. This works very well at IE but Firefox doesn't give a error. So at some computers with Firefox this will not work. It is very strange and i don't know why it will not work.
Situation 1: Works sometimes
Situation 2: Works sometimes
Sometimes situation 1 works and ad a other computer situation 2 works, WHY?
Anybody know how to solve?
Thank you very much!!
Redirect your domain like this tonerize.com to www.tonerize.com will solve this issue
please read this http://en.wikipedia.org/wiki/Same_origin_policy. for more information
Is your ajax file located on some other server?
If no then, you need not specify the the whole path for url.
Its enough if you use
url: 'ajaxfilename.php' //depending on the folder the file is located
I found the solutions it is causing due to cache, try to disable the cache and add the random value in your query string.
function leuk(decrease_id,user_id)
{
$.ajax({
type: "POST",
cache:fale,
timeout:10000,
url: '/nieuw/index.php/leerlingen/checkvoortgang/?rnd='+Math.random(),
data: 'decrease_id='+decrease_id+'&user_id='+user_id,
success: function(msg){
$('#output').html(msg);
}
});
}
You can not use a path such as this for AJAX.
http://something.com/file.php
It has to be relative to your file and located on your server like to.
/file.php
I am not quite sure what your problem is though, your question does not provide any error information.