Jquery Ajax not working on IE - php

I got very strange bug on IE. I used the code below to make a ajax request to get data from database and create drop down option <option> with that data. The thing is on IE the data didn't appear properly, it's only showing first character of data, but on other browser the data are showing correctly. I tried printing out the data as well, data are correct.
So I suspected either of my Jquery selection or append is wrong and tried appending outside the ajax call with some junk data and data are showing correctly but then again I put that code inside the ajax and its not showing again... I really out of clue now.. Can you guy plz help me with this? I have tested with FF, Chrome and safari they all working fine...
$.ajax({
cache: false,
type: "POST",
url: "<?php echo $this->baseUrl(); ?>/rewards/getdiscounttype/",
data: { esid: estore_id }
}).done(function( data ) {
var obj = jQuery.parseJSON(data);
jQuery.each(obj, function (i, app) {
//alert(i+app['discount_type']);
var sel = $('select[name=discount_type'+id+']');
sel.append('<option value="'+app['id']+'">'+app['discount_type']+'</option>');
});
});

$.ajax({
cache: false,
type: "POST",
url: "<?php echo $this->baseUrl(); ?>/rewards/getdiscounttype/",
data: { esid: estore_id },
datatype: "json",
succes: function(jsonData){
$.each(jsonData,function(i,app){
var sel = $('select[name=discount_type'+i+']');
sel.append('<option value="'+app.id.+'">'+app.discount_type.+'</option>');
});
},
error: function(e){
}
})
Try this, and I think its better to treat JSON as objects like app.id in stead of app['id']. Haven't had much time to do some testing, Ive you would give me the json you receive I can test.

Working now with JavaScript!
$.ajax({
cache: false,
type: "POST",
url: "<?php echo $this->baseUrl(); ?>/rewards/getdiscounttype/",
data: { esid: estore_id }
}).done(function( data ) {
var obj = jQuery.parseJSON(data);
/* clearing options with JS since jQuery cleare the select in the DOM but enter code herenot on screen. */
$('select[name=discount_type'+id+']')[0].options.length = 0;
$('select[name=discount_type'+id+']').children().remove().end().append('');
jQuery.each(obj, function (i, app) {
var sel = $('select[name=discount_type'+id+']');
sel.append('<option value="'+app.id+'">'+app.discount_type+'</option>');
});
});

Related

Ajax post not appending data to URL

I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.

passing javascript object array to ajax

This is my imple code on submit of form. Where I want to insert table data values in database through ajax. But it's not going to controller.
$('#submit').click(function(){
var TableData = new Array();
$('#cart_details tr').each(function(row, tr){
TableData[row]={
"productname" : $(tr).find('td:eq(0)').text()
, "quantity" :$(tr).find('td:eq(1)').text()
, "unit" : $(tr).find('td:eq(2)').text()
, "unit_rate" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift();
//TableData = $.toJSON(TableData);
var TableData = JSON.stringify(TableData);
alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
When I stringify tabledata array output is like this..
[{"productname":"Copper Sulphate","quantity":"1","unit":"1","unit_rate":"100"},
{"productname":"Hypta Hydrate","quantity":"1","unit":"1","unit_rate":"100"}]
My question is why it's not going to controller? it's because of array object or something else??
Tabledata is javascript object array . Am I right??
Use
$.ajax({
instead of
$.post({
use this code
$.ajax({
type: "POST",
url:followurl,
data: {TableData : TableData},
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
check the Documentation jquery.post
The syntax for $.post is
$(selector).post(URL,data,function(data,status,xhr),dataType)
You don't have to define the type ,
but here you are using the $.ajax mixing with $.post
this is the $.ajax function syntax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
SO change the $.post to $.ajax and try
As you can read in the documentation, you can pass an object to data. I think you'd make things easier and simpler for you if you followed that approach.
...
//TableData = $.toJSON(TableData); NO!!!
//var TableData = JSON.stringify(TableData); NO!!!
//alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: {
dataTable: TableData
},
datatype : "json",
cache: false,
success: function (data) {
alert(data);
}
});
});
Very simple example (without validation or anything of the kind) of index.php/purchase/save_product
$data = $_POST["dataTable"];
echo $data[0]["productname"];// Sending back the productName of the first element received.
die();
As you can see, you could access data in your index.php/purchase/save_product file very easily if you followed this approach.
Hope it helps.
Hi It look like you are using some CMS or Framework. Can you please let us know which framework or CMS you are using. I would then be able to sort out this issue. It looks like you are using Code Ignitor. If its so then i hope this would help you
$.post( "<?php echo base_url();?>index.php/purchase/save_product", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
in Your case your ajax call must look like
var followurl="<?php echo base_url();?>index.php/purchase/save_product";
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
Error Seems to be in your followUrl please try using as its in mine code

How to prevent multiple loading PHP script calling JS script?

I created a simple voting system (+ and -) on Ajax for users comments. One page have 50 posted comments and you can vote for each "plus" or "minus". This data sent through the PHP script to the database. However, if a user votes, the PHP script is called 50 times - it is visible in Chrome developer tool. There are errors - more value than expected. Here is my code (two DIV buttons and the script).
Tell me please how to change the code to the script (up_vote.php or down_vote.php) is called only once.
<script type="text/javascript" src="raitings/jquery.js"></script>
<script type="text/javascript">$(function() {$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down')
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);}
});
}
else
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);
} });
}
return false;
});
});
</script>
//php code below;
echo "<div class=\"box1\"><div class=\"up\">".$up."</div>"
."<div class=\"down\">".$down."</div></div>\n";
Using jQuery, it's important to know that events are stackable, even if the event is exactly the same. For example:
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
If we ran these three lines verbatim, we'll have 3 different events attached. That is, we would get 3 alerts one after the other by clicking in an element with the vote class.
In addition, oftentimes it happens that pages being loaded through ajax carry the same <script></script> block of the parent page, and when this is the case, the code is inadvertently being processed again and again with every ajax call.
While I was not able to pinpoint exactly how is this happening by the code you provided, it seems this is the most likely scenario: your click handler event is being loaded several times, and as a result one click triggers several ajax calls.
The quick and dirty solution when this presents as I mentioned in the comments is replacing:
$(".vote").click(function()
By:
$(".vote").unbind("click").click(function()
Which thanks to the unbind function forces it to discard previously attached events every time a new one is attached, thus preventing it from having more than one event attached no matter how many times the code is processed.
While this will work, the better solution is, of course, to locate where is the js code being loaded multiple times and make sure it is loaded just once.
$(".vote").each(function () { $(this).click( clickHandler .... etc should solve your problem.
I don't fully understand how your version works but I would do it similar to this:
+
-
Where 200 would be the unique id of the comment.
Then have a vote_up() and vote_down() function defined in a JavaScript and add your ajax requests there.
That way it should not call the script more than once when +/- button is clicked.
You can disabled button before send you ajax request.
// Sample:
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
parent.fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
if(name=='down')
{
$.ajax({
type: "POST",
url: "raitings/down_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "raitings/up_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});

Strange behaviour with jQuery.ajax

I've suddenly gotten a very strange "bug". Up to now, this script has worked like a charm. But all of the sudden the formData variable is not passed through jQuery.ajax, as if it does not exist.
The funny thing is that if I trigger an alert displaying the data, it all works. But as soon as I remove the alert, the php script tells me that formData index is missing.
I'm clueless to what causes this or how to solve it :-/
This works fine on my development server, but not on the production server.
jQuery('#btn_saveForm').live('click', function() {
var instance = 'update';
var brand_id = jQuery('#itemID').val();
// Get form data
var form_data = jQuery("#data_form").serialize();
// alert(form_data); //If I uncomment this, the script works...
//Process form data
jQuery.ajax({
url: siteURL +"/wp-content/themes/my_theme/include/jquery.php",
data: {
instance : instance,
formData : form_data,
brandID : brand_id
},
success: (function(feedback) {
showFeedback(feedback);
}),
dataType: 'json'
});
});
My guess would be that putting the alert() in allows the form_data and brand_id variables to be filled completely before the AJAX request is sent. With that in mind, try this:
jQuery.ajax({
url: siteURL +"/wp-content/themes/my_theme/include/jquery.php",
data: {
instance : instance,
formData : jQuery("#data_form").serialize(),
brandID : jQuery('#itemID').val()
},
success: (function(feedback) {
showFeedback(feedback);
}),
dataType: 'json'
});
Alternatively, just to test, you could set async: false on the AJAX call to see if that makes a difference.
try to restart browser / change browser to another and see whats happening then
If it's true that you have some races here (which would be very strange, as js is single-threaded), the following should help you:
setTimeout(function() {
jQuery.ajax({
url: siteURL +"/wp-content/themes/my_theme/include/jquery.php",
data: {
instance : instance,
formData : form_data,
brandID : brand_id
},
success: (function(feedback) {
showFeedback(feedback);
}),
dataType: 'json'
})
}, 0);
The 0-timeout construction will put your code at the end of execution queue.

jquery .load not loading immediately after loading data

I was wondering if this was making an asynchronous request...write now Im using:
<script type='text/javascript'>
$(document).ready(function() {
var ktitle = $('.hiddentwo').text();
$('div#tab2').load('morefour.php?title=' + encodeURIComponent(ktitle));
});
</script>
what Im doing though is adding text in the first, into the database, on the current php file (addtext.php). Im passing the Id of the current document to the morefour.php and that is loading the added text on the second tab...the thing is, Im having to refresh to see the content again. Im running on localhost btw.
For more clarity, Im running another jquery script that on clicks, retrieves this data to send it to a php file to enter into a database
$(".button").click(function() {
var content = $(this).siblings().outerHTML();
$.ajax({
async: false,
type: "POST",
url: "tosqltwo.php",
data: {
content: content
}
});
});
$(function(){ //shorthand of $(document).ready
$('div#tab2').html($.ajax({
type: "GET", //if you are doin $_GET['title'] in morefour.php
url: "morefour.php",
data : {title:ktitle},
dataType: 'html', //i am not sure about this part
async: false
}).responseText)
});
or you can try
$(function(){
$.ajax({
url : 'morefour.php',
data : {title:ktitle},
type:'GET',
dataType:'html',
success: function(data) {
$('div#tab2').html(data);
}
});
});
you can use $.ajax function with async to false.
$.ajax({
async: false,
url : 'morefour.php',
data : 'title=' + encodeURIComponent(ktitle),
success: function(data) {
$('div#tab2').html(data);
}
});

Categories