No data receive in Jquery from php json_encode - javascript

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>

Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];

Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>

A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

Related

jQuery autocomplete ajax not working for autocorrection when wrong input is given

I'm trying to make a project similar to Google's search bar using Flask, Elasticsearch and jQuery that will automatically suggest based on input given and also automatically give correct suggestions when a wrong input is given. I've had success with the autosuggestion with correct spellings but when giving a wrong input, the correct suggestion data from Elasticsearch comes up in browser console but doesn't appear in the autocomplete drop-down. I inserted data into Elasticsearch using PySpark. I think the problem is related to the JS file but don't know if it's my JS file or the jquery-ui file. What am I doing wrong?
JS:
$(document).ready(function () {
const $source = document.querySelector('#source');
const $result = document.querySelector('#result');
const typeHandler = function (e) {
$result.innerHTML = e.target.value;
console.log(e.target.value);
$.ajax({
url: "/ajax_call",
type: 'POST',
dataType: 'json',
data: { 'data': e.target.value },
success: function (html) {
var data = html.aggregations.auto.buckets
var bucket = []
$.each(data, (index, value) => {
bucket.push(value.key)
});
console.log(bucket)
$("#source").autocomplete({
source: bucket
});
}
});
}
$source.addEventListener('input', typeHandler)
});
Correct Input:
Incorrect Input:
Correct data for Incorrect Input
Consider the following example.
$(function() {
const $source = $('#source');
const $result = $('#result');
$source.autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax_call",
type: 'POST',
dataType: 'json',
data: {
'data': request.term
},
success: function(html) {
var data = html.aggregations.auto.buckets;
var bucket = [];
$.each(data, (index, value) => {
bucket.push(value.key);
});
console.log(bucket);
response(bucket);
}
});
}
});
});
See More:
https://jqueryui.com/autocomplete/#remote-jsonp
https://api.jqueryui.com/autocomplete/#option-source

Attribute from class iteration return object instead of string

I have multiple divs that have an attribute on my page e.g.:
<div class="followCallout" id="follow_123" data-follow-id="123">
WHATEVER
</div>
....
<div class="followCallout" id="follow_456" data-follow-id="456">
WHATEVER
</div>
With a timer i loop through these divs and make an ajax call for each, to see if sth has changed:
function checkFollows() {
var t = setTimeout(checkFollows, 5000);
$('.followCallout').each(function(){
var $that = $(this);
var $id = $that.attr('data-follow-id');
var $url = $('#ajax-route-check-follow').val();
console.log($id); //THIS RETURN 123 etc...
$.ajax({
url: $url,
data: {
id: $id
},
type: "get",
contentType: false,
processData: false,
cache: false,
dataType: "json",
error: function (err) {
},
success: function (data) {
}
});
})
}
The $url is from here <input type="hidden" id="ajax-route-check-follow" value="/cCRM/web/app_dev.php/admin/_ajax/_checkFollow" />
However, the URL I'm sending looks like this:
http://localhost/cCRM/web/app_dev.php/admin/_ajax/_checkFollow?[object%20Object]&_=1497624513190
So instead of checkFollow?id=123 it gives me checkFollow?[object%20Object] so I assume sth is wrong with my ajax call? I am using the exact same call (w/o the $.each, only single calls though) on other parts as well. Where am I wrong?

Retrieving event and htmlInput element from a foreach using javascript or jquery

I managed to retrieve a dynamic element ID from inside a foreach and send it to a controller this way:
#using (Html.BeginForm("DeleteConfirmed", "Gifts", FormMethod.Post, new { #class = "form-content", id = "formDiv" }))
{
foreach (var item in Model.productList)
{
<input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" />
}
}
and here's the relevant script, pointing to the controller's ActionResult method in charge for item deletion:
function DeleteButtonClicked(elem) {
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
window.location.href = "/Gifts/DeleteConfirmed/" + itemID;
}}
Now, this works just fine, as itemID is correctly retrieved.
As I would like to add a #Html.AntiForgeryToken() to the form, the idea is to change the MVC controller's Actionmethod into a JsonResult adding a little Ajax to the script, allowing me to pass both itemID and token.
Something like:
function DeleteButtonClicked(elem) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
dynamic }Some
but I have no idea on how to add the 'event' to the element (this => elem) in <input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" /> that I am using to identify the item inside the foreach loop, in order to pass it to the script.
Above script obviously fails as there's no 'event' (provided this would end to be the only mistake, which I'm not sure at all).
Some help is needed. Thanks in advance for your time and consideration.
What you want to do is use jQuery to create an event handler:
$('input[type="button"]').on('click', function(event) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(this).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
});
Just make sure you render this script after your buttons are rendered. Preferably using the $(document).onReady technique.
Try the 'on' event handler attachment (http://api.jquery.com/on/). The outer function is shorthand for DOM ready.
$(function() {
$('.some-container').on('click', '.delete-btn', DeleteButtonClicked);
})

Get response code and parse to message via jQuery ajax

I have this structure:
HTML:
<input type="submit" name="_ninja_forms_field_7" class="ninja-forms-field popup-submit" id="ninja_forms_field_7" value="" rel="7">
JS:
$('#ninja_forms_field_7').click(function () {
var name = $('#ninja_forms_field_6').val();
var surname = $('#ninja_forms_field_6').val();
var emailAddress = $('#ninja_forms_field_8').val();
var eCommerceSiteUrl = $('#ninja_forms_field_9').val();
var post_datas = emailAddress = +emailAddress+ & name = +name+ & surname = +surname+ & eCommerceSiteUrl = +eCommerceSiteUrl;
$.ajax({
type: 'POST',
url: 'myserviceaddress',
data: post_datas,
success: function (answer) {
console.log(answer);
}
});
});
It working good. But I want, If service response code 0, parse a text in page.
How can I do it?
Just add the error: function() lines you see below beneath success:
$.ajax({
type: 'POST',
url: 'myserviceaddress',
data: post_datas,
success: function (answer) {
console.log(answer);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#result_div").html("textStatus");
}
});
Also, make sure you create a <div id="result_div"></div> so that the JQuery has a place to put the result in.

What's wrong with this jQuery Ajax/PHP setup?

I'm building a search app which uses Ajax to retrieve results, but I'm having a bit of trouble in how exactly to implement this.
I have the following code in Javascript:
if (typeof tmpVariable == "object"){
// tmpVariable is based on the query, it's an associative array
// ie: tmpVariable["apple"] = "something" or tmpVariable["orange"] = "something else"
var sendVariables = {};
sendVariables = JSON.stringify(tmpVariable);
fetchData(sendVariables);
}
function fetchData(arg) {
$.ajaxSetup ({
cache: false
});
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
});
}
And within script.php:
<?php
$data = json_decode(stripslashes($_GET['data']));
foreach($data as $d){
echo $d;
}
?>
What is it that I'm doing wrong?
Thanks.
Your PHP script is expecting a GET var called 'data'. With your code you're not sending that.
Try this:
if (typeof tmpVariable == "object"){
var data = {data : JSON.stringify(tmpVariable)}; // Added 'data' as object key
fetchData(data);
}
function fetchData(arg) {
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
success: function(response){
alert(response);
$("body").html(response); // Write the response into the HTML body tag
}
});
}

Categories

Resources