Ajax code for cross-domain request fails - javascript

I need to send data through AJAX to another domain. I use the following code which alerts error.
$(document).ready(function(){
$('p').click(function(){
$.ajax({
url:"http://tarjom.ir/demo/javascript/get.php?callback=?",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
type : "GET",
data: "username=mostafa&url="+window.location,
success:function(json){
// do stuff with json (in this case an array)
alert(json);
},
error:function(){
alert("Error");
},
});
});
});
I want each click on <p> tag be reported to a file called get.php on another server. This file would save the click record+the time of the event into a DB.
Due to development stage, I have added an alert(); to the code, to alert whatever received from get.php, but I ONLY get alerted 'error'.
Here is the get.php code:
<?php
if($_POST['username'] != "")
{
$site = new mysqli('localhost', 'tarjomir_mostafa', 'securefiction1916', 'demo');
$stmt = $site->prepare("INSERT INTO demo (url) VALUES(?)");
$stmt->bind_param('s', $a);
$stmt->execute();
$stmt->close();
echo json_encode("success");
}
?>

try this:
$(function(){
$.ajax({
url:"http://tarjom.ir/demo/javascript/get.php",
dataType: 'jsonp',
type : "GET",
data: "username=mostafa&url="+window.location,
jsonpCallback:"myFunction"
})
.done(function(json){
// do stuff with json (in this case an array)
alert('done ' + json);
})
.fail(function(){
alert("Error");
});
});
And the response for http://tarjom.ir/demo/javascript/get.php be something like:
myFunction({"data": "mydata" })

Related

How to get POST data using Jquery AJAX

I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>

Delete post using $.ajax

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID
<button type="button" onclick="submitdata();">Delete</button>
When click this button then following $.ajax process running.
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:datastring,
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
And delete.php is
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_GET['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
This code not working post not deleted. Please how do I do?
You likely want to not only match the "GET" you use in your PHP but also add the ID to the button
<button class="del" type="button"
data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>
using $.get which matches your PHP OR use $.ajax({ "type":"DELETE"
$(function() {
$(".del").on("click", function() {
$.get("delete.php",{"post_id":$(this).data("id")},
function(html) {
alert(html);
}
);
});
});
NOTE: Please clean the var
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Using ajax DELETE with error handling
$(function() {
$(".del").on("click", function() {
$.ajax({
url: "delete.php",
method: "DELETE", // use "GET" if server does not handle DELETE
data: { "post_id": $(this).data("id") },
dataType: "html"
}).done(function( msg ) {
$( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
In the PHP you can do
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_REQUEST["post_id"] ....
}
since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET
here is how it sould be
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_POST['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
for the JS code
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:{"post_id":post_id},
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
here i've supposed thqt the give you the real id post you're looking for !!
The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request
Change:
type:"POST",
url:"delete.php",
data:datastring,
to
type:"DELETE",
url:"delete.php?" + datastring,
in PHP
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
$id = $_REQUEST["post_id"];
// perform delete
}
DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.
Follow #roberts advise and also:
You should have a way to handle errors eg.
to your ajax code add this:
error:function(e){
alert(e.statusText)// if you like alerts
console.log(e.statusText)// If you like console
}
You should also check your error logs. Assuming you use apache2 and linux
execute this in terminal:
tail -f /var/log/apache2/error.log
This gives you a very elaborate way to code. You also eliminate the problem of trial and error.

No alert from Ajax call

I´m trying to alert some data from a Ajax call. Can anyone spot what I am doing wrong?
PHP
while($row = $stmt->fetch()){
echo json_encode($row);
}
echo "Done!";
Result from Json_encode / Network Preview
{"flakId":"21098-10_flak-2"}{"flakId":"21098-10_flak-1"}Done!
JS
if(chosenObjNr){
alert('I CAN see this alert')
$.ajax({
url:'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
error: function (data){ alert("failed, i can see this!");},
success: function(data){
alert('I cannot see this alert!');
alert(data);
var data0;
data0 = data[0];
alert(data0);
var falkId;
flakId = data[0];
alert(flakId);
console.log(data);
}
});
};
RESULT
No alert and nothing in the console.
The problem is, that the success part of the ajax never will run. You defined the dataType as a json, so it expecting json. Your PHP is echos 2 json and an unwanted string.
So, to check what is your error add the fail function as Sina sad in the comment:
if (chosenObjNr) {
alert('I CAN see this alert')
$.ajax({
url: 'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
}).done(function (data) {
alert('I cannot see this alert!');
//Do what you want to do here
}).fail(function (msg) {
alert('An error occured: ' + msg.statusText);
});
}
And, if you want to fix your .php remove the echo 'Done'; part, and add your records to an array, and when its done, encode it to json:
$return = array();
while ($row = $stmt->fetch()) {
$return[] = $row;
}
echo json_encode($return);

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Categories

Resources