ajax unexpected token * - javascript

I have ajax script but it returns unexpected token *. I use ajax example from w3school.com and it different from usually. This is my script:
<script>
$("#conform").click(function ()
{
var a= $(this).closest(".col").prev().find("#prod_qty").val();
var b= $(this).prev().val();
var c= $(this).closest("#highlight_product").find("#name").val();
var d= b * c;
var e= "<?php echo $_SESSION['name'] ?>";
var f= "<?php echo $_SESSION['email'] ?>";
}
)
function buy()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ('Browser does not support HTTP Request');
return;
}
var url='buy.php?user='+e+'&email='+f+'&product='+c+'&count='+a+'&total='+d;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open('GET',url,true);
xmlHttp.send(null);*/
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete')
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xmlHttp;
}
I try find it in google, It says problem with dataType, It must HTML. But i dont know how to change it, anyone know?

The line
xmlHttp.send(null);*/
has unexpected "*/" which needs to be removed
xmlHttp.send(null);

Can I suggest using Jquery AJAX wrapper? It's cross browser compliant, much neater and lets gives you a handy callback function on completion(really important) since the result is ASYNC which allows you to retrieve data before execution.
$.ajax({
type: "POST",
url: '',
data : '',
dataType: 'JSON',
}).done(function(data) {
// this will be run when the AJAX request completes
var ParsedData= jQuery.parseJSON(data);
// this will be run when the AJAX request succeeds
}).fail(function() {
// this will be run when the AJAX request fails
}).always(function() {
// this will be run when the AJAX request is complete, whether it fails or succeeds
});
}

Related

ajaxStart() and ajaxStop() functions not getting fired

I am building a Q/A website. When the user clicks on a particular question, he is redirected to the question page where the user can post answers.
Now, the issue is while the user clicks on "Answer" link, few things are processing in the background like updating db, sending mail, etc. I am trying to display a load indicator in the UI but the AJAX function is not getting triggered.
Here is my code:
HTML:
<span id="msg"><img src="ajax-loader.gif"/></span>
<a id="sub-link" href="javascript:void(0)" onclick="loadAnswerList(document.getElementById('user-ans').value,<?php echo $qid; ?>,'<?php echo $posted_by; ?>')">Answer</a>
JS:
$(document).ajaxStart(function () {
$('#msg').show();
}).ajaxStop(function () {
$('#msg').hide();
});
AJAX request
function loadAnswerList(ans,qid,postedBy,page) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ans_container").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page,true);
xmlhttp.send();
}
I also tried adding $(document).ready(function() { .... }); above the ajax but still it is not working. Am I missing anything?
Am using jQuery version 3.2.1
jQuery does not work with the native XMLHttpRequest object. The ajaxStart and ajaxEnd lines you are using deals with their api. So in order to use it, you need to use jQuery's .ajax() or .get() methods.
Thanks for the details.
This is the modified function:
function loadAnswerList(ans,qid,postedBy,page) {
var answer=ans;
var qstnid=qid;
var postby=postedBy;
var pg=page;
var request = $.ajax({
type: "GET",
url: "load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page",
data: {ans: answer, qid: qstn_id, postedBy: postby, page: pg},
dataType: "html"
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Please correct me if am wrong. One more thing - I want to display the response from the php page to a particular div as I have done in my previous ajax request.
document.getElementById("ans_container").innerHTML = this.responseText;
How do I do it here?

Flag Query PHP to JavaScript

I have that
JavaScript
flagQuery = session.reponseText;
alert(flagQuery);
flagQuery = JSON.parse(flagQuery);
contentElt.innerHTML = "valeur FLAG" + flagQuery;
My javascript must receive a flag sent from php.
The code above is the treatment of flag when it is received.
In my php I declare the variable flag to true.
I want to treat this with Ajax, if it's possible.
I don't know what to add in the PHP to get the flag in JavaScript?
I should prefer not to have to overload my code with a jQuery bookshop that I will use it for half a score line of code.
I assume want to access php value through ajax request. And you can do that liek below;
PHP: flag.php
<?php
$flag = "Your flag value";
echo $flag;
JS:
$.ajax({
url: "flag.php",
type: "get",
success: function(data){
alert("Flag value is: " + data);
},
error:function(){
alert("Error occured!");
}
});
Pure JS:
<script>
function getFlagValue() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 && xmlHttp.status==200) {
alert(xmlHttp.responseText);
}
}
xmlHttp.open("GET","flag.php",true);
xmlHttp.send();
}
</script>
Hello. Try this and see if it's you need.
//PHP File
<?php
echo json_encode(array("one","two"));
?>
//Js File
$.get("page.php", function(data){
alert(data)
})

Transform this function completely to jQuery

I need this function as jQuery.
There is a part jQuery but I am finding a tough time to write the code!
function showUser(str) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("drop_em").innerHTML = xmlhttp.responseText;
$('#scrollbar3').tinyscrollbar();
}
}
xmlhttp.open("GET", "list_playlist_popup.php?qq=" + str, true);
xmlhttp.send();
}
What have you tried? Where are you stuck? (Because this is the most basic form of AJAX call in jQuery)
$.get(
"list_playlist_popup.php",
{ qq: str },
function success(data) {
$('#drop_em').html(data);
$('#scrollbar3').tinyscrollbar();
});
Use jQuery Ajax :
$.ajax({
url:'list_playlist_popup.php',
type:'POST',
data:{
variable : value
},
success:function(data){
alert('success');
}
})
Just copy paste this over the existing function.
function showUser( str ) {
$.ajax({
url: 'list_playlist_popup.php',
data: {
'qq': str
}
}).done(function( data ) {
$('#drop_em').html(data);
$('#scrollbar3').tinyscrollbar();
});
}
function showUser(str) {
$.get('list_playlist_popup.php',{qq:str},function(response) {
$('#drop_em').html(response);
$('#scrollbar').tinyscrollbar();
});
};
This is your jQuery equivalent.

Cross domain json parsing

I have the following json in one of the links:
{"edi":[{"NEdid":"19", "Publications":"B0001", "NCid":"141"
, "SEditionCode":"C0001", "SLang":"English", "STimeZone":"GMT+4:00"
, "SEdname":"Default", "NEdmon":"1", "NEdtue":"1", "NEdwed":"1"
, "NEdthu":"1", "NEdfri":"1", "NEdsat":"1", "NEdsun;":"1"
, "SFrequency":"Daily", "NSequence":"1", "dtCreatedOn":"2013-03-25 12:18:46.0"
, "NCreatedBy":"3", "dtModifiedOn":"2013-03-25 12:18:46.0"
, "NModifiedBy":"3", "BIsActive":"1", "BIsDeleted":"0", "NNoe":"7"}]}
I want to parse cross domain json. I am calling the following function on page load of a php page and using localhost. I am using the following code:
function loadEditionList(edurl) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var jsonEdition = xmlhttp.responseText;
var objEdition = JSON.parse(jsonEdition);
for (var i = 0; i < objEdition.edi.length; i++) {
var editionname=objEdition.edi[i].SEdname;
alert(editionname);
}
}
}
xmlhttp.open("GET", edurl, true);
xmlhttp.send();
}
Above code is working in IE with a alert message regarding security, but it is not working in chrome and mozilla. xmlhttp.status is 0 in chrome and mozilla.
Another code I used:
function loadEdition()
{
var getUrl = 'someurl/desktopReader.do?numPublisher=3&type=Editions&numPublication=19';
$.ajax({
url : getUrl,
type : 'GET',
dataType : 'jsonp',
jsonp: 'jsonp',
crossDomain : true,
success: function() { alert('Success!'); },
error: function() { alert('Uh Oh!'); },
});
}
In this case I always get alert 'Uh Oh!'.
Please, suggest me the proper way!
Maybe problem is on server side. Here is example i give other guy: http://jsfiddle.net/YGm89/
The code:
$.ajax({
url: "http://ws.geonames.org/postalCodeSearchJSON",
dataType: "json",
data: {
postalcode_startsWith: request.term
},
success: function(data) {alert("ok");}
});
Example with your code.
I removed JSONP function callback name, becouse i can not see any in you request. I asume, thet you do standard JSON request (not JSON P).

want to create a js plugin that sends a lot of data async to another server

is there a way i can send a lot of data to another server asynchronously via javascript without running into cross domain problems?
how is google analytics able to send their encoded data to their servers?
you can use Ajax to send a lot of data.
Native Javascript:
function NewAjax(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function load_page (url, container){
ajax=NewAjax();
ajax.open("GET", url,true);
ajax.onreadystatechange=function(){
if(ajax.readyState==1){
container.innerHTML = "loading";//<-- Preload
}else if(ajax.readyState==4){
//Page loaded
if(ajax.status==200){
//OK
container.innerHTML = ajax.responseText;
add_action();
}else if(ajax.status==404){
//Page doesn't exist
container.innerHTML = "Erro loading page";
}else{
//Show error
container.innerHTML = "Error:".ajax.status;
}
}
}
ajax.send(null); }
Or
JQuery Ajax:
$.ajax({url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');}});

Categories

Resources