Ajax POST in Javascript is not working - javascript

I searched my problem but I cannot find any solution.
I guess it's really simple and I missing something really easy...but I'm stucked.
I have an html page with a php generated list of links, like that:
<?php
$val = "'"my file with spaces.txt"'";
echo 'click me';
?>
Where $val is different each time, depending on a SQL query.
And the file name is showed correctly, since I hover the mouse on the link and I can read on the bottom-left of the browser:
javascript:post_filename('my file with spaces.txt');
Clicking this link will call this javascript function:
<script type="text/javascript">
function post_filename(val){
$.ajax
({
url: 'myurl.php',
data: { filename: val },
type: 'POST'
});
}
</script>
But clicking on it, does nothing! No errors, just nothing happens.
With the dev tools (F12 on Chrome) I see that it's all ok... just the mypage.php doesn't show... is a page with graphics, part of the site!
I'm stucked... please help me!
Thanks so much

Your AJAX call was invalid, data should be either a String, Array or Object. Object is probably what you're after here from the start you've made
<script type="text/javascript">
function post_filename(val){
$.ajax
({
url: 'myurl.php',
data: {
filename: val
},
type: 'POST';
});
}
</script>

Try making data an object:
<script type="text/javascript">
function post_filename(val){
$.ajax
({
url: 'myurl.php',
data: { filename: val },
type: 'POST';
});
}
</script>

I tried your code, but I made some some revisions for it to work ( I just notice you had a semicolon after type, I believe that should be a comma, that the reason why you have unexpected token) my codes works using this:
<?php
$val = "'hello.txt'";
echo 'click me';
?>
on javascript
$('.click').click(function() {
$.ajax
({
url: 'myurl.php',
data: { filename: $(this).attr('file') },
type: 'POST'
})
.done(function (data) {
//check the output from your url
console.log(data);
})
.fail(function (jqXHR, textStatus) {
console.log("Request failed: " + textStatus);
});
});

Related

How to add post type from console... Error: Expected POST console html

My JQuery Ajax call gives error: EXPECTED POST
I am having the same issue as the guy in the link. I need to post instead of get, but I cannot change the ajax code directly. I have to do it from the console dynamically using JavaScript
I have been making changes in the index.html file via the console. Here is part of the index.html file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>For some reason, this form is submitted via AJAX, but there are a couple of bugs preventing that from working. Use your browser's console to fix it.</p>
<button type="button" onclick="alert('Form is broken, see Step 2');">Submit</button>
<h3>Results:</h3>
<div id='results'>
</div>
<script>
var success_callback = function(data) {
console.log(data);
$('#results')[0].innerHTML = data;
}
$('button').click(function(){
$.ajax('ajax.php', {
data: {submission: JSON.stringify({prop: $('text_area').val()})},
success: success_callback
}
);
});
</script>
I know all I have to do is add type: 'POST', right before data. If I could change the index.html file directly, I would. but I can't, so how can I do this using JavaScript during runtime from this
console
You could remove the click listener and add your own with the modified code:
$('button').off('click').click(() => {
$.ajax('ajax.php', {
data: { submission: JSON.stringify({ prop: $('text_area').val() }) },
success: success_callback,
type: 'POST'
})
})
Since success_callback is defined in the global scope, it should be callable by your code too.
Another option would be to monkey-patch $.ajax.
Very dirty, but it will do the job too... Something like this:
const oldAjax = $.ajax
$.ajax = function (url, opts) {
if (url !== 'ajax.php') return oldAjax.apply(this, arguments)
return oldAjax.call(this, url, { ...opts, type: 'POST' })
}
This will replace $.ajax by your own function which will then either just call the original function with unmodified arguments if url isn't ajax.php , or, if it is ajax.php, insert type: 'POST' into the options object.
See also: https://www.audero.it/blog/2016/12/05/monkey-patching-javascript/#using-monkey-patching-to-change-a-method
(Note: This is not the method of choice in normal circumstances!)

jQuery Ajax post is not working

I know that there is a lot of questions like this out there, but I have been surfing them and other website for like 4 hours trying to figure this out. I am trying to get main.js to post the data via ajax and then the php should echo that data. If it does not work, it will echo "null". It keeps echoing "null" instead of "John". I know that the jquery and main.js links work, I have tested them. Here is main.js:
$(document).ready(function(){
$.post("index.php", { test: "John"} );
});
And here is the php part of index.php:
<?php
$var = "null";
if(isset($_POST['test'])) {
$var = $_POST['test'];
}
echo $var;
?>
I hope you can solve my problem, and thank you in advance.
You are missing the callback function with the response from the server.
$.post( "index.php",{ test: "John"}, function( data ) {
alert(data);
});
Or you can do something like this:
$.post( "index.php",{ test: "John"})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Please check the documentation Documentation
Give this a shot
jQuery
var available agent = 1;
jQuery.ajax({
type: "POST",
url: "your-url",
data: available_agent,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data){
owner = data['round_robin_agent'];
},
error : function () {
alert("error");
}
});
PHP Script
public function round_robin() {
//Do your work
$round_robin_agent = 'rob';
$results_array = array(
'round_robin_agent' => $round_robin_agent
);
return json_encode($results_array);
}
Download HTTP Trace chrome extension, traceback ajax call and share a screenshot.
https://chrome.google.com/webstore/detail/http-trace/idladlllljmbcnfninpljlkaoklggknp

jquery function not redirecting url

I am working with codeigniter and jquery. I am using ajax to send some info to a codeigniter function to perform a db operation , in order to update the page. After the operation is complete I am trying to refresh the page. However the refresh works inconsistently and usually I have to reload the page manually. I see no errors in firebug:
var message = $('#send_message').val()
if ((searchIDs).length>0){
alert("searchIDs "+searchIDs );
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
success: function(){
alert("OK");
},
complete: function() {
location.href = "pan_controller/my_detail";
}
})
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("OK");
location.href = "pan_controller/my_detail";
});
} else { alert("nothing checked") }
break;
How can I fix this?
addendum: I tried changing to ;
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "pan_controller/my_detail";
});
}
})
This is just defaulting to the website homepage. again, no errors in firebug
Add the window object on location.href like this:
window.location.href = "pan_controller/my_detail";
Try to use full path like
$.ajax({a
type: "POST",
url: "YOURBASEPATH/AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "YOURBASEPATH/pan_controller/my_detail";
});
}
})
BASEPATH should be like this "http://www.example.com"
Try disabling the csrf_enabled (config/config.php) and trying it. If that works, then re-enable the protection and, instead of compiling data yourself, serialize the form; or, at least include the csrf hidden field codeigniter automatically adds. You can also use GET to avoid the CSRF protection, but that's least advisable of of the solutions.

Jquery ajax call a php script with require once

I have an ajax request like :
$.ajax({
type: "GET",
url: "services/Test.class.php",
data: "call=getTest",
success: function (data) {
alert(data);
},
error: function (response) {
alert("Error getting php file");
}
});
So, in my class ( Test.class.php ), I have a getTest() function and a require_once('OtherPHP'),
When I test this code, I have an error in require once :
No such file or directory
in my alert(data)
how can I fix it?
It seems like you've included a wrong path of OtherPHP file in Test.class.php. Use file_exists() function to make sure that given path really exists before including/requiring in Test.class.php
if (file_exists(`OtherPHP.php`)) {
require_once(`OtherPHP.php`)
} else {
echo "The file `OtherPHP.php` does not exist";
}
You cant able to call the class directly from ajax,
create new php file say test.php
in test.php
include("Test.class.php");
$test = new Test();
$test ->getTest(); //print the getTest outpout here
Javascript:
$.ajax({
type: "GET",
url: "test.php",
.....

How to pass value from javascript to php in same page

Im tying to implament a preloader for swf based on this Post, but im getting trouble passing the javascript value to a php variable.
<script type="text/javascript">
var swfJSPreLoaderConfig = {
'assets':['swf/test.swf'],
'assetLoaded': function( asset){
alert(asset);
},}
</script>
The alert in the above code shows only when the swf file test.swf is fully downloaded. the value that im trying to get in php is asset ( this value contain the swf file path, in this example is swf/test.swf. the alert fires always when the swf files is fully dowloaded and it works very good.)
i tried something like this to get it in a php variable. but no lucky.
$filename = $_REQUEST['asset'];
also i tired using ajax but nothing.
<script type="text/javascript">
var swfJSPreLoaderConfig = {
'assets':['swf/test.swf'],
'assetLoaded': function( asset){
$.ajax ({
type: "post",
url: "index.php",
data: { 'asset': asset },
success: function()
{
alert(asset);
}
});
},}
</script>
and then
$filename = $_REQUEST['asset'];
Whats worng?
Try this,
data: { 'asset': asset },
success: function(response)
{
alert(response);
}
instead of,
data: { 'asset': asset },
success: function()
{
alert(asset);
}
});
PHP:
echo $filename = $_REQUEST['asset'];
Change from
url: "index.php"
to
url: "index.php?asset="+asset
Then in PHP, use:
echo $_GET['asset'];
to confirm that you are sending the correct value

Categories

Resources