Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyphen not allowing jQuery AJAX call to work properly

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('-', '&#45;'). 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?

like image 881
aCarella Avatar asked Oct 24 '25 18:10

aCarella


2 Answers

Change this:

mimeType: 'json',

to this:

contentType: 'json',

-Or-

removing mimeType altogether will solve this issue.

like image 114
CodeGodie Avatar answered Oct 26 '25 08:10

CodeGodie


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);
        }
    });
}
like image 22
Rick Burns Avatar answered Oct 26 '25 06:10

Rick Burns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!