Post an XML request to the URL using JavaScript - javascript

I have an API URL where I want to post the XML data. My API URL only accept XML. I am posting my XML to URL using ajax.
Here is my XML
<?xml version="1.0" encoding="UTF-8"?>
<data>
<lead>
<key>*****</key>
<id>*****</id>
<data6>Lead has been updated. merchant</data6>
</lead>
</data>
and my JavaScript code is:
<button type="button" onclick="loadXMLDoc()">Add Quote</button>
<script>
function loadXMLDoc() {
var data = "<data><lead><key>*****</key><id><?php echo $id; ?></id><data6>Lead has been updated. merchant</data6></lead></data>";
$.ajax({ type: "POST",
url: "https://inspire.flg360.co.uk/api/APILeadCreateUpdate.php",
data: data,
contentType: "text/xml",
dataType: "xml",
cache: false,
error: function() { alert("No data found."); },
success: function(xml) {
alert("it works");
alert($(xml).find("project")[0].attr("id"));
}
});
}
</script>
When I click the add quote button then it goes into error block of the ajax function. I have given the data posting URL and XML data in the code.

I assume you are using this snippet inside a wordpress template.
The first thing is, you should enclose all your codes with jQuery No Conflict
The reason why it does not do anything is $ is not being recognized. So, replace $ by jQuery and then your code will work properly.
Make sure you have declared the $id variable inside a PHP block right before the script.
I have ran it here
Hope it works!

Related

Update Span Element with Ajax and php

Hello again stack overflow
I have a simple PHP file (countsomething.php) that looks up a number and echo's it.
How do I get ajax to update a simple span element on my HTML page.
I've tried triggering the ajax on page load with : <body class="skin-blue" onload="updateCDNonts();">
The JS
function updateCDNonts() {
$.get("x.x.x.x:8080/getliveontscdn.php=", function(result){
$("#countonts").html(result)};
}
The HTML
<span id="countonts" class="info-box-number">0</span>
Can someone point me in the right direction ?
You have a few issues with your code i have tried to point them all out below for you:
function updateCDNonts() {
$.get("x.x.x.x:8080/getliveontscdn.php", function(result){ //removed equals from url
$("#countonts").html(result); //removed curly brace that shouldn't be there
}); //added missing bracket and semicolon
Also as someone else noted watchout for cors if your url is different.
I managed to get it working. I changed my php script to return a json, here is the json: {"cdnonts":"144","eagonts":"0","stamonts":null,"foxonts":null,"pentonts":null,"topponts":null,"wickhamonts":null}
And in the html I did the following
<script language="javascript">
window.onload = function() {
$.ajax({
type: 'GET',
url: 'countallonts.php',
dataType: "json",
data: { get_param: 'cdnonts' },
success: function(data){
$('span#cdnonts').html( data.cdnonts);
$('span#eagonts').html( data.eagonts);
}});}
</script>
Although I am not sure why it works, because I expected data variable to return just the "cdnonts" object, but I suspect it parses all of the objects instead?
Thank you for you help.

script doesn't load after ajax response

I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.
$.ajax({
type: "get",
url: "{{url('searchByCheckbox')}}",
dataType: 'html',
success: function(html)
{
$(".infinite-scroll").html(html)
}
});
But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script.
suppose the html response like this :
<script>
alert()
</script>
// html
How do i make it work?
I put the script above the html page which i'm getting as response.
(those who are marking the Question as duplicate should read at least what i want and what they wanted )
Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.
The best solution is to return the data from your ajax call as a json
To do that you should:
1- add a dataType to your ajax parameter as the below:
$.ajax({
type: "get",
dataType: "json",
2- In the php file handling the ajax call, you must resurn the values as a json as below:
Assume that currently you are doing the following:
echo $html
You should change it to match the below:
$retArr = array(
"html" => $html, //Your html code without the javascript function
"jsFunc" => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;
And then your ajax success must be as the below:
success: function(data)
{ //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
data.jsFunc // Your javascript function params
$(".infinite-scroll").html(data.html) ;
}

load external xml file into js variable to be using jquery

I am trying to load an xml file containing config for a single page apps logic using jquery.
I can get the console to show the xml has been loaded and even display the xml in console but have yet to be able to get the xml to be declared as a string variable. I am using the following code
$.ajax({
type: "GET",
url: "dummy.xml",
dataType: "xml",
success: function (url) {
console.log('started function xml');
console.log(url);
// Parse the xml file and get data
parseXMLConfig;
}
});
I have a separate function to parse the xml using jquery which works if I declare the xml directly in the JavaScript but need to separate the xml and js for later development efforts.
Can anyone tell me how to set the js object to a variable for use elsewhere in scripts.
You can do something like this
$.ajax({
type: "GET",
url: "dummy.xml",
success: function (xmContent) {
console.log(xmContent);
xmlDoc = $.parseXML(xmContent),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );
console.log($title );
}
});
For more detail refer DOC

AJAX post variable to PHP not working

I am trying to get a jQuery variable to a PHP variable. I have looked it up but can't find a solution. I have the following jQuery:
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success');
}
});
When I console.log te "eventID" it correctly displays the number.
My PHP code is in the index.php. This is also where the .eventRow class is.
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
However nothing happens. The console.log just displays: "Number: " Is there something wrong with the code? Thanks for your help!
EDIT: Could it be the problem that the index.php is already loaded before I click on the button? Because this php code is in the index.php and thus the $phpEventId is not yet set.
In your Ajax, the type: "POST" is for jQuery prior to 1.9.0. If you're using the latest jQuery, then use method: "POST".
If you're using the latest jQuery and you don't specify method: "POST", then it defaults to method: "GET" and your PHP needs to capture it with $_GET['phpEventId'];.
After reading your update, let's try one thing. Change your PHP to return something meaningful to Ajax:
<?php
$phpEventId = $_POST['phpEventId'];
echo $phpEventId;
?>
Then try to capture the PHP response in your Ajax:
$.ajax({
url: "index.php",
method: "POST",
data: {'phpEventId': eventID },
success: function (result) {
alert("result: " + result);
}
});
This is just a part of your code, and the problem is somewhere else. In this context your code works just fine:
<div class="eventrow" id="1">This</div>
<div class="eventrow" id="2">That</div>
<script>
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index-1.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success: '+eventID);
}
});
});
</script>
With the matching index-1.php:
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
Not sure though why do you print javascript code (console.log) into an ajax response here...
Error Is Visible Even Here
According to WebZed round statistic report, this error was visible over 84% of web-developers.
Failed to post data to PHP via JQuery while both frameworks and codes were updated.
Possible Solutions Available Today
Try using other methods for posting because JQUERY and AJAX libraries are not as efficient as shown in the surveys.
New frameworks are available which can do better with PHP.
Alternative method is to create a post request via $_GET method.
Regular HTML5 supports <form></form> try method="post". For security reasons try using enctype="" command.
Try using React Native https://nativebase.io/

ajax parse xml response function wont recognize XML file URL

im using the following code from another solution on here
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
dataType: "xml",
url: "xmlfile.xml",
success: function(xml){
$("#output").append($(xml).find("address"));
}
});
});
</script>`
and if i use the local xmlfile.xml file it works fine, but when i try to run the same function with the xml file hosted elsewhere, it stops working:
http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm?zws-id=X1-ZWz1ebcem1ra4r_10irx&zpid=48749425
I tried encoding the URL using escape() and encodeURIComponent()
neither of those worked.
what am i doing wrong? why does the function work with a local xml file but breaks when i use the other URL?

Categories

Resources