I have this code:
<a href="#">
<i class="icon-heart" id="icon_heart" value="20"></i>
</a>
var some_value = $("#icon_heart").attr("value");
$('[id=id_heart]').click(function() {
$.ajax({
url: "<?=base_url(); ?>controller/save",
type: "post",
data: { some_value: some_value },
success: function(dat){
alert(dat);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
PHP:
function save()
{
$post = $this->input->post();
$some_value = $post['some_value'];
$dtl['some_field'] = $some_value;
$dtl['date_insert'] = date('Y-m-d H:m:s');
$this->db->insert('resep_like',array_filter($dtl));
$this->db->set('is_like', 'is_like+1',FALSE);
$this->db->where('some_field', $some_value);
$this->db->update('some_table');
echo "success";
}
The insert and update queries is success, but the AJAX response returns error: status code 500 internal server error. Why can that be? It's successful but the result is error, and the echo from PHP is not displayed. How can i handle the response if it success but the AJAX response show error
Dont know if this the best answer or not..
I just solve this problem by change the url: <?=base_url();?>controller/save to url: <?=base_url();?>save.php
I point url of my ajax to my single file of php placed in root of document and not using the ci controller again to do the insert and update queries, then voila its work
If there a better method of this, please let me know it.
Thanks
Related
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];
I am creating an Android application using Intel XDK and for some reason It seems to work on the emulator but on the mobile it seems to fail. Below are the screenshots of what it looks like on the emulator and on the device.
Both are using the exact same code and are pointed to the correct database and server. Below is the code I'm using, the PHP and JavaScript code.
function getSessionData(callback) {
$.ajax({
url: 'http://sm.script47.net/api/v1/modules/sessionData/sessionData.php',
"type": "GET",
dataType: "json",
async: true,
success: function (data) {
callback(data);
},
error: function (xhr, textStatus, error) {
alert(xhr.statusText);
alert(textStatus);
alert(error);
},
});
}
Then in another file called home.js.
window.onload = function () {
getSessionData(function (data) {
window.token = data.token;
window.userID = data.userID;
window.username = data.username;
window.emailAddress = data.emailAddress;
alert(window.userID);
getElement("userDetails").innerHTML = "Hello <strong> " + window.username + "</strong>"
});
};
Then to get the session data I'm using the below on a PHP server hosted by namecheap (shared hosting).
<?php
session_start();
// I added the code below in the comment block to try and make it work.
/******************************************************/
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
/******************************************************/
$sessionData = array(
"token" => htmlspecialchars(trim($_SESSION['token'])),
"userID" => htmlspecialchars(trim($_SESSION['userID'])),
"username" => htmlspecialchars(trim($_SESSION['username'])),
"emailAddress" => htmlspecialchars(trim($_SESSION['emailAddress']))
);
echo json_encode($sessionData, JSON_PRETTY_PRINT);
I don't know why it won't work or what is causing it to not work which is why I'm not sure what the fix is. I've talked to the namecheap customer support and they said AJAX requests should work, and they do as I use them to login/register but getting the JSON session data on an actual mobile device doesn't seem to work. Also the success/error callback doesn't return anything either.
I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.
I am trying to make an ajax call within the success of another ajax call.
This is working perfectly in localhost but not on the server.
Here's what I am doing.
FB.api('/me', function(response) {
$.ajax({
type:"POST",
url:"http://gagsterz.com/index.php/home/InsertUser",
data:{id: response.id,name:response.name,at:self.access_token},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
$('#error').html(xhr.responseText);
},
success:function(data)
{
FB.api('/me/friends',function(response) {
if(response.data)
{
countfriends = 0;
filedata="";
self.friendsID = new Array();
self.friendsName = new Array();
$.each(response.data,function(index,friend) {
filedata+=friend.id+"\t"+friend.name+"\t"+self.UID+"\n";
countfriends++;
self.friendsID.push(friend.id);
self.friendsName.push(friend.name);
});
if($.trim(data)=="InsertFriends")
{
$.ajax({
url:"http://gagsterz.com/index.php/home/InsertFBFriends",
type:"POST",
data: {fdata : filedata },
success:function(r)
{
alert("success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText); },
});
}
});
});
Now when I click the button.The first ajax call(parent) works fine and returns me InsertFriends as answer from the php script.Now the ajax request present in the if condition of InsertFriends does not work correctly and the xhr.responseText is empty string. Now I don't know why it is not working properly. To make it simple I just echoed abc on the server side script but I don't know whats wrong with this.
I get the following error in the Chrome Network Tab.
So why it is not working ?
I just change the requesttype from POST to GET and it worked.