Problem: The parameter being passed through my addData() function has a hyphen in it; think "12345678-9". Whenever the data being passed has a hyphen, I get the Ajax Fail! alert box popped up on my app. However, whenever I hardcode the $_GET variable to be a string or number without a hyphen, this part of my app works. I've narrowed it down to the likely fact that the hyphen is causing this error. See code below.
HTML
<button id="add-analysis-button" onClick="addData( $( '#click-number' ).text() )">Add Data</button>
Javascript/jQuery/AJAX
function addData(a_ship) {
$.ajax({
type: 'GET',
url: 'models/add-data.php?oShip=' + a_ship,
mimeType: 'json',
success: function(data) {
alert( data );
},
error: function() {
alert('Ajax Fail!');
}
});
PHP (File: add-data.php)
<?php
echo $_GET['oShip'];
What I've tried: I have tried using javascript's replace function in addData() function to replace the hyphen with an HTML number. Eg: a_ship = a_ship.replace('-', '-'). This seems to allow the code to partially work, but then gets rid of the number after the hyphen, which leads me into another problem.
Question:How do I pass hyphens from to jQuery's AJAX without causing error?
Change this:
mimeType: 'json',
to this:
contentType: 'json',
-Or-
removing mimeType altogether will solve this issue.
Replace your code with this and reply back with the results (editable fiddle here: http://jsfiddle.net/caLu0kj9/). Note the addition of the dataType in the ajax request and removal of the onclick event in the HTML code.
HTML:
<div id="click-number">12345678-9</div>
<button id="add-analysis-button">Add Data</button>
JavaScript:
$("#add-analysis-button").click(function(){
addData($( '#click-number').text());
});
function addData(a_ship) {
$.ajax({
type: 'GET',
url: 'models/add-data.php?oShip=' + encodeURIComponent(a_ship),
dataType: 'json',
beforeSend: function(jqXHR, settings) {
jqXHR.url = settings.url;
},
success: function(jqXHR, data) {
alert("SUCCESS! " + data + " " + jqXHR.url);
},
error: function(jqXHR) {
alert("FAIL! " + jqXHR.url);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With