Unexpected characters in image url in ajax response Javascript - javascript

In My Codeigniter web application I'm using an ajax function to get some data from the database inorder to show it in the view.The data from database contains an image url and other fields.
My problem is that when I get the data in ajax success function, the image url looks like this:
<button id='product-1301' type='button' value=1301 class='blue' ><i><img src='assets\/uploads\/thumbs\/default.png'></button>
Since the url contains these characters \ my view is not rendering properly. I tried using stripslash function to remove this. But didn't work. I didn't know where am going wrong.
my ajax function
$.ajax({
type: "get",
url: "index.php?module=pos&view=ajaxproducts1",
data: {category_id: cat_id, per_page: p_page},
dataType: "html",
success: function(data) {
var x= data;
alert(x);
if(data!=1)
{
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
}
else
{
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
Controller
function ajaxproducts1()
{
$mn;$data1;
$img="assets/uploads/thumbs/default.png"; //this is my image path, when this comes in ajax success,\ character adds
$img=str_replace('\"', '', $img);
if($this->input->get('category_id')) { $category_id = $this->input->get('category_id'); }
if($this->input->get('per_page')) { $per_page = $this->input->get('per_page'); }
if($item = $this->pos_model->getProductsByCategory($category_id,$per_page))
{
foreach ($item as $i)
{
$button="<button id='product-".$i->id."' type='button' value=".$i->id." class='blue' ><i><img src='".$img."'><span><span>".$i->name;
$mn=$mn.$button;
}
$data1=$mn;
}
else
{
$data1=1;
}
echo json_encode($data1);
}
Can anyone help me with this ?

Try this:
// use an array to gather up all the values
// call encodeURIComponent() on the variables before adding them
// join them all together and pass them as "data"
var tempVars=['module=pos&view=ajaxproducts1'];
tempVars.push('category_id='+encodeURIComponent( cat_id ));
tempVars.push('userInfo='+encodeURIComponent( p_page ));
var sendVars=tempVars.join('&');
$.ajax({
type: "get",
url: "index.php",
data: sendVars,
dataType: "text",
success: function(data) {
var x = data;
alert(x);
if (data != 1) {
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
} else {
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});

My issue was solved by using jQuery.parseJSON function.

Related

Using AJAX to post data into API

I have a script that uses AJAX to comunicate with PHP based API.
First part loads trade history:
$(document).ready(function () {
var orders = $('#History ul');
var user = "<?php echo $user; ?>";
$.ajax({
type: "GET",
url: "api.php",
data: {
user: user
},
success: function (response) {
console.log(response);
var res = JSON.parse(response);
$.each(res, function (index, value) {
console.log(value);
if(value['PL']>=0){
orders.append("<li style=\"color:green;\">" + value['User'] + "</li>");
}else{orders.append("<li style=\"color:red;\">" + value['User'] + "</li>");}
});
}
});
Second part posts a trade to database:
$("#submit").click(function(){
//event.preventDefault();
var oPrice = newOrder.elements["oPrice"].value;
var cPrice = newOrder.elements["cPrice"].value;
var oType = newOrder.elements["oType"].value;;
var oSymbol = newOrder.elements["oSymbol"].value;
var oAmount = newOrder.elements["oAmount"].value;
var json ={
'user': user,
'oPrice': oPrice,
'cPrice': cPrice,
'oType': oType,
'oSymbol': oSymbol,
'oAmount': oAmount};
alert(JSON.stringify(json)); //---check zda je naplněný
$.ajax({
type: "POST",
url: "api.php",
data: json,
success: function (response) {
alert(response);
}
});
});
The problem is, that when i press the button and send json, its missing the 'user' data and looks like this:
TraderBook.php?oPrice=1&cPrice=1&oType=LONG&oSymbol=1&oAmount=1
I have no idea why does ajax exclude it. The json variable has it filled out
I think your problem might be here
$(document).ready(function () {
var user = "<?php echo $user; ?>";
var is the JS scoping declaration. So you're limiting your user value to just the anonymous function being triggered by the page DOM load completing. What you should do is try scoping it outside the function
var user; //global scope
$(document).ready(function () {
user = "<?php echo $user; ?>";
This way, when your $("#submit").click(function() fires, there's a value to feed into your script.
I was wrongchecking the problem a mistook data from a form for the json. Problem was inside the API --> There was a tabulator in a SQL command..
Thanks to everyone for suggestions.

Unable to access to my json data in javascript

Working in a jquery request in JSON but I have some problem to access to my data.
My request is :
$(document).ready( function () {
$("#client").change( function() {
$.ajax({
type: "GET",
url: "jsonContacts.php",
data: "q="+$("#client").val(),
success: function(data){
document.form.contactClient.options.length=0;
for(var i=0; i<data.length; i++) {
document.form.contactClient.options[i]=new Option(data[i].prenom, data[i].id, false, false);
}
document.form.contactClient.options[i]=new Option("End", i, false, false);
}
});
});
});
When I put
alert(data[1].prenom);
It gives me undefined :/
Here an example of my json :
[{"id":"1","prenom":"Maxime","nom":"Xnate"},{"id":"3","prenom":"Test_prenom","nom":"Test_nom"}]
My request displays two empty options and one option "End", so it goes well across array but can't get any data.
So do you have any idea about the access of the data ?
Thanks
EDIT :
My json encoding
$json = array();
while($contact = $requeteContact->fetch()) {
array_push($json, array("id" => $contact['idContact'],
"prenom" => $contact['CTC_Prenom'],
"nom" => $contact['CTC_Nom']));
}
echo json_encode($json);
Working :
$(document).ready( function () {
$("#client").blur( function() {
$.ajax({
type: "GET",
url: "jsonContacts.php",
data: "q="+$("#client").val(),
success: function(data){
document.form.contactClient.options.length=0;
for(var i=0; i<data.length; i++) {
document.form.contactClient.options[i]=new Option(data[i].prenom + " " + data[i].nom, data[i].id, false, false);
}
document.form.contactClient.options[i]=new Option("End", i, false, false);
}
});
});
});
Your data is probably just returned as a string. You can solve this in several ways:
1) use getJSON.
$.getJSON('http://..',{q:$("#client").val()},function(result){
})
2) Parse the string as JSON
JSON.parse(data);
3) Set the dataType to 'json'. If you do this, you will have to sett the content-type on the server side to 'application/json'. In PHP this would look like this:
header('Content-Type: application/json');

Set the function itself to the url in AJAX?

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

Pass Array FROM Jquery with JSON to PHP

hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});

cant pass the value from data using ajax

this is very frustrating, 2 hours passed and still can't get it working.
I just want to test on how to pass a value to my method using ajax.
Code:
Javascript
$('#form-payment').submit(function () {
var request = $.ajax({
url: "<?php echo site_url(array('home', 'update_credit_card')); ?>",
type: "POST",
data: 'someNumber=12'
});
request.done(function(data) {
console.log('boom' + data);
});
request.fail(function(jqXHR, textStatus) {
console.log('error' + textStatus);
//print_r(jqXHR);
});
});
PHP
function update_credit_card()
{
var_dump($_POST['someNumber']);//returns NULL value
$somenumber = $_POST['someNumber'];
if ($somenumber == '12') {
print "Number is 12";
} else {
print "Number is not 12";
}
}
The code is very simple but for the life of me can't get it to work. T_T.
Badly need help.
You can also use like this.
var values={};
values['arg1'] = 1;
values['arg2'] = 2;
$.ajax({
type:'POST',
url:'....',
data: values,
success:function(){}
});

Categories

Resources