jQuery AJAX call not working in Webkit - php

I've run into a strange issue with Webkit based browsers (both Safari and Chrome - I'm testing on a Mac) and I am not sure what is causing it. Here's a small script I've created that replicates the issue:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function doRequest() {
document.test.submit();
$.ajax({
type: "GET",
cache: false,
url: 'ajax.php?tmp=1',
success: doSuccess
});
}
function doSuccess(t_data,t_status,req) {
alert('Data is: '+ t_data +', XMLHTTPRequest status is: '+ req.status);
}
</script>
</head>
<body>
<form name="test" method="post" action="ajax.html" enctype="multipart/form-data">
<input type="file" name="file_1">
<br><input type="button" value="upload" onclick="doRequest();">
</form>
</body>
</html>
ajax.php is:
<?php
echo $_REQUEST['tmp'];
?>
This works as is on Firefox, but the XMLHTTPRequest status is always "0" on both Safari and Chrome. If I remove this line:
document.test.submit();
then it works, but of course the form is not submitted. I've tried changing the form submit button from "button" to "submit", but that also prevents it from working on Safari or Chrome.
What I am trying to accomplish is:
submit the form
call another script to get status on the file being uploaded via the form (it's for a small upload progress meter).
Any help is really appreciated - I'm hopeful it is just a quirk I'm not familiar with.
Thanks!
Brian

Simply put: you cannot upload files using AJAX.
There are nice plugins such as jquery form that will handle this automatically (by creating a hidden iframe and performing the real file upload).
I think FireFox has a native file upload API but if you want a cross browser solution you will need to take a look at some plugins. Using a flash upload is another solution.

My experience while developing a similar upload checking tool1 is that you should use both success: .. and complete: ... They would probably do the exact same thing in your code and you can have them call the same function. complete: gets called when the request finishes, success: when a request succeeds. Thus maybe:
function doRequest() {
document.test.submit();
$.ajax({
type: "GET",
cache: false,
url: 'ajax.php?tmp=1',
complete: doSuccess,
success: doSuccess
});
}

Related

Jquery Preview Video In Div After PHP Validation Not Working While An Image Does

I use the following code successfully (with different IDs, etc.) to preview a banner image in a div after PHP validates the upload, using AJAX. This works just fine. No issues.
I am having a problem doing the same with a video. The code below works well, except the video doesn't preview. Just echos back the alt tag value. I am passing the uploaded video ID to a hidden input for some back end PHP validation via ajax function. After validation, the video is moved to the folder I want it to move to without a problem. I also echo back an error if the video doesn't meet requirements. This is all good. The video just doesn't show on the page. Any help is appreciated.
<div>Upload Video</div>
<div><input type="file" id="banner-video"></div>
<div id="loading"></div>
<div class="padding-top-1" id="show-video"></div>
<script>
$(document).ready(function() {
$("#banner-video").change(function() {
var data = new FormData();
data.append("file", $("#banner-video")[0].files[0]);
$.ajax({
url: "create-promotions/video-banner-promotions/create-promotion.video.process-banner-video.php",
method: "POST",
data: data,
contentType: false,
processData: false,
cache: false,
beforeSend: function() {
$("#loading").load("../loading.php");
},
success: function(data) {
$('#loading').hide()
$('#show-video').html(data); // ********** This line seems to be the problem
if ($('#show-video').find('img').length) {
bannerVideo = $('#show-video').html(data);
document.getElementById("the-banner-video").value =
bannerVideo
}
}
});
});
});
</script>
<input type="hidden" id="the-banner-video" value="">
Nevermind. After 3 days of working on it, it was just using the wrong tag on my back end php echo. The code works. Feel free to use it if you ever come across it. Let me know if you would like the other pieces.

Jquery IE. ajax request running only once

This is the code . Ajax is only running once when i run in the IE. But with all other browsers it is running great.
Untitled Document
function cool_add()
{ //alert(post_id);
var txt1 = $("#txt1").val();
$.post('jqueryphp.php', {txt1:txt1}, function(data) {
var dat = data;
$("div").html(data);
});
}
</script>
</head>
<body>
<form>
<input type="text" id="txt1" /><br />
<input type="button" id="butn" onclick="cool_add();">
</form>
<div></div>
</body>
</html>
It is running great in all other browsers but with IE it only runs once thats it.
IE tends to cache all request and if the request params are same then it will return the cached response. To avoid this, you can use $.ajaxSetup following code which will be applied globally for any future ajax calls.
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false,
});
You can also apply this cache on a specific call as below,
$.ajax ( {
//..other params
cache: false,
//..other params
});
When cache=false, jQuery will add current timestamp to each request so that the request params are unique.
In your ajax call, make sure to include
cache: false
IE caches everything, so it assumes your calls are all the same.
I suspect this is the caching issue I identified in your question yesterday.
http://www.gtothesquare.com/2010/09/26/if-jquery-ajax-call-not-working-in-internet-explorer-try-this/

dynamic loading of html via php javascript not executing

i have a simple setup, with php pulling html content from a database. if i go to my template page, it loads the data and returns it to the browser via a simple php echo ... not rocket science.
now, i've written an html file using jquery and an ajax call. i load the html file in my browser and the javascript / ajax query works.
when i load the html into the database and print it out via the php / echo, the content is the exact same when i view the source, but the ajax query doesn't execute.
<html>
<head>
<title>random query - api - get</title>
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head>
<body>
<pre>
executing the GET method
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){
alert( msg );
}
});
</script>
</pre>
</body>
</html>
Any comments / suggestions would be great. What I find bizarre, is i have no problem copying the source of http://jquery.com/ and pasting it into the db and doing the php / echo. this works fine. maybe an onLoad() would help...hm.
The issue is outlined in the following url:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
When I load the javascript console in chrome I get this:
XMLHttpRequest cannot load http://some-rand.om.api.com/user?011b38b8-011f-4b03-bb21-4c5bb26600b3. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
To resolve the problem, on the api vhost, in the code that serves the content accessed by the ajax query, i added this (it is also php):
header('Access-Control-Allow-Origin: http://some-rand.om.client.com');
Now when I access it, it's all good and loads as expected. So, infact, it wasn't related to it being stored in the database, php or javascript. It was related to cross site scripting.
Or, to be super lazy (probably not a great idea...):
header('Access-Control-Allow-Origin: ' . $_SERVER["HTTP_ORIGIN"]);
If in your description of the problem you are listing the whole of the code, then the JavaScript should be wrapped in a $(document).ready(function(){ ... });.
i.e.
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){alert( msg );}
});
});

HTML form with PHP

I'd like to have a form that executes some php code without having to open a completely new php page. Right now, I'm familiar with "POST" so that I can execute a php file and call the variables from the HTML form using $_POST[variable] but, it takes time to open a new page, and I want to have a form that does the action right then and there.
For example, can someone write html code that creates a text box and a button, and when the user presses go, it displays the text that the user entered right next to the button.
Thanks!
Here's an HTML and PHP snippet to get you started. It uses jQuery and just writes the value of textarea beneath the submit button using AJAX.
HTML Snippet [file=so.html]
<!DOCTYPE html>
<html><head><title>SO Example</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js">
</script>
</head>
<body>
<form id="frm" name="frm">
<textarea id="txt" name="txt" rows="4" cols="40">
</textarea><br />
<input type="submit"><br />
<span id="result"></span>
</form>
<script type="text/javascript">
$('#frm').submit(function(e){
e.preventDefault();
$.ajax({
url:"/so.php",type:"post",dataType:"html",
data:$('#frm').serialize(),
success:function(obj){
$('#result').text(obj);
}
});
});
</script>
</body>
</html>
PHP Snippet [file=so.php]
<?php
echo $_POST['txt'];
If you want to execute php code after the page is loaded without opening a new page then you should be using a technology like AJAX. PHP is a pre-processor and is meant to be run to process a page, not for functions after that.
With AJAX you can use javascript to call a webpage that's processed by PHP. Then with that returned page/data you can do your page function.
For more info on ajax check here: http://en.wikipedia.org/wiki/Ajax_(programming)
I recommend looking at jQuery as an ajax wrapper: http://api.jquery.com/jQuery.ajax/
You can find a ton of tutorials online to get you started.
I'd look into AJAX, more specifically an AJAX call using jQuery. It looks a little bit like this for a POST request:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
});
And if I filled that out, it might look like this:
$.ajax({
type: 'POST', // Method of submission: POST or GET
url: 'processor.php', // The script to send to.
data: { id: 1, name: 'John' }, // The data to give to PHP.
success: function(data) { // Do something with what PHP gives back.
console.log(data);
}
});
For more info on jQuery's AJAX functions, head here: http://api.jquery.com/category/ajax/
You're interested in jQuery.ajax(), jQuery.post(), and jQuery.get() probably.

Unable to get JQuery to return AJAX data

I'm relatively new to JQuery, so before I try to build the actual app, I'm trying to build a simple Ajax script that'll simply return the data.
However, despite more or less copying and pasting the code, I still can't get it to work.
<html>
<head>
<title>This is a title!</title>
<script src="scripts/jquery-1.4.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function(){
alert ('1');
$.ajax({
url: 'process.php',
dataType: "html",
success: function(data) {
$('#testsite').html(data);
alert('Load was performed.');
}
});
alert ('2');
});
</script>
</head>
<body>
<div id='login'>
<div id='testsite'>
</div>
<input type='button' id='lsubmit' value='Submit' />
</div>
</body>
</html>
The JQuery script is definitely loaded, process.php is definitely called up (it creates a text file just to prove that it has in fact been run) but anything echo'd in the process.php doesn't get sent through as data.
It's probably something simple, but I've run out of ideas.
Thanks in advance
Okay, this was major stupidity on my part. I messed up the process.php file so it didn't have any data to return
I have no memory of doing this and no idea why I did. Sorry for wasting your time and thanks to all those that helped =]
You will want to add an error handler, see if that gets fired, and inspect the error that is happening.... Add a callback to error.
HTH.
Try using these
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
even you solve yur problem , you can try these

Categories