ajax call not performed in firefox when form submits - javascript

I don't know what I'm doing wrong. The following snippet works fine in Chrome but not in Firefox. The odd thing is, if I test in Firefox and add a breakpoint, e.g. at "request.send(params)" and do a "Step Over" everything works fine. But if I perform a "Continue" it also wont work.
Does anybody know, what I'm doing wrong? Thanks
$(document).ready(function(){
var form =$("form#my_form");
var id = form.id;
form.submit(function(event){
event.preventDefault();
myVar.myMethod(document.getElementById('my_input_1').value, document.getElementById('my_input_2').value);
this.submit();
});
});
var myVar = {};
myVar.myMethod = function(par1, par2) {
params = "par1=" + par1 + "&par2=" + par2;
request = new XMLHttpRequest();
request.open("POST", "Destination", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
};

I'm not sure why it's working in Chrome - could just be a speed thing.
Sounds like your ajax request (being asynchronous) isn't getting sent before this.submit(); You need to write some kind of callback in myVar.myMethod that only processes once the XHR is finished.
A better method might be (since you're using jQuery, but not really utilizing it):
$(document).ready(function(){
var form =$("form#my_form");
var id = form.id;
form.submit(function(event){
event.preventDefault();
$.post({
url: '??', // from form - the url you submitted to
data: {par1: $('#my_input_1').val(), par2: $('#my_input_2').val() }
success: function( data ) {
//handle the returned data
}
})
});
});
Or, if you're trying to submit those two fields in the POST data to your form's url attribute, you should just process the POST data when you get it on the next page - in other words, as long as your inputs are in the form they should be sent to the url with POST.

I removed the this.submit()-Line and now everything works fine. Thanks to David Votrubec's and charlietfl comments, which brings me on the track.
$(document).ready(function(){
var form =$("form#my_form");
var id = form.id;
form.submit(function(event){
event.preventDefault();
myVar.myMethod(document.getElementById('my_input_1').value, document.getElementById('my_input_2').value);
});
});
var myVar = {};
myVar.myMethod = function(par1, par2) {
params = "par1=" + par1 + "&par2=" + par2;
request = new XMLHttpRequest();
request.open("POST", "Destination", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
};

Related

xhr does not get invoked from js

i am using phonegap and trying to invoke a xhr POST on click of a button.
my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:
function fetchTags(){
console.log("Fetched url is:" + IMAGE_URL);
//var url = "http://localhost:8080/echo";
var url ="http://localhost:8080/echo";
console.log("#1");
var xhr = new XMLHttpRequest();
console.log("#2");
xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
console.log("#3");
xhr.setRequestHeader("Content-type", "application/json");
console.log("#4");
xhr.open('POST', url, true);
console.log("#5");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response);
}else{
window.alert(xhr.status);
}
};
console.log("#5");
//var msg = "{'message' : '" + IMAGE_URL + "'}";
console.log("sending request");
xhr.send(JSON.stringify({"message" : "my msg"}));
}
Button code:
<button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
The console prints:
Fetched url is:undefined
#1
#2
#3
To clarify i can see first console.log getting printed. but that's it. nothing happens after that.
just for everyone's benefit the issue was not the javascript but invoking from the phonegap using the localhost.
I was unders the assumption that phonegap will be able to access my api at localhost (not sure why had this stupid idea) but yes using the actual ip of the host machine made it work right away.

How to get link specific php varaible to pass through ajax

I dont know much about ajax or jquery yet but i currently have an ajax script that does successfully send A variable through and does work properly.
--the way i have it set up is like this for my loop:
<?php
$tt= mysql_query("SELECT * FROM monsters");
while ($row= mysql_fetch_array($tt))
{
$namee= $row['name'];
echo "<a id='namee' onclick='post();'>$namee</a>", "</br>";
}
which echos:
horseman
dragon
---the results do make a list of all the names from the table as shown above and they are clickable which is working great
my ajax request is this:
<script type="text/javascript">
function post(){
var hr = new XMLHttpRequest();
var url = "mess.php";
var vars =document.getElementById("namee").innerHTML;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}
</script>
the alert when i click on horseman returns "horseman"
but when i click on dragon it still alerts "horseman"
i would like to get the specific variable ( when i click horseman it says horseman and when i click dragon it says dragon etc) so i can send it through ajax to update a database ( which i already know to to set up)
please help me and show me if you can full code so i can learn and see how it works and understand your response since im new like i said :)
thanks in advance:
if have any questions feel free to ask
Thats because ids should be unique, jquery will get only the first element with that id, my suggestion is to pass the value by parameter:
echo "<a class='namee' onclick='post($namee);'>$namee</a>", "</br>";
And then the js:
function post(vars) {
var hr = new XMLHttpRequest();
var url = "mess.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}

readystate never reaching 4

In the code below I try to post some data to a table and then retrieve several records from the table afterwards. For testing purposes I have only included a dummy query in the php, which returns a valid xml.
But the Javascript readystate only reach readystate 1 (twice). As the php seems to be working fine I suspect I have scripted the javascript incorrectly. Is it a problem with the "request" variable?
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
var name = $('input[name=name]').val();
var request = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var xml = request.responseXML;
var dynamiclist = '';
document.getElementById("myLink").innerHTML = '';
var posts = xml.documentElement.getElementsByTagName("post");
for (var i = 0; i < posts.length; i++) {
var Msg = posts[i].getAttribute("Msg");
alert("test");
var dynamiclist = dynamiclist + '<article class="middleContent"><header><h2>' + Msg + '</h2></header> </article>';
document.getElementById("myLink").innerHTML = dynamiclist;
};
};
};
request.open('POST', 'process.php', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send('name=' + name);
});
});
Using jQuery makes sense here.
Simple solution however most probably is to simply remove the last "true" in request.open(), which makes the request an asynchronous, non-blocking one (which it really should be anyway). MDN also states at onreadystatechange that you shouldn't be using it with synchronous requests (aka requests that have "true" as third argument for open())
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Try preventing the default form event from firing:
$('form').submit(function(event) {
event.preventDefault();
This prevents the form element from reloading the browser window.

XMLHTTPRequest.send() in not working firefox

The following piece of js code is not working only in firefox but works fine in chrome and IE. Can anyone please help.
I am trying to submit two forms with a single click of a button
function abc(url){
var form = document.getElementById("sample");
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("actionCode=2");
var form1 = document.getElementById("sample1");
form1.submit();
}
What's strange is that on placing place a debugger using firebug at line xhr.send() it works, as soon as I remove the debugger from firebug, xhr.send does not execute.
Any suggestions are really appreciated.
Thanks
It is async request, you need to check status of the request
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var form1 = document.getElementById("sample1");
form1.submit();
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("actionCode=2");
or this may help
xhr.open("POST", url, false); - it will make the request synchronous.
Then you will not required to move submit or listen to events
And additional way to submit form data
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Categories

Resources